Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
本頁涵蓋平行工具呼叫:當 Claude 在一次轉換中呼叫多個工具時、如何格式化訊息歷史以保持平行性,以及如何停用它。如需單一呼叫流程,請參閱處理工具呼叫。
根據預設,Claude 可能會使用多個工具來回答使用者查詢。您可以透過以下方式停用此行為:
auto 時設定 disable_parallel_tool_use=true,這確保 Claude 最多使用一個工具any 或 tool 時設定 disable_parallel_tool_use=true,這確保 Claude 恰好使用一個工具使用 Tool Runner 更簡單:下面的範例顯示手動平行工具處理。對於大多數使用案例,Tool Runner 會自動處理平行工具執行,程式碼少得多。
以下是一個完整的、可執行的指令碼,用於測試和驗證平行工具呼叫是否正常運作:
# Define tools
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"],
},
},
]
# Test conversation with parallel tool calls
messages = [
{
"role": "user",
"content": "What's the weather in SF and NYC, and what time is it there?",
}
]
# Make initial request
print("Requesting parallel tool calls...")
response = client.messages.create(
model="claude-opus-4-7", max_tokens=1024, messages=messages, tools=tools
)
# Check for parallel tool calls
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")
# Simulate tool execution and format results correctly
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}
)
# Continue conversation with tool results
messages.extend(
[
{"role": "assistant", "content": response.content},
{"role": "user", "content": tool_results}, # All results in one message!
]
)
# Get final response
print("\nGetting final response...")
final_response = client.messages.create(
model="claude-opus-4-7", max_tokens=1024, messages=messages, tools=tools
)
print(f"\nClaude's response:\n{final_response.content[0].text}")
# Verify formatting
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 有效地進行平行工具呼叫。
雖然 Claude 4 模型預設具有出色的平行工具使用功能,但您可以透過有針對性的提示在所有模型中增加平行工具執行的可能性:
如果 Claude 在預期時沒有進行平行工具呼叫,請檢查這些常見問題:
1. 工具結果格式不正確
最常見的問題是在對話歷史中格式化工具結果不正確。這會「教導」Claude 避免平行呼叫。
特別是對於平行工具使用:
// ❌ This reduces 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
]
// ✅ This 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. 測量平行工具使用
若要驗證平行工具呼叫是否正常運作:
# Calculate average tools per tool-calling message
tool_call_messages = [
msg for msg in messages if any(block.type == "tool_use" for block in msg.content)
]
total_tool_calls = sum(
len([b for b in msg.content if b.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}")
# Should be > 1.0 if parallel calls are workingtool_result 格式化規則,請參閱處理工具呼叫。Was this page helpful?