Was this page helpful?
程式化工具呼叫允許 Claude 在程式碼執行容器中編寫以程式方式呼叫工具的程式碼,而不需要為每次工具呼叫進行往返模型。這可以減少多工具工作流程的延遲,並通過允許 Claude 在資料到達模型的上下文視窗之前過濾或處理資料來降低代幣消耗。在BrowseComp和DeepSearchQA等代理搜尋基準上,這些基準測試多步驟網路研究和複雜資訊檢索,在基本搜尋工具之上添加程式化工具呼叫是完全解鎖代理效能的關鍵因素。
差異在實際工作流程中迅速複合。考慮檢查 20 名員工的預算合規性:傳統方法需要 20 次單獨的模型往返,沿途將數千個費用行項目拉入上下文。使用程式化工具呼叫,單個指令碼執行所有 20 次查詢,過濾結果,並僅返回超過限額的員工,將 Claude 需要推理的內容從數百千位元組縮小到幾行。
如需深入了解程式化工具呼叫所解決的推理和上下文成本,請參閱進階工具使用。
此功能需要啟用程式碼執行工具。
This feature is not eligible for Zero Data Retention (ZDR). Data is retained according to the feature's standard retention policy.
程式化工具呼叫需要 code_execution_20260120,以下模型支援此功能:
| 模型 |
|---|
Claude Opus 4.7 (claude-opus-4-7) |
Claude Opus 4.6 (claude-opus-4-6) |
Claude Sonnet 4.6 (claude-sonnet-4-6) |
Claude Opus 4.5 (claude-opus-4-5-20251101) |
Claude Sonnet 4.5 (claude-sonnet-4-5-20250929) |
如需完整的程式碼執行工具版本矩陣,請參閱程式碼執行工具模型相容性表。程式化工具呼叫可通過 Claude API 和 Microsoft Foundry 使用。
以下是一個簡單範例,其中 Claude 以程式方式多次查詢資料庫並聚合結果:
當您配置工具可從程式碼執行呼叫,且 Claude 決定使用該工具時:
tool_use 區塊此方法特別適用於:
自訂工具被轉換為非同步 Python 函式以支援平行工具呼叫。當 Claude 編寫呼叫工具的程式碼時,它使用 await(例如,result = await query_database("<sql>"))並自動包含適當的非同步包裝函式。
為了清晰起見,本文件中的程式碼範例中省略了非同步包裝。
allowed_callers 欄位allowed_callers 欄位指定哪些上下文可以呼叫工具:
{
"name": "query_database",
"description": "Execute a SQL query against the database",
"input_schema": {
// ...
},
"allowed_callers": ["code_execution_20260120"]
}可能的值:
["direct"] - 只有 Claude 可以直接呼叫此工具(如果省略則為預設值)["code_execution_20260120"] - 只能從程式碼執行內呼叫["direct", "code_execution_20260120"] - 可以直接呼叫和從程式碼執行呼叫為每個工具選擇 ["direct"] 或 ["code_execution_20260120"] 而不是同時啟用兩者,因為這為 Claude 提供了更清晰的指導,說明如何最好地使用該工具。
caller 欄位每個工具使用區塊都包含一個 caller 欄位,指示它是如何被呼叫的:
直接呼叫(傳統工具使用):
{
"type": "tool_use",
"id": "toolu_abc123",
"name": "query_database",
"input": { "sql": "<sql>" },
"caller": { "type": "direct" }
}程式化呼叫:
{
"type": "tool_use",
"id": "toolu_xyz789",
"name": "query_database",
"input": { "sql": "<sql>" },
"caller": {
"type": "code_execution_20260120",
"tool_id": "srvtoolu_abc123"
}
}tool_id 參考進行程式化呼叫的程式碼執行工具。
程式化工具呼叫使用與程式碼執行相同的容器:
container 欄位在回應中返回當工具以程式方式呼叫且容器正在等待您的工具結果時,您必須在容器過期之前回應。監視 expires_at 欄位。如果容器過期,Claude 可能會將工具呼叫視為超時並重試它。
以下是完整的程式化工具呼叫流程的運作方式:
發送包含程式碼執行和允許程式化呼叫的工具的請求。要啟用程式化呼叫,請將 allowed_callers 欄位新增到工具定義中。
在工具描述中提供工具輸出格式的詳細描述。如果您指定工具返回 JSON,Claude 會嘗試在程式碼中反序列化和處理結果。您提供的有關輸出架構的詳細資訊越多,Claude 就能更好地以程式方式處理回應。
請求形狀與快速開始範例相同:在工具清單中包含 code_execution,將 allowed_callers: ["code_execution_20260120"] 新增到任何您希望 Claude 從程式碼呼叫的工具,並發送您的使用者訊息。
Claude 編寫呼叫工具的程式碼。API 暫停並返回:
{
"role": "assistant",
"content": [
{
"type": "text",
"text": "I'll query the purchase history and analyze the results."
},
{
"type": "server_tool_use",
"id": "srvtoolu_abc123",
"name": "code_execution",
"input": {
"code": "results = await query_database('<sql>')\ntop_customers = sorted(results, key=lambda x: x['revenue'], reverse=True)[:5]\nprint(f'Top 5 customers: {top_customers}')"
}
},
{
"type": "tool_use",
"id": "toolu_def456",
"name": "query_database",
"input": { "sql": "<sql>" },
"caller": {
"type": "code_execution_20260120",
"tool_id": "srvtoolu_abc123"
}
}
],
"container": {
"id": "container_xyz789",
"expires_at": "2025-01-15T14:30:00Z"
},
"stop_reason": "tool_use"
}包含完整的對話歷史記錄加上您的工具結果:
程式碼執行繼續進行並處理結果。如果需要額外的工具呼叫,重複步驟 3 直到所有工具呼叫都得到滿足。
程式碼執行完成後,Claude 提供最終回應:
{
"content": [
{
"type": "code_execution_tool_result",
"tool_use_id": "srvtoolu_abc123",
"content": {
"type": "code_execution_result",
"stdout": "Top 5 customers by revenue:\n1. Customer C1: $45,000\n2. Customer C2: $38,000\n3. Customer C5: $32,000\n4. Customer C8: $28,500\n5. Customer C3: $24,000",
"stderr": "",
"return_code": 0,
"content": []
}
},
{
"type": "text",
"text": "I've analyzed the purchase history from last quarter. Your top 5 customers generated $167,500 in total revenue, with Customer C1 leading at $45,000."
}
],
"stop_reason": "end_turn"
}Claude 可以編寫程式碼來有效地處理多個項目:
async def _claude_code():
regions = ["West", "East", "Central", "North", "South"]
results = {}
for region in regions:
data = await query_database(f"<sql for {region}>")
results[region] = sum(row["revenue"] for row in data)
# Process results programmatically
top_region = max(results.items(), key=lambda x: x[1])
print(f"Top region: {top_region[0]} with ${top_region[1]:,} in revenue")
此模式:
Claude 可以在滿足成功條件時立即停止處理:
async def _claude_code():
endpoints = ["us-east", "eu-west", "apac"]
for endpoint in endpoints:
status = await check_health(endpoint)
if status == "healthy":
print(f"Found healthy endpoint: {endpoint}")
break # Stop early, don't check remaining
async def _claude_code():
file_info = await get_file_info(path)
if file_info["size"] < 10000:
content = await read_full_file(path)
else:
content = await read_file_summary(path)
print(content)
async def _claude_code():
logs = await fetch_logs(server_id)
errors = [log for log in logs if "ERROR" in log]
print(f"Found {len(errors)} errors")
for error in errors[-10:]: # Only return last 10 errors
print(error)
當程式碼執行呼叫工具時:
{
"type": "tool_use",
"id": "toolu_abc123",
"name": "query_database",
"input": { "sql": "<sql>" },
"caller": {
"type": "code_execution_20260120",
"tool_id": "srvtoolu_xyz789"
}
}您的工具結果被傳回給執行中的程式碼:
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_abc123",
"content": "[{\"customer_id\": \"C1\", \"revenue\": 45000, \"orders\": 23}, {\"customer_id\": \"C2\", \"revenue\": 38000, \"orders\": 18}, ...]"
}
]
}當所有工具呼叫都得到滿足且程式碼完成時:
{
"type": "code_execution_tool_result",
"tool_use_id": "srvtoolu_xyz789",
"content": {
"type": "code_execution_result",
"stdout": "Analysis complete. Top 5 customers identified from 847 total records.",
"stderr": "",
"return_code": 0,
"content": []
}
}| 錯誤 | 說明 | 解決方案 |
|---|---|---|
invalid_tool_input | 工具輸入不符合結構描述 | 驗證您的工具的 input_schema |
tool_not_allowed | 工具不允許請求的呼叫者類型 | 檢查 allowed_callers 是否包含正確的上下文 |
missing_beta_header | 未提供必需的測試版標頭(僅限 Bedrock 和 Vertex AI;程式化工具呼叫在第一方 Claude API 上為 GA) | 將必需的測試版標頭新增到您的請求中 |
如果您的工具花費太長時間來回應,程式碼執行會收到 TimeoutError。Claude 在 stderr 中看到這個錯誤,通常會重試:
{
"type": "code_execution_tool_result",
"tool_use_id": "srvtoolu_abc123",
"content": {
"type": "code_execution_result",
"stdout": "",
"stderr": "TimeoutError: Calling tool ['query_database'] timed out.",
"return_code": 0,
"content": []
}
}為了防止逾時:
expires_at 欄位如果您的工具返回錯誤:
{
"type": "tool_result",
"tool_use_id": "toolu_abc123",
"content": "Error: Query timeout - table lock exceeded 30 seconds"
}Claude 的程式碼會收到此錯誤並可以適當地處理它。
strict: true 的工具不支援程式化呼叫tool_choice 強制程式化呼叫特定工具disable_parallel_tool_use: true 不支援程式化呼叫以下工具目前無法以程式方式呼叫,但未來版本可能會新增支援:
在回應程式化工具呼叫時,有嚴格的格式要求:
僅工具結果回應: 如果有待處理的程式化工具呼叫等待結果,您的回應訊息必須僅包含 tool_result 區塊。您不能包含任何文字內容,即使在工具結果之後也不行。
無效 - 回應程式化工具呼叫時無法包含文字:
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_01",
"content": "[{\"customer_id\": \"C1\", \"revenue\": 45000}]"
},
{ "type": "text", "text": "What should I do next?" }
]
}有效 - 回應程式化工具呼叫時僅工具結果:
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_01",
"content": "[{\"customer_id\": \"C1\", \"revenue\": 45000}]"
}
]
}此限制僅適用於回應程式化(程式碼執行)工具呼叫時。對於常規用戶端工具呼叫,您可以在工具結果之後包含文字內容。
程式化工具呼叫受到與常規工具呼叫相同的速率限制。來自程式碼執行的每個工具呼叫都計為單獨的呼叫。
實施將以程式方式呼叫的使用者定義工具時:
程式化工具呼叫可以顯著減少代幣消耗:
例如,直接呼叫 10 個工具使用的代幣大約是以程式方式呼叫它們並返回摘要的 10 倍。
程式化工具呼叫使用與程式碼執行相同的定價。有關詳細資訊,請參閱 程式碼執行定價。
程式化工具呼叫的代幣計數:來自程式化呼叫的工具結果不計入您的輸入/輸出代幣使用量。只有最終程式碼執行結果和 Claude 的回應計算。
良好的使用案例:
不太理想的使用案例:
「工具不允許」錯誤
"allowed_callers": ["code_execution_20260120"]容器過期
expires_at 欄位工具結果未正確解析
caller 欄位 以確認程式化呼叫Claude 的訓練包括對程式碼的廣泛接觸,使其在推理和鏈接函式呼叫方面有效。當工具在程式碼執行環境中呈現為可呼叫函式時,Claude 可以利用此優勢來:
此方法啟用了使用傳統工具使用不切實際的工作流程(例如處理超過 1M 代幣的檔案),允許 Claude 以程式方式處理資料,而不是將所有內容載入到對話上下文中。
程式化工具呼叫是一個可概括的模式,可以在 Anthropic 的託管程式碼執行之外實現。以下是方法的概述:
為 Claude 提供程式碼執行工具,並描述該環境中可用的函式。當 Claude 使用程式碼呼叫工具時,您的應用程式在定義了這些函式的本地執行它。
優點:
缺點:
使用時機: 您的應用程式可以安全地執行任意程式碼、您想要簡單的解決方案,以及 Anthropic 的託管產品不符合您的需求。
從 Claude 的角度來看相同的方法,但程式碼在具有安全限制的沙箱容器中執行(例如,無網路出口)。如果您的工具需要外部資源,您將需要一個協議來在沙箱外執行工具呼叫。
優點:
缺點:
使用時機: 安全至關重要,Anthropic 的託管解決方案不符合您的要求。
Anthropic 的程式化工具呼叫是沙箱執行的託管版本,具有針對 Claude 調整的固執己見的 Python 環境。Anthropic 處理容器管理、程式碼執行和安全工具呼叫通訊。
優點:
如果您使用 Claude API,請考慮使用 Anthropic 的託管解決方案。
程式化工具呼叫建立在程式碼執行基礎設施上,並使用相同的沙箱容器。容器資料,包括執行工件和輸出,最多保留 30 天。
有關所有功能的 ZDR 資格,請參閱 API 和資料保留。
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-4-7",
max_tokens=4096,
messages=[
{
"role": "user",
"content": "Query sales data for the West, East, and Central regions, then tell me which region had the highest revenue",
}
],
tools=[
{"type": "code_execution_20260120", "name": "code_execution"},
{
"name": "query_database",
"description": "Execute a SQL query against the sales database. Returns a list of rows as JSON objects.",
"input_schema": {
"type": "object",
"properties": {
"sql": {"type": "string", "description": "SQL query to execute"}
},
"required": ["sql"],
},
"allowed_callers": ["code_execution_20260120"],
},
],
)
print(response)response = client.messages.create(
model="claude-opus-4-7",
max_tokens=4096,
container="container_xyz789", # Reuse the container
messages=[
{
"role": "user",
"content": "Query customer purchase history from the last quarter and identify our top 5 customers by revenue",
},
{
"role": "assistant",
"content": [
{
"type": "text",
"text": "I'll query the purchase history and analyze the results.",
},
{
"type": "server_tool_use",
"id": "srvtoolu_abc123",
"name": "code_execution",
"input": {"code": "..."},
},
{
"type": "tool_use",
"id": "toolu_def456",
"name": "query_database",
"input": {"sql": "<sql>"},
"caller": {
"type": "code_execution_20260120",
"tool_id": "srvtoolu_abc123",
},
},
],
},
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_def456",
"content": '[{"customer_id": "C1", "revenue": 45000}, {"customer_id": "C2", "revenue": 38000}, ...]',
}
],
},
],
tools=[...],
)
print(response)定義工具的逐步指南。