「Programmatic tool calling」(程式化工具呼叫)讓 Claude 能夠撰寫程式碼,在 code execution(程式碼執行)容器中以程式化方式呼叫您的工具,而不需要每次工具呼叫都經過模型往返。這降低了多工具工作流程的「latency」(延遲),並且由於 Claude 可以在資料進入模型的「context window」(上下文視窗)之前先行篩選或處理資料,因而減少了 token 消耗。在 BrowseComp 和 DeepSearchQA 等測試多步驟網路研究與複雜資訊檢索的代理式搜尋基準測試中,在基本搜尋工具之上加入程式化工具呼叫,平均提升了 11% 的效能,同時減少了 24% 的輸入 token(請參閱透過動態篩選改善網路搜尋)。
以檢查 20 位員工的預算合規情況為例:傳統方法需要 20 次獨立的模型往返,過程中會將數千筆費用明細項目拉進上下文中。使用程式化工具呼叫時,單一腳本即可執行全部 20 次查詢、篩選結果,並只回傳超出額度的員工,將 Claude 需要推理的內容從數百 KB 縮減到寥寥數行。
程式化工具呼叫需要 code_execution_20260120 或更新版本,以下模型支援此版本:
| 模型 |
|---|
| Claude Fable 5 () |
| Claude Mythos 5 () |
| Claude Opus 5 () |
| Claude Opus 4.8 () |
| Claude Opus 4.7 () |
| Claude Opus 4.6 () |
| Claude Sonnet 5 () |
| Claude Sonnet 4.6 () |
| Claude Opus 4.5 () |
| Claude Sonnet 4.5 () |
如需完整的程式碼執行工具版本對照表,請參閱程式碼執行工具模型相容性表。程式化工具呼叫可在 Claude API、Claude Platform on AWS 以及 Microsoft Foundry 上使用。在 Microsoft Foundry 上,程式化工具呼叫需要 Hosted on Anthropic 部署。目前尚未在 Amazon Bedrock 或 Google Cloud 上提供。
以下範例中,Claude 以程式化方式多次查詢資料庫並彙總結果。在工具定義中加入 allowed_callers: ["code_execution_20260120"],即可讓該工具能夠從程式碼執行環境中被呼叫(請參閱 allowed_callers 欄位):
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-5",
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)回應會以 stop_reason: "tool_use" 停止,並附帶一個 container ID,以及一個 query_database 的 tool_use 區塊,其 caller 欄位標示了呼叫它的程式碼執行作業。請依照範例工作流程的步驟 3 所示回傳結果,讓程式碼得以完成執行。
當您將某個工具設定為可從程式碼執行環境呼叫,且 Claude 判斷需要該工具時:
tool_use 區塊此方法特別適用於:
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"] - 引導 Claude 僅從程式碼執行環境中呼叫此工具["direct", "code_execution_20260120"] - Claude 可以直接呼叫此工具,也可以從程式碼執行環境中呼叫"code_execution_20260120" 與 "code_execution_20260521" 在 allowed_callers 中皆可接受且可互換:使用任一程式碼執行工具版本的請求,都能滿足列出任一呼叫者的工具。無論請求宣告的是哪個版本,回應區塊一律將呼叫者標記為 code_execution_20260120。
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 是發出該呼叫的程式碼執行 server_tool_use 區塊的 id,因此您可以將每個程式化 tool_use 對應到產生它的程式碼執行作業。
程式化工具呼叫使用與程式碼執行相同的容器:
container 欄位中回傳,並附帶 expires_at 時間戳記expires_at 告訴您容器還剩多少時間。閒置容器目前約在 5 分鐘後被回收,且任何容器在建立超過 30 天後都無法再重複使用。以下是完整的程式化工具呼叫流程的運作方式:
傳送一個包含程式碼執行以及允許程式化呼叫之工具的請求。若要啟用程式化呼叫,請在工具定義中加入 allowed_callers 欄位。
請求的結構與快速開始範例相同:在工具清單中包含 code_execution,為任何您希望 Claude 從程式碼中呼叫的工具加入 allowed_callers: ["code_execution_20260120"],然後傳送您的使用者訊息。此工作流程的其餘步驟使用的使用者訊息為 "Query customer purchase history from the last quarter and identify our top 5 customers by revenue"。
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": "import json\n\nrows = json.loads(await query_database({'sql': '<sql>'}))\ntop_customers = sorted(rows, 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": "2026-01-20T14:30:00Z"
},
"stop_reason": "tool_use"
}傳送完整的對話歷史記錄以及您的工具結果。此請求有三個重要細節:
tool_result 區塊。請參閱訊息格式限制。container ID。若後續請求有待處理的程式化工具呼叫卻沒有容器 ID,API 會拒絕該請求。tools 陣列。程式碼執行工具必須仍然存在,暫停的程式碼才能恢復執行,而您在此請求中傳送的工具,就是 Claude 與執行中的程式碼在本輪其餘部分可使用的定義。response = client.messages.create(
model="claude-opus-5",
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 陣列
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)程式碼從暫停處繼續執行並處理您的結果。每個後續回應要麼再次暫停並帶有更多程式化 tool_use 區塊,要麼完成程式碼執行並讓 Claude 繼續本輪(步驟 5)。請檢查 stop_reason 以及每個 tool_use 區塊的 caller 來區分兩者:為您暫停的回應具有 stop_reason: "tool_use",以及一個 caller 標示程式碼執行版本的 tool_use 區塊,此時您需重複步驟 3,在單一使用者訊息中為每個待處理的程式化呼叫提供 tool_result。
程式碼執行完成後,Claude 提供最終回應:
{
"content": [
{
"type": "code_execution_tool_result",
"tool_use_id": "srvtoolu_abc123",
"content": {
"type": "code_execution_result",
"stdout": "Top 5 customers: [{'customer_id': 'C1', 'revenue': 45000}, {'customer_id': 'C2', 'revenue': 38000}, {'customer_id': 'C5', 'revenue': 32000}, {'customer_id': 'C8', 'revenue': 28500}, {'customer_id': 'C3', 'revenue': 24000}]",
"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 可以撰寫能有效率地處理多個項目的程式碼:
regions = ["West", "East", "Central", "North", "South"]
results = {}
for region in regions:
rows = json.loads(await query_database({"sql": f"<sql for {region}>"}))
results[region] = sum(row["revenue"] for row in rows)
# 以程式化方式處理結果
top_region = max(results.items(), key=lambda x: x[1])
print(f"Top region: {top_region[0]} with ${top_region[1]:,} in revenue")此模式:
Claude 可以在達成成功條件後立即停止處理:
endpoints = ["us-east", "eu-west", "apac"]
for endpoint in endpoints:
status = await check_health({"endpoint": endpoint})
if status == "healthy":
print(f"Found healthy endpoint: {endpoint}")
break # Stop early, don't check remainingpath = "/tmp/example.txt"
file_info = json.loads(await get_file_info({"path": path}))
if file_info["size"] < 10000:
content = await read_full_file({"path": path})
else:
content = await read_file_summary({"path": path})
print(content)server_id = "srv-01"
log_text = await fetch_logs({"server_id": server_id})
errors = [line for line in log_text.splitlines() if "ERROR" in line]
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 | 回應中 code_execution_tool_result 錯誤區塊上的 error_code | 傳遞給程式碼執行工具的參數無效 | 請參閱程式碼執行工具錯誤 |
invalid_request_error(於 tool_choice) | HTTP 400 錯誤回應 | tool_choice 指定了一個 allowed_callers 不包含 "direct" 的工具 | 在該工具的 allowed_callers 中加入 "direct",或將該工具從 tool_choice 中移除,讓 Claude 從程式碼中呼叫它 |
如果您的工具結果未在約 4 分鐘內送達,待處理的呼叫會在 Claude 執行中的程式碼內引發 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 (no response after 270s).",
"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 不支援程式化呼叫若自訂工具的 input_schema 包含遞迴 $ref(參照循環,例如參照自身的結構描述),則無法啟用程式化呼叫。在此類工具的 allowed_callers 中包含程式碼執行工具版本,會導致請求失敗並回傳 400 invalid_request_error,其訊息包含 Circular $ref detected。相同的結構描述在直接工具呼叫中則可被接受。
若要解決此問題,請執行下列其中一項:
allowed_callers(或將其設為 ["direct"]),讓該工具維持僅限直接呼叫。同一請求中的其他工具仍可使用程式化呼叫。description 中描述任何更深層的巢狀結構,或將遞迴屬性替換為一個純粹的 {"type": "object"},並在其 description 中說明預期的結構。下列工具無法以程式化方式呼叫:
computer_toolset_20260801 與 browser_toolset_20260801),其 allowed_callers 欄位僅接受 "direct"回應程式化工具呼叫時,有嚴格的格式要求:
僅含工具結果的回應: 如果有待處理的程式化工具呼叫正在等待結果,您的回應訊息必須僅包含 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}]"
}
]
}此限制僅適用於回應程式化(程式碼執行)工具呼叫時。對於一般的用戶端工具呼叫,您可以在工具結果之後包含文字內容。
僅限文字的工具結果內容: 回應程式化呼叫的每個 tool_result 的 content 必須是字串或 text 區塊。圖片、文件及其他內容區塊類型會被拒絕。
程式化工具呼叫與一般工具呼叫受相同的速率限制約束。來自程式碼執行的每次工具呼叫都計為一次獨立的呼叫。
在實作將以程式化方式呼叫的使用者定義工具時:
程式化工具呼叫透過三種方式減少 token 消耗:
例如,直接呼叫 10 個工具所使用的 token,約為以程式化方式呼叫並回傳摘要的 10 倍。
在 Anthropic 針對正式環境 Claude 模型的內部評估中:
tools 陣列包含 10 到 49 個工具定義的請求,在啟用程式化工具呼叫後,通常可節省 20% 到 40% 的 token。實際節省幅度因工作負載型態而異。請參閱何時使用程式化呼叫。
程式化工具呼叫採用與程式碼執行相同的定價。詳情請參閱程式碼執行定價。
程式化工具呼叫以少量固定的額外負擔(容器啟動、腳本產生)換取工具結果 token 與模型往返次數的大幅節省。這項取捨是否划算取決於工作負載型態。
非常適合:
不太適合:
如果您不確定,請在廣泛啟用之前,先以具代表性的流量樣本,測量有無 allowed_callers 時的計費輸入 token。
設定 tool_choice 時出現 invalid_request_error
tool_choice 不能指定 allowed_callers 省略了 "direct" 的工具。請在該工具的 allowed_callers 中加入 "direct",或將該工具從 tool_choice 中移除,讓 Claude 從程式碼中呼叫它。容器到期
expires_at 時間戳記之前儘早回應每個程式化工具呼叫。Claude 的程式碼約在 4 分鐘後停止等待結果,而閒置容器目前約在 5 分鐘後被回收。工具結果未正確解析
caller 欄位以確認程式化呼叫Claude 以大量程式碼進行訓練,因此將工具呈現為可呼叫的 Python 函式,能讓它發揮這項優勢:
程式化工具呼叫是一種可通用的模式,也可以在您自己的基礎架構上實作。以下是各種方法的比較:
為 Claude 提供一個程式碼執行工具,並描述該環境中有哪些可用函式。當 Claude 以程式碼呼叫該工具時,您的應用程式會在定義這些函式的本機環境中執行它。
優點:
缺點:
適用時機: 您的應用程式可以安全地執行任意程式碼、您想要最精簡的實作,且 Anthropic 的託管方案不符合您的需求。
從 Claude 的角度來看方法相同,但程式碼在具有安全限制(例如無網路對外連線)的沙箱容器中執行。如果您的工具需要外部資源,您將需要一套在沙箱外執行工具呼叫的協定。
優點:
缺點:
適用時機: 安全性至關重要,且 Anthropic 的託管解決方案不符合您的需求。
Anthropic 的程式化工具呼叫是沙箱執行的託管版本,具備為 Claude 調校、帶有既定設計取向的 Python 環境。Anthropic 負責處理容器管理、程式碼執行以及安全的工具呼叫通訊。
優點:
如果您使用的是 Claude API、Claude Platform on AWS 或 Microsoft Foundry,請考慮使用 Anthropic 的託管解決方案。在 Microsoft Foundry 上,程式化工具呼叫需要 Hosted on Anthropic 部署。
程式化工具呼叫建構於程式碼執行基礎架構之上,並使用相同的沙箱容器。容器資料(包括執行產物與輸出)最多保留 30 天。
如需所有功能的 ZDR 資格資訊,請參閱 API 與資料保留。
為對延遲敏感的應用程式串流工具輸入,無需伺服器端 JSON 緩衝。
在沙箱容器中執行 Python 與 bash 程式碼,以分析資料、產生檔案並反覆改進解決方案。
將 Claude 連接到外部工具與 API。了解工具在何處執行、Claude 何時呼叫它們,以及哪種工具適合您的任務。
指定工具結構描述、撰寫有效的描述,並控制 Claude 何時呼叫您的工具。
Was this page helpful?