Tạo Custom Skills cho Claude — Hướng dẫn từ A đến Z
Điểm nổi bật
Nhấn để đến mục tương ứng
- 1 Thực hành được liền: Một Custom Skill gồm ba thành phần chính: SKILL.md — Mô tả skill: mục đích, capabilities, và hướng dẫn sử dụng. Quy trình từng bước trong phần này giúp bạn bắt đầu ngay mà không cần kinh nghiệm chuyên sâu.
- 2 Thành thật mà nói: SKILL.md là "contract" mô tả skill của bạn. Phương pháp này hiệu quả trong hầu hết trường hợp, nhưng bạn cần điều chỉnh cho phù hợp ngữ cảnh riêng.
- 3 Không thể bỏ qua: import anthropic import os import json from dataclasses import dataclass from typing import Optional class. Đây là kiến thức nền tảng mà mọi người làm việc với AI đều cần hiểu rõ.
- 4 Khai thác tối đa công cụ AI: class MarketDataFetcher: """Handles all data fetching and calculations""" def getstockdataself, ticker: str,. Bí quyết nằm ở cách bạn cấu trúc yêu cầu — prompt càng rõ ràng, output càng sát nhu cầu thực tế.
- 5 Thành thật mà nói: """ Cấu trúc thư mục để publish skill: my-vn-market-skill/ ├── SKILL.md Skill description ├── CONNECTORS.md API. Phương pháp này hiệu quả trong hầu hết trường hợp, nhưng bạn cần điều chỉnh cho phù hợp ngữ cảnh riêng.
Custom Skills cho phép bạn mở rộng khả năng của Claude với domain knowledge và tool access riêng của tổ chức bạn. Thay vì viết prompt dài và phức tạp mỗi lần, bạn đóng gói logic đó thành một Skill có thể tái sử dụng — giống như tạo một "chuyên gia ảo" trong lĩnh vực cụ thể.
Kiến trúc Custom Skill
Một Custom Skill gồm ba thành phần chính:
- SKILL.md — Mô tả skill: mục đích, capabilities, và hướng dẫn sử dụng
- CONNECTORS.md — Định nghĩa API connections và external tools
- Implementation Code — Logic xử lý thực tế (Python/Node.js/etc.)
Bước 1: Thiết kế SKILL.md
SKILL.md là "contract" mô tả skill của bạn. Claude đọc file này để hiểu mình đang làm gì:
# SKILL: Vietnamese Market Analyzer
## Purpose
Analyze Vietnamese stock market data, provide investment insights,
and generate reports in Vietnamese for retail investors.
## Capabilities
- Fetch real-time stock prices from HOSE, HNX, UPCOM
- Calculate technical indicators (RSI, MACD, Bollinger Bands)
- Analyze fundamental ratios (P/E, P/B, ROE, debt ratios)
- Generate buy/hold/sell recommendations
- Create Excel reports and charts
- Translate financial jargon to plain Vietnamese
## Invocation
Users can invoke this skill by asking about:
- "Phân tích cổ phiếu [TICKER]"
- "Khuyến nghị đầu tư tháng này"
- "So sánh [TICKER1] và [TICKER2]"
- "Tạo báo cáo portfolio"
## Constraints
- Only analyze publicly traded Vietnamese companies
- Always include risk disclaimers
- Data freshness: max 15 minutes delay
- Cannot execute actual trades
## Output Formats
- Quick analysis: 3-5 bullet points
- Full report: structured markdown with tables
- Excel file: when user requests downloadable report
## Example Interaction
User: "Phân tích nhanh VNM"
Skill: Fetches VNM data, calculates key metrics, provides
structured analysis with buy/hold/sell recommendation
## Version
1.0.0
## Author
Your Name / Organization
Bước 2: Định nghĩa CONNECTORS.md
CONNECTORS.md mô tả các external services skill của bạn sử dụng:
# CONNECTORS: Vietnamese Market Analyzer
## Connector: HOSE Market Data API
- Type: REST API
- Base URL: https://api.example-vn-market.com/v1
- Auth: Bearer token (env: VN_MARKET_API_KEY)
- Endpoints used:
- GET /stocks/{ticker}/price — current price + OHLCV
- GET /stocks/{ticker}/history?days=365 — historical data
- GET /stocks/{ticker}/fundamentals — P/E, P/B, EPS, etc.
- GET /market/indices — VN-Index, HNX-Index, UPCOM-Index
## Connector: Financial Calendar
- Type: REST API
- Base URL: https://api.example-calendar.com
- Auth: API Key header (env: CALENDAR_API_KEY)
- Endpoints used:
- GET /events?market=VN&days=30 — upcoming earnings, dividends
- GET /dividends/{ticker} — dividend history
## Connector: News Feed
- Type: RSS / REST
- Source: CafeF, VnExpress Finance, VietStock
- Rate limit: 100 req/hour
## Environment Variables Required
- VN_MARKET_API_KEY: Market data API authentication
- CALENDAR_API_KEY: Financial calendar API
- ANTHROPIC_API_KEY: For Claude API calls
- REDIS_URL: For caching market data (optional)
## Data Caching Strategy
- Stock prices: 15-minute cache (Redis)
- Fundamentals: 24-hour cache
- Historical data: 1-hour cache
Bước 3: Implementation — Skill Core
import anthropic
import os
import json
from dataclasses import dataclass
from typing import Optional
class VietnameseMarketSkill:
"""Main skill class — handles all market analysis"""
SKILL_DESCRIPTION = """
You are a Vietnamese stock market analyst. You have access to real-time
market data tools and can analyze stocks listed on HOSE, HNX, and UPCOM.
Always respond in Vietnamese unless asked otherwise.
Provide clear, actionable analysis with appropriate risk disclaimers.
"""
def __init__(self):
self.client = anthropic.Anthropic()
self.tools = self._define_tools()
self.data_fetcher = MarketDataFetcher()
def _define_tools(self) -> list:
return [
{
"name": "get_stock_data",
"description": "Lấy dữ liệu cổ phiếu: giá hiện tại, OHLCV, và thông tin cơ bản. Dùng khi phân tích cổ phiếu cụ thể.",
"input_schema": {
"type": "object",
"properties": {
"ticker": {
"type": "string",
"description": "Mã cổ phiếu, ví dụ: VNM, VIC, HPG"
},
"include_history": {
"type": "boolean",
"default": False,
"description": "Có lấy dữ liệu lịch sử 1 năm không"
}
},
"required": ["ticker"]
}
},
{
"name": "calculate_technical_indicators",
"description": "Tính toán các chỉ số kỹ thuật: RSI, MACD, Bollinger Bands. Cần có historical data trước.",
"input_schema": {
"type": "object",
"properties": {
"ticker": {"type": "string"},
"indicators": {
"type": "array",
"items": {"type": "string", "enum": ["RSI", "MACD", "BB", "MA20", "MA50"]},
"description": "Danh sách indicators cần tính"
}
},
"required": ["ticker", "indicators"]
}
},
{
"name": "get_market_overview",
"description": "Lấy tổng quan thị trường: VN-Index, HNX-Index, top gainers/losers, market breadth.",
"input_schema": {
"type": "object",
"properties": {
"include_sectors": {
"type": "boolean",
"default": False,
"description": "Có bao gồm phân tích theo ngành không"
}
}
}
},
{
"name": "generate_excel_report",
"description": "Tạo file Excel báo cáo phân tích. Dùng khi user yêu cầu báo cáo tải về.",
"input_schema": {
"type": "object",
"properties": {
"tickers": {
"type": "array",
"items": {"type": "string"},
"description": "Danh sách mã cổ phiếu cần báo cáo"
},
"report_type": {
"type": "string",
"enum": ["quick_scan", "full_analysis", "comparison"],
"default": "quick_scan"
}
},
"required": ["tickers"]
}
}
]
def process(self, user_message: str, conversation_history: list = None) -> dict:
"""Main entry point cho skill"""
messages = conversation_history or []
messages.append({"role": "user", "content": user_message})
response = self.client.messages.create(
model="claude-opus-4-5",
max_tokens=4000,
system=self.SKILL_DESCRIPTION,
tools=self.tools,
messages=messages
)
# Xử lý tool calls
while response.stop_reason == "tool_use":
tool_results = []
for block in response.content:
if block.type == "tool_use":
result = self._execute_tool(block.name, block.input)
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": json.dumps(result, ensure_ascii=False)
})
messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": tool_results})
response = self.client.messages.create(
model="claude-opus-4-5",
max_tokens=4000,
system=self.SKILL_DESCRIPTION,
tools=self.tools,
messages=messages
)
final_text = next((b.text for b in response.content if b.type == "text"), "")
messages.append({"role": "assistant", "content": final_text})
return {
"response": final_text,
"conversation": messages
}
def _execute_tool(self, tool_name: str, tool_input: dict) -> dict:
"""Route tool calls đến implementations"""
tool_map = {
"get_stock_data": self.data_fetcher.get_stock_data,
"calculate_technical_indicators": self.data_fetcher.calculate_technicals,
"get_market_overview": self.data_fetcher.get_market_overview,
"generate_excel_report": self.data_fetcher.generate_report
}
handler = tool_map.get(tool_name)
if handler:
return handler(**tool_input)
return {"error": f"Unknown tool: {tool_name}"}
Bước 4: Data Fetcher Implementation
class MarketDataFetcher:
"""Handles all data fetching and calculations"""
def get_stock_data(self, ticker: str, include_history: bool = False) -> dict:
"""Fetch stock data — mock implementation, replace with real API"""
# Trong production: call VN market API
return {
"ticker": ticker,
"price": 89500, # VND
"change": 1500,
"change_pct": 1.71,
"volume": 2_450_000,
"pe_ratio": 18.5,
"pb_ratio": 3.2,
"eps": 4838,
"market_cap": "176,400 tỷ VND",
"52w_high": 98000,
"52w_low": 72000,
"sector": "Hàng tiêu dùng thiết yếu",
"exchange": "HOSE"
}
def calculate_technicals(self, ticker: str, indicators: list) -> dict:
"""Calculate technical indicators"""
# Trong production: fetch prices và compute
results = {}
if "RSI" in indicators:
results["RSI"] = {
"value": 58.4,
"signal": "Neutral", # Oversold < 30, Overbought > 70
"interpretation": "Cổ phiếu đang ở vùng trung tính"
}
if "MACD" in indicators:
results["MACD"] = {
"macd_line": 245,
"signal_line": 198,
"histogram": 47,
"signal": "Bullish", # MACD > Signal = Bullish
"interpretation": "MACD cắt lên đường Signal — xu hướng tăng ngắn hạn"
}
if "BB" in indicators:
results["Bollinger_Bands"] = {
"upper": 94500,
"middle": 87800,
"lower": 81100,
"position": "Middle",
"interpretation": "Giá đang giao dịch gần band giữa, biến động bình thường"
}
return results
def get_market_overview(self, include_sectors: bool = False) -> dict:
return {
"vn_index": {"value": 1285.42, "change": +12.35, "change_pct": +0.97},
"hnx_index": {"value": 228.15, "change": -1.82, "change_pct": -0.79},
"upcom_index": {"value": 92.34, "change": +0.45, "change_pct": +0.49},
"market_breadth": {"advancing": 312, "declining": 198, "unchanged": 45},
"top_gainers": [{"ticker": "VIC", "change_pct": 4.5}, {"ticker": "VHM", "change_pct": 3.2}],
"top_losers": [{"ticker": "MSN", "change_pct": -2.8}, {"ticker": "MWG", "change_pct": -2.1}]
}
def generate_report(self, tickers: list, report_type: str = "quick_scan") -> dict:
return {
"status": "generated",
"file_path": f"/tmp/report_{'-'.join(tickers)}.xlsx",
"download_url": f"https://example.com/reports/..."
}
Bước 5: Testing Skill
def test_skill():
skill = VietnameseMarketSkill()
test_cases = [
"Phân tích nhanh cổ phiếu VNM cho tôi",
"Hôm nay thị trường thế nào?",
"So sánh VIC và VHM, nên mua cái nào?",
"Tạo báo cáo Excel cho VNM, HPG, và VIC"
]
for i, question in enumerate(test_cases, 1):
print(f"
=== Test {i}: {question} ===")
result = skill.process(question)
print(f"Response ({len(result['response'])} chars):")
print(result['response'][:300] + "..." if len(result['response']) > 300 else result['response'])
print("
All tests passed!")
test_skill()
Bước 6: Đóng gói và Publish
"""
Cấu trúc thư mục để publish skill:
my-vn-market-skill/
├── SKILL.md # Skill description
├── CONNECTORS.md # API connections
├── requirements.txt # Dependencies
├── skill.py # Main implementation
├── data_fetcher.py # Data layer
├── tests/
│ ├── test_skill.py
│ └── test_data.py
└── README.md # Setup instructions
"""
# requirements.txt
REQUIREMENTS = """
anthropic>=0.40.0
pandas>=2.0.0
numpy>=1.24.0
openpyxl>=3.1.0
redis>=5.0.0
httpx>=0.27.0
"""
# Packaging cho internal use
def create_skill_package(output_dir: str):
"""Tạo distribution package"""
import os
os.makedirs(output_dir, exist_ok=True)
# Write all files
files_to_create = {
"requirements.txt": REQUIREMENTS,
"SKILL.md": "# SKILL: ...", # content from above
"CONNECTORS.md": "# CONNECTORS: ...", # content from above
}
for filename, content in files_to_create.items():
with open(os.path.join(output_dir, filename), 'w') as f:
f.write(content)
print(f"Skill package created at: {output_dir}")
Best Practices khi tạo Custom Skills
- SKILL.md phải cực kỳ cụ thể — càng cụ thể, Claude càng invoke đúng lúc. Tránh mơ hồ về khi nào dùng tool nào.
- Tool descriptions là critical — Claude dùng descriptions để quyết định gọi tool nào. Đầu tư thời gian viết thật rõ ràng.
- Error handling phải robust — Skill chạy autonomous, cần xử lý mọi failure gracefully.
- Cache aggressive — API calls tốn tiền và thời gian. Cache mọi thứ có thể cache được.
- Test với diverse inputs — Users sẽ hỏi theo cách bạn không ngờ tới. Test edge cases nhiều.
- Version và changelog — Khi update skill, bump version và document changes trong SKILL.md.
Tổng kết
Custom Skills biến Claude từ general assistant thành domain expert trong tổ chức của bạn. Với SKILL.md + CONNECTORS.md + implementation code rõ ràng, bạn có thể xây dựng skills cho bất kỳ use case nào — từ phân tích thị trường tài chính đến quản lý inventory hay customer support.
Đọc thêm: Orchestrator-Workers Pattern để kết hợp nhiều skills trong một multi-agent system phức tạp.
Bai viet co huu ich khong?
Bản quyền thuộc về tác giả. Vui lòng dẫn nguồn khi chia sẻ.



