預設情況下,Claude 可能會在單一回應中呼叫多個工具。本頁面說明如何執行這些呼叫、如何格式化訊息歷史記錄以維持平行處理的運作,以及在需要時如何停用平行工具使用。關於單一呼叫流程,請參閱處理工具呼叫。
當 Claude 呼叫工具時,回應的 stop_reason 為 tool_use,且單一助理回合中可包含多個 tool_use 區塊。如何執行這些呼叫由您決定。API 並未規定執行順序:您可以並行執行這些呼叫(Promise.all、asyncio.gather)、依照出現順序依序執行,或採用任何適合您工具的組合方式。
請根據工具的用途選擇策略。獨立的唯讀操作通常可以安全地平行執行,以降低「latency」(延遲)。具有副作用、共享狀態或順序需求的工具,可能較適合依序執行。
無論您採用哪種策略,都要為每個 tool_use 區塊回傳一個 tool_result,並全部放在下一則使用者訊息中。使用 tool_use_id 將每個結果對應到其呼叫,並將所有 tool_result 區塊放在該訊息中任何文字內容之前。完整的格式化規則請參閱處理工具呼叫。如果您選擇不執行某個特定呼叫(例如,因為您依序執行批次且較早的呼叫失敗),仍需為其回傳一個 tool_result,並設定 is_error: true 及簡短說明。
{
"type": "tool_result",
"tool_use_id": "toolu_02",
"is_error": true,
"content": "Not executed: the preceding write_file call failed."
}大多數應用程式請使用 Tool Runner: SDK 的 Tool Runner 會處理包含多個工具呼叫的回應,並為您格式化結果,因此您無需自行撰寫此處理邏輯。當您需要直接控制呼叫的執行方式時(例如自訂批次處理、排序或錯誤處理),請使用本頁面的手動模式。
以下指令碼會發送一個應觸發平行工具呼叫的請求、驗證回應是否包含這些呼叫,並格式化工具結果以維持平行處理的運作。請在環境中設定 ANTHROPIC_API_KEY 後執行:
client = Anthropic()
# 定義工具
tools = [
{
"name": "get_weather",
"description": "Get the current weather in a given location",
"input_schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
}
},
"required": ["location"],
},
},
{
"name": "get_time",
"description": "Get the current time in a given timezone",
"input_schema": {
"type": "object",
"properties": {
"timezone": {
"type": "string",
"description": "The timezone, e.g. America/New_York",
}
},
"required": ["timezone"],
},
},
]
# 測試包含平行工具呼叫的對話
messages = [
{
"role": "user",
"content": "What's the weather in SF and NYC, and what time is it there?",
}
]
# 發出初始請求
print("Requesting parallel tool calls...")
response = client.messages.create(
model="claude-opus-4-8", max_tokens=1024, messages=messages, tools=tools
)
# 檢查平行工具呼叫
tool_uses = [block for block in response.content if block.type == "tool_use"]
print(f"\n✓ Claude made {len(tool_uses)} tool calls")
if len(tool_uses) > 1:
print("✓ Parallel tool calls detected!")
for tool in tool_uses:
print(f" - {tool.name}: {tool.input}")
else:
print("✗ No parallel tool calls detected")
# 模擬工具執行並正確格式化結果
tool_results = []
for tool_use in tool_uses:
if tool_use.name == "get_weather":
if "San Francisco" in str(tool_use.input):
result = "San Francisco: 68°F, partly cloudy"
else:
result = "New York: 45°F, clear skies"
else: # get_time
if "Los_Angeles" in str(tool_use.input):
result = "2:30 PM PST"
else:
result = "5:30 PM EST"
tool_results.append(
{"type": "tool_result", "tool_use_id": tool_use.id, "content": result}
)
# 使用工具結果繼續對話
messages.extend(
[
{"role": "assistant", "content": response.content},
{"role": "user", "content": tool_results}, # All results in one message!
]
)
# 取得最終回應
print("\nGetting final response...")
final_response = client.messages.create(
model="claude-opus-4-8", max_tokens=1024, messages=messages, tools=tools
)
final_text = next(
block.text for block in final_response.content if block.type == "text"
)
print(f"\nClaude's response:\n{final_text}")
# 驗證格式
print("\n--- Verification ---")
print(f"✓ Tool results sent in single user message: {len(tool_results)} results")
print("✓ No text before tool results in content array")
print("✓ Conversation formatted correctly for future parallel tool use")結尾的摘要行重申了維持平行處理運作的兩項格式化規則:所有工具結果都在單一使用者訊息中回傳,且該訊息中的工具結果之前不出現任何文字內容。
當請求能從多個工具中受益時,Claude 4 模型預設會進行平行工具呼叫。對於所有模型,您可以透過針對性的提示來提高平行工具呼叫的可能性:
平行工具使用預設為開啟。若要關閉,請在 tool_choice 物件內設定 disable_parallel_tool_use: true。這不是頂層請求參數。其效果取決於 tool_choice 的類型。
當 tool_choice 類型為 auto(預設值)時,設定 disable_parallel_tool_use: true 表示 Claude 每次回應最多呼叫一個工具。Claude 仍可以純文字回答而不呼叫任何工具。醒目標示的行是與標準工具使用請求的唯一差異:
client = Anthropic()
response = client.messages.create(
model="claude-opus-4-8",
max_tokens=1024,
tools=[
{
"name": "get_weather",
"description": "Get the current weather in a given location",
"input_schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
}
},
"required": ["location"],
},
}
],
tool_choice={"type": "auto", "disable_parallel_tool_use": True},
messages=[
{
"role": "user",
"content": "What is the weather in San Francisco and New York?",
}
],
)
print(response.content)當 tool_choice 類型為 any 或 tool 時,設定 disable_parallel_tool_use: true 表示 Claude 恰好呼叫一個工具。以下範例使用 any。相同的欄位也適用於 tool:
client = Anthropic()
response = client.messages.create(
model="claude-opus-4-8",
max_tokens=1024,
tools=[
{
"name": "get_weather",
"description": "Get the current weather in a given location",
"input_schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
}
},
"required": ["location"],
},
}
],
tool_choice={"type": "any", "disable_parallel_tool_use": True},
messages=[
{
"role": "user",
"content": "What is the weather in San Francisco and New York?",
}
],
)
print(response.content)如果 Claude 在預期情況下未進行平行工具呼叫,請檢查以下常見問題:
1. 工具結果格式不正確
最常見的問題是在對話歷史記錄中錯誤地格式化工具結果。這會「教導」Claude 避免平行呼叫。
特別針對平行工具使用:
// Wrong: separate user messages reduce parallel tool use
[
{"role": "assistant", "content": [tool_use_1, tool_use_2]},
{"role": "user", "content": [tool_result_1]},
{"role": "user", "content": [tool_result_2]} // Separate message
]
// Correct: one user message with all results maintains parallel tool use
[
{"role": "assistant", "content": [tool_use_1, tool_use_2]},
{"role": "user", "content": [tool_result_1, tool_result_2]} // Single message
]其他格式化規則請參閱處理工具呼叫。
2. 提示力度不足
預設提示可能不夠。請使用最大化平行工具使用中較強的系統提示。
3. 測量平行工具使用情況
若要驗證平行工具呼叫是否正常運作:
messages = [] # Message objects returned by client.messages.create across your run
tool_call_messages = [
msg for msg in messages if any(block.type == "tool_use" for block in msg.content)
]
total_tool_calls = sum(
len([block for block in msg.content if block.type == "tool_use"])
for msg in tool_call_messages
)
avg_tools_per_message = (
total_tool_calls / len(tool_call_messages) if tool_call_messages else 0.0
)
print(f"Average tools per message: {avg_tools_per_message}")
# 若平行呼叫正常運作,應 > 1.04. 批次中的呼叫似乎彼此相依
執行順序由您決定。如果您的工具有順序相依性,依序執行批次並在第一次失敗時停止是有效的策略:對於任何未執行的呼叫回傳 is_error: true。如果您平行執行且某個呼叫因其前置條件尚未完成而失敗,請回傳 is_error: true 並附上自然的錯誤訊息。Claude 會在下一回合重新發出該呼叫。若要減少相依呼叫同時出現的情況,請將以下內容加入您的系統提示:「Only batch tool calls that are independent of each other.」(僅批次處理彼此獨立的工具呼叫。)
使用 SDK 的 Tool Runner 抽象層來自動處理代理迴圈、錯誤包裝及型別安全。
解析 tool_use 區塊、格式化 tool_result 回應,並使用 is_error 處理錯誤。
指定工具結構描述、撰寫有效的說明,並控制 Claude 何時呼叫您的工具。
Was this page helpful?