跳到主要内容

Tool Use(工具调用)

import anthropic

client = anthropic.Anthropic(api_key="your-api-key", base_url="https://www.cheapertoken.work")

tools = [
{
"name": "get_weather",
"description": "获取指定城市的天气",
"input_schema": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名称"}
},
"required": ["city"]
}
}
]

response = client.messages.create(
model="claude-opus-4-7",
max_tokens=1024,
tools=tools,
messages=[{"role": "user", "content": "广州今天天气怎么样?"}]
)

for block in response.content:
if block.type == "tool_use":
print(f"调用工具: {block.name}, 参数: {block.input}")

完整工具调用循环

import anthropic

client = anthropic.Anthropic(api_key="your-api-key", base_url="https://www.cheapertoken.work")

def get_weather(city: str) -> str:
return f"{city}今天晴天,25°C"

tools = [
{
"name": "get_weather",
"description": "获取指定城市的天气",
"input_schema": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"]
}
}
]

messages = [{"role": "user", "content": "北京天气怎么样?"}]

while True:
response = client.messages.create(
model="claude-opus-4-7",
max_tokens=1024,
tools=tools,
messages=messages
)

if response.stop_reason == "end_turn":
print(response.content[0].text)
break

tool_results = []
for block in response.content:
if block.type == "tool_use":
result = get_weather(**block.input)
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": result
})

messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": tool_results})