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?