Tool Use(工具调用)是构建 AI Agent 的核心能力——让 Claude 能够调用你定义的函数,获取实时数据、执行操作、与外部系统交互。本文从原理到实战完整讲解。
工作原理
你定义工具 -> 发送给 Claude -> Claude 决定是否调用
-> 你执行工具 -> 把结果发回 -> Claude 基于结果给出最终答案
Claude 本身不执行工具,它只是决定调用哪个工具、传什么参数。实际执行由你的代码完成。
基础示例:天气查询工具
python
import anthropic, json
client = anthropic.Anthropic()
# Step 1:定义工具(JSON Schema)
tools = [{
"name": "get_weather",
"description": "Get current weather for a location. Returns temperature and conditions.",
"input_schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City name, e.g. Shanghai, Beijing"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "Temperature unit"
}
},
"required": ["location"]
}
}]
# Step 2:发送请求(带工具定义)
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
tools=tools,
messages=[{"role": "user", "content": "What's the weather in Shanghai?"}]
)
# Step 3:处理工具调用请求
if response.stop_reason == 'tool_use':
tool_use_block = next(b for b in response.content if b.type == 'tool_use')
tool_name = tool_use_block.name
tool_input = tool_use_block.input
print(f'Claude wants to call: {tool_name}({tool_input})')
# Step 4:你来执行工具(这里是模拟)
if tool_name == 'get_weather':
result = {'temperature': 22, 'condition': 'Sunny', 'humidity': '60%'}
# Step 5:把工具结果发回给 Claude
final_response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
tools=tools,
messages=[
{"role": "user", "content": "What's the weather in Shanghai?"},
{"role": "assistant", "content": response.content},
{
"role": "user",
"content": [{
"type": "tool_result",
"tool_use_id": tool_use_block.id,
"content": json.dumps(result)
}]
}
]
)
print(final_response.content[0].text)多工具定义
python
tools = [
{
"name": "search_web",
"description": "Search the web for current information",
"input_schema": {
"type": "object",
"properties": {"query": {"type": "string"}},
"required": ["query"]
}
},
{
"name": "get_stock_price",
"description": "Get current stock price for a ticker symbol",
"input_schema": {
"type": "object",
"properties": {
"ticker": {"type": "string", "description": "Stock ticker, e.g. AAPL"}
},
"required": ["ticker"]
}
},
{
"name": "calculate",
"description": "Evaluate a mathematical expression",
"input_schema": {
"type": "object",
"properties": {"expression": {"type": "string"}},
"required": ["expression"]
}
}
]并行工具调用
Claude 可以在一次响应中调用多个工具(并行):
python
def process_tool_calls(response, tools_dict):
tool_results = []
for block in response.content:
if block.type == 'tool_use':
func = tools_dict.get(block.name)
if func:
result = func(**block.input)
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": json.dumps(result)
})
return tool_results
# 工具实现映射
tools_dict = {
'get_weather': lambda location, unit='celsius': {'temp': 22, 'unit': unit},
'get_stock_price': lambda ticker: {'ticker': ticker, 'price': 150.25},
'calculate': lambda expression: {'result': eval(expression)}
}完整 Agent 循环
python
def run_agent(user_message, tools, tools_dict, max_steps=10):
messages = [{"role": "user", "content": user_message}]
for step in range(max_steps):
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=4096,
tools=tools,
messages=messages
)
messages.append({"role": "assistant", "content": response.content})
# 任务完成
if response.stop_reason == 'end_turn':
return next(b.text for b in response.content if b.type == 'text')
# 执行工具调用
if response.stop_reason == 'tool_use':
tool_results = process_tool_calls(response, tools_dict)
messages.append({"role": "user", "content": tool_results})
return 'Max steps reached'
result = run_agent(
'Search for the latest Claude Code news and calculate how many days since its launch',
tools, tools_dict
)
print(result)控制工具调用行为
python
# 强制调用特定工具
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
tools=tools,
tool_choice={"type": "tool", "name": "get_weather"}, # 强制调用
messages=[{"role": "user", "content": "Tell me about Shanghai"}]
)
# 禁止调用工具(纯文本回复)
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
tools=tools,
tool_choice={"type": "none"},
messages=[{"role": "user", "content": "What can you do?"}]
)常见错误
错误 1:tool_result 顺序错误 tool_result 必须紧跟在包含 tool_use 的 assistant 消息之后。
错误 2:tool_use_id 不匹配 tool_result 里的 tool_use_id 必须和 Claude 请求里的完全一致。
错误 3:description 写得不够清楚 Claude 根据 description 决定何时调用工具,描述越准确调用越准确。
来源:Tool Use Overview - Anthropic 官方文档