使用 Agent Skills 與 API
Agent Skills 透過組織化的指令、指令碼和資源資料夾來擴展 Claude 的功能。本指南展示如何使用預先建立的和自訂 Skills 與 Claude API。
如需完整的 API 參考,包括請求/回應架構和所有參數,請參閱:
- Skill 管理 API 參考 - Skills 的 CRUD 操作
- Skill 版本 API 參考 - 版本管理
快速連結
概述
如需深入了解 Agent Skills 的架構和實際應用,請閱讀我們的工程部落格:使用 Agent Skills 為代理程式配備真實世界的功能。
Skills 透過程式碼執行工具與 Messages API 整合。無論使用由 Anthropic 管理的預先建立 Skills 或您上傳的自訂 Skills,整合形式都是相同的——兩者都需要程式碼執行,並使用相同的 container 結構。
使用 Skills
Skills 在 Messages API 中的整合方式相同,無論來源如何。您在 container 參數中指定 Skills,包括 skill_id、type 和可選的 version,它們在程式碼執行環境中執行。
您可以從兩個來源使用 Skills:
| 方面 | Anthropic Skills | 自訂 Skills |
|---|---|---|
| Type 值 | anthropic | custom |
| Skill ID | 短名稱:pptx、xlsx、docx、pdf | 生成的:skill_01AbCdEfGhIjKlMnOpQrStUv |
| 版本格式 | 基於日期:20251013 或 latest | Epoch 時間戳:1759178010641129 或 latest |
| 管理 | 由 Anthropic 預先建立和維護 | 透過 Skills API 上傳和管理 |
| 可用性 | 對所有使用者可用 | 私有於您的工作區 |
兩個 Skill 來源都由 List Skills 端點 返回(使用 source 參數進行篩選)。整合形式和執行環境相同——唯一的區別是 Skills 的來源和管理方式。
先決條件
要使用 Skills,您需要:
- Anthropic API 金鑰,來自 Console
- Beta 標頭:
code-execution-2025-08-25- 啟用程式碼執行(Skills 所需)skills-2025-10-02- 啟用 Skills APIfiles-api-2025-04-14- 用於上傳/下載檔案到/從容器
- 程式碼執行工具在您的請求中啟用
在 Messages 中使用 Skills
Container 參數
Skills 使用 Messages API 中的 container 參數指定。您可以在每個請求中包含最多 8 個 Skills。
結構對 Anthropic 和自訂 Skills 都相同——指定必需的 type 和 skill_id,並可選擇包含 version 以固定到特定版本:
import anthropic
client = anthropic.Anthropic()
response = client.beta.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=4096,
betas=["code-execution-2025-08-25", "skills-2025-10-02"],
container={
"skills": [
{
"type": "anthropic",
"skill_id": "pptx",
"version": "latest"
}
]
},
messages=[{
"role": "user",
"content": "Create a presentation about renewable energy"
}],
tools=[{
"type": "code_execution_20250825",
"name": "code_execution"
}]
)import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic();
const response = await client.beta.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 4096,
betas: ['code-execution-2025-08-25', 'skills-2025-10-02'],
container: {
skills: [
{
type: 'anthropic',
skill_id: 'pptx',
version: 'latest'
}
]
},
messages: [{
role: 'user',
content: 'Create a presentation about renewable energy'
}],
tools: [{
type: 'code_execution_20250825',
name: 'code_execution'
}]
});curl https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "anthropic-beta: code-execution-2025-08-25,skills-2025-10-02" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-4-5-20250929",
"max_tokens": 4096,
"container": {
"skills": [
{
"type": "anthropic",
"skill_id": "pptx",
"version": "latest"
}
]
},
"messages": [{
"role": "user",
"content": "Create a presentation about renewable energy"
}],
"tools": [{
"type": "code_execution_20250825",
"name": "code_execution"
}]
}'下載生成的檔案
當 Skills 建立文件(Excel、PowerPoint、PDF、Word)時,它們在回應中返回 file_id 屬性。您必須使用 Files API 下載這些檔案。
工作原理:
- Skills 在程式碼執行期間建立檔案
- 回應包含每個建立的檔案的
file_id - 使用 Files API 下載實際檔案內容
- 在本地儲存或根據需要處理
範例:建立和下載 Excel 檔案
import anthropic
client = anthropic.Anthropic()
# Step 1: Use a Skill to create a file
response = client.beta.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=4096,
betas=["code-execution-2025-08-25", "skills-2025-10-02"],
container={
"skills": [
{"type": "anthropic", "skill_id": "xlsx", "version": "latest"}
]
},
messages=[{
"role": "user",
"content": "Create an Excel file with a simple budget spreadsheet"
}],
tools=[{"type": "code_execution_20250825", "name": "code_execution"}]
)
# Step 2: Extract file IDs from the response
def extract_file_ids(response):
file_ids = []
for item in response.content:
if item.type == 'bash_code_execution_tool_result':
content_item = item.content
if content_item.type == 'bash_code_execution_result':
for file in content_item.content:
if hasattr(file, 'file_id'):
file_ids.append(file.file_id)
return file_ids
# Step 3: Download the file using Files API
for file_id in extract_file_ids(response):
file_metadata = client.beta.files.retrieve_metadata(
file_id=file_id,
betas=["files-api-2025-04-14"]
)
file_content = client.beta.files.download(
file_id=file_id,
betas=["files-api-2025-04-14"]
)
# Step 4: Save to disk
file_content.write_to_file(file_metadata.filename)
print(f"Downloaded: {file_metadata.filename}")其他 Files API 操作:
# Get file metadata
file_info = client.beta.files.retrieve_metadata(
file_id=file_id,
betas=["files-api-2025-04-14"]
)
print(f"Filename: {file_info.filename}, Size: {file_info.size_bytes} bytes")
# List all files
files = client.beta.files.list(betas=["files-api-2025-04-14"])
for file in files.data:
print(f"{file.filename} - {file.created_at}")
# Delete a file
client.beta.files.delete(
file_id=file_id,
betas=["files-api-2025-04-14"]
)如需 Files API 的完整詳細資訊,請參閱 Files API 文件。
多輪對話
透過指定容器 ID 在多個訊息中重複使用相同的容器:
# First request creates container
response1 = client.beta.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=4096,
betas=["code-execution-2025-08-25", "skills-2025-10-02"],
container={
"skills": [
{"type": "anthropic", "skill_id": "xlsx", "version": "latest"}
]
},
messages=[{"role": "user", "content": "Analyze this sales data"}],
tools=[{"type": "code_execution_20250825", "name": "code_execution"}]
)
# Continue conversation with same container
messages = [
{"role": "user", "content": "Analyze this sales data"},
{"role": "assistant", "content": response1.content},
{"role": "user", "content": "What was the total revenue?"}
]
response2 = client.beta.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=4096,
betas=["code-execution-2025-08-25", "skills-2025-10-02"],
container={
"id": response1.container.id, # Reuse container
"skills": [
{"type": "anthropic", "skill_id": "xlsx", "version": "latest"}
]
},
messages=messages,
tools=[{"type": "code_execution_20250825", "name": "code_execution"}]
)長時間執行的操作
Skills 可能執行需要多個回合的操作。處理 pause_turn 停止原因:
messages = [{"role": "user", "content": "Process this large dataset"}]
max_retries = 10
response = client.beta.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=4096,
betas=["code-execution-2025-08-25", "skills-2025-10-02"],
container={
"skills": [
{"type": "custom", "skill_id": "skill_01AbCdEfGhIjKlMnOpQrStUv", "version": "latest"}
]
},
messages=messages,
tools=[{"type": "code_execution_20250825", "name": "code_execution"}]
)
# Handle pause_turn for long operations
for i in range(max_retries):
if response.stop_reason != "pause_turn":
break
messages.append({"role": "assistant", "content": response.content})
response = client.beta.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=4096,
betas=["code-execution-2025-08-25", "skills-2025-10-02"],
container={
"id": response.container.id,
"skills": [
{"type": "custom", "skill_id": "skill_01AbCdEfGhIjKlMnOpQrStUv", "version": "latest"}
]
},
messages=messages,
tools=[{"type": "code_execution_20250825", "name": "code_execution"}]
)回應可能包含 pause_turn 停止原因,表示 API 暫停了長時間執行的 Skill 操作。您可以在後續請求中按原樣提供回應,讓 Claude 繼續其回合,或修改內容以中斷對話並提供額外指導。
使用多個 Skills
在單個請求中組合多個 Skills 以處理複雜工作流程:
response = client.beta.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=4096,
betas=["code-execution-2025-08-25", "skills-2025-10-02"],
container={
"skills": [
{
"type": "anthropic",
"skill_id": "xlsx",
"version": "latest"
},
{
"type": "anthropic",
"skill_id": "pptx",
"version": "latest"
},
{
"type": "custom",
"skill_id": "skill_01AbCdEfGhIjKlMnOpQrStUv",
"version": "latest"
}
]
},
messages=[{
"role": "user",
"content": "Analyze sales data and create a presentation"
}],
tools=[{
"type": "code_execution_20250825",
"name": "code_execution"
}]
)管理自訂 Skills
建立 Skill
上傳您的自訂 Skill 以在您的工作區中使用。您可以使用目錄路徑或個別檔案物件上傳。
import anthropic
client = anthropic.Anthropic()
# Option 1: Using files_from_dir helper (Python only, recommended)
from anthropic.lib import files_from_dir
skill = client.beta.skills.create(
display_title="Financial Analysis",
files=files_from_dir("/path/to/financial_analysis_skill"),
betas=["skills-2025-10-02"]
)
# Option 2: Using a zip file
skill = client.beta.skills.create(
display_title="Financial Analysis",
files=[("skill.zip", open("financial_analysis_skill.zip", "rb"))],
betas=["skills-2025-10-02"]
)
# Option 3: Using file tuples (filename, file_content, mime_type)
skill = client.beta.skills.create(
display_title="Financial Analysis",
files=[
("financial_skill/SKILL.md", open("financial_skill/SKILL.md", "rb"), "text/markdown"),
("financial_skill/analyze.py", open("financial_skill/analyze.py", "rb"), "text/x-python"),
],
betas=["skills-2025-10-02"]
)
print(f"Created skill: {skill.id}")
print(f"Latest version: {skill.latest_version}")要求:
- 必須在頂層包含 SKILL.md 檔案
- 所有檔案必須在其路徑中指定公共根目錄
- 總上傳大小必須小於 8MB
- YAML frontmatter 要求:
name:最多 64 個字元,僅小寫字母/數字/連字號,無 XML 標籤,無保留字("anthropic"、"claude")description:最多 1024 個字元,非空,無 XML 標籤
如需完整的請求/回應架構,請參閱 Create Skill API 參考。
列出 Skills
檢索您工作區中所有可用的 Skills,包括 Anthropic 預先建立的 Skills 和您的自訂 Skills。使用 source 參數按 Skill 類型進行篩選:
# List all Skills
skills = client.beta.skills.list(
betas=["skills-2025-10-02"]
)
for skill in skills.data:
print(f"{skill.id}: {skill.display_title} (source: {skill.source})")
# List only custom Skills
custom_skills = client.beta.skills.list(
source="custom",
betas=["skills-2025-10-02"]
)請參閱 List Skills API 參考 以了解分頁和篩選選項。
檢索 Skill
取得特定 Skill 的詳細資訊:
skill = client.beta.skills.retrieve(
skill_id="skill_01AbCdEfGhIjKlMnOpQrStUv",
betas=["skills-2025-10-02"]
)
print(f"Skill: {skill.display_title}")
print(f"Latest version: {skill.latest_version}")
print(f"Created: {skill.created_at}")刪除 Skill
要刪除 Skill,您必須先刪除其所有版本:
# Step 1: Delete all versions
versions = client.beta.skills.versions.list(
skill_id="skill_01AbCdEfGhIjKlMnOpQrStUv",
betas=["skills-2025-10-02"]
)
for version in versions.data:
client.beta.skills.versions.delete(
skill_id="skill_01AbCdEfGhIjKlMnOpQrStUv",
version=version.version,
betas=["skills-2025-10-02"]
)
# Step 2: Delete the Skill
client.beta.skills.delete(
skill_id="skill_01AbCdEfGhIjKlMnOpQrStUv",
betas=["skills-2025-10-02"]
)嘗試刪除具有現有版本的 Skill 將返回 400 錯誤。
版本控制
Skills 支援版本控制以安全地管理更新:
Anthropic 管理的 Skills:
- 版本使用日期格式:
20251013 - 進行更新時發布新版本
- 指定確切版本以確保穩定性
自訂 Skills:
- 自動生成的 Epoch 時間戳:
1759178010641129 - 使用
"latest"始終獲取最新版本 - 更新 Skill 檔案時建立新版本
# Create a new version
from anthropic.lib import files_from_dir
new_version = client.beta.skills.versions.create(
skill_id="skill_01AbCdEfGhIjKlMnOpQrStUv",
files=files_from_dir("/path/to/updated_skill"),
betas=["skills-2025-10-02"]
)
# Use specific version
response = client.beta.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=4096,
betas=["code-execution-2025-08-25", "skills-2025-10-02"],
container={
"skills": [{
"type": "custom",
"skill_id": "skill_01AbCdEfGhIjKlMnOpQrStUv",
"version": new_version.version
}]
},
messages=[{"role": "user", "content": "Use updated Skill"}],
tools=[{"type": "code_execution_20250825", "name": "code_execution"}]
)
# Use latest version
response = client.beta.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=4096,
betas=["code-execution-2025-08-25", "skills-2025-10-02"],
container={
"skills": [{
"type": "custom",
"skill_id": "skill_01AbCdEfGhIjKlMnOpQrStUv",
"version": "latest"
}]
},
messages=[{"role": "user", "content": "Use latest Skill version"}],
tools=[{"type": "code_execution_20250825", "name": "code_execution"}]
)請參閱 Create Skill Version API 參考 以了解完整詳細資訊。
Skills 如何被載入
當您在容器中指定 Skills 時:
- 元資料發現:Claude 在系統提示中看到每個 Skill 的元資料(名稱、描述)
- 檔案載入:Skill 檔案被複製到容器中的
/skills/{directory}/ - 自動使用:Claude 在與您的請求相關時自動載入和使用 Skills
- 組合:多個 Skills 組合在一起以處理複雜工作流程
漸進式揭露架構確保高效的上下文使用——Claude 僅在需要時載入完整的 Skill 指令。
使用案例
組織 Skills
品牌與通訊
- 將公司特定的格式(顏色、字體、佈局)應用於文件
- 按照組織範本生成通訊
- 確保所有輸出中的一致品牌指南
專案管理
- 使用公司特定格式(OKR、決策日誌)結構化筆記
- 按照團隊慣例生成任務
- 建立標準化的會議摘要和狀態更新
業務運營
- 建立公司標準報告、提案和分析
- 執行公司特定的分析程序
- 按照組織範本生成財務模型
個人 Skills
內容建立
- 自訂文件範本
- 專業化的格式和樣式
- 特定領域的內容生成
資料分析
- 自訂資料處理管道
- 專業化的視覺化範本
- 特定行業的分析方法
開發與自動化
- 程式碼生成範本
- 測試框架
- 部署工作流程
範例:財務建模
組合 Excel 和自訂 DCF 分析 Skills:
# Create custom DCF analysis Skill
from anthropic.lib import files_from_dir
dcf_skill = client.beta.skills.create(
display_title="DCF Analysis",
files=files_from_dir("/path/to/dcf_skill"),
betas=["skills-2025-10-02"]
)
# Use with Excel to create financial model
response = client.beta.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=4096,
betas=["code-execution-2025-08-25", "skills-2025-10-02"],
container={
"skills": [
{"type": "anthropic", "skill_id": "xlsx", "version": "latest"},
{"type": "custom", "skill_id": dcf_skill.id, "version": "latest"}
]
},
messages=[{
"role": "user",
"content": "Build a DCF valuation model for a SaaS company with the attached financials"
}],
tools=[{"type": "code_execution_20250825", "name": "code_execution"}]
)限制和約束
請求限制
- 每個請求的最大 Skills 數:8
- 最大 Skill 上傳大小:8MB(所有檔案合計)
- YAML frontmatter 要求:
name:最多 64 個字元,僅小寫字母/數字/連字號,無 XML 標籤,無保留字description:最多 1024 個字元,非空,無 XML 標籤
環境約束
Skills 在程式碼執行容器中執行,具有以下限制:
- 無網路存取 - 無法進行外部 API 呼叫
- 無執行時套件安裝 - 僅可用預先安裝的套件
- 隔離環境 - 每個請求都獲得一個新的容器
請參閱 程式碼執行工具文件 以了解可用的套件。
最佳實踐
何時使用多個 Skills
當任務涉及多個文件類型或領域時組合 Skills:
良好的使用案例:
- 資料分析(Excel)+ 簡報建立(PowerPoint)
- 報告生成(Word)+ 匯出為 PDF
- 自訂領域邏輯 + 文件生成
避免:
- 包含未使用的 Skills(影響效能)
版本管理策略
用於生產:
# Pin to specific versions for stability
container={
"skills": [{
"type": "custom",
"skill_id": "skill_01AbCdEfGhIjKlMnOpQrStUv",
"version": "1759178010641129" # Specific version
}]
}用於開發:
# Use latest for active development
container={
"skills": [{
"type": "custom",
"skill_id": "skill_01AbCdEfGhIjKlMnOpQrStUv",
"version": "latest" # Always get newest
}]
}提示快取考慮
使用提示快取時,請注意在容器中更改 Skills 列表將破壞快取:
# First request creates cache
response1 = client.beta.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=4096,
betas=["code-execution-2025-08-25", "skills-2025-10-02", "prompt-caching-2024-07-31"],
container={
"skills": [
{"type": "anthropic", "skill_id": "xlsx", "version": "latest"}
]
},
messages=[{"role": "user", "content": "Analyze sales data"}],
tools=[{"type": "code_execution_20250825", "name": "code_execution"}]
)
# Adding/removing Skills breaks cache
response2 = client.beta.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=4096,
betas=["code-execution-2025-08-25", "skills-2025-10-02", "prompt-caching-2024-07-31"],
container={
"skills": [
{"type": "anthropic", "skill_id": "xlsx", "version": "latest"},
{"type": "anthropic", "skill_id": "pptx", "version": "latest"} # Cache miss
]
},
messages=[{"role": "user", "content": "Create a presentation"}],
tools=[{"type": "code_execution_20250825", "name": "code_execution"}]
)為了獲得最佳快取效能,請在請求中保持 Skills 列表一致。
錯誤處理
優雅地處理 Skill 相關的錯誤:
try:
response = client.beta.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=4096,
betas=["code-execution-2025-08-25", "skills-2025-10-02"],
container={
"skills": [
{"type": "custom", "skill_id": "skill_01AbCdEfGhIjKlMnOpQrStUv", "version": "latest"}
]
},
messages=[{"role": "user", "content": "Process data"}],
tools=[{"type": "code_execution_20250825", "name": "code_execution"}]
)
except anthropic.BadRequestError as e:
if "skill" in str(e):
print(f"Skill error: {e}")
# Handle skill-specific errors
else:
raise