文档 · 模型能力
工具调用
工具调用(Function Calling)让模型按你定义的函数返回结构化调用;你的代码执行函数后,把结果交还模型继续作答。适用于带「工具调用」能力的模型。
完整流程
- 1在
tools中用 JSON Schema 描述函数。 - 2模型返回
tool_calls(finish_reason为tool_calls)。 - 3你的代码执行函数,把结果作为
role: "tool"消息(带对应的tool_call_id)追加到对话。 - 4再次请求,模型基于工具结果给出最终回答。
import json
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string", "description": "City name, e.g. Tokyo"}},
"required": ["city"],
},
},
}]
messages = [{"role": "user", "content": "What's the weather in Tokyo?"}]
resp = client.chat.completions.create(model="gpt-4.1-mini", messages=messages, tools=tools)
msg = resp.choices[0].message
if msg.tool_calls:
messages.append(msg) # 1. keep the assistant's tool_calls
for call in msg.tool_calls:
args = json.loads(call.function.arguments) # 2. run the tool in your code
result = {"city": args["city"], "temp_c": 22, "sky": "clear"}
messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})
final = client.chat.completions.create(model="gpt-4.1-mini", messages=messages, tools=tools)
print(final.choices[0].message.content) # 3. the model answers using the result控制调用方式
| tool_choice | 行为 |
|---|---|
"auto"(默认) | 模型自行决定是否调用 |
"none" | 不调用工具 |
"required" | 必须调用至少一个工具 |
{"type": "function", "function": {"name": "..."}} | 强制调用指定函数 |
部分较新的模型不支持强制调用(
required 或指定函数),会返回 400。此时请使用 auto,并在提示词中说明何时应调用哪个工具。并行调用
模型可能一次返回多个 tool_calls。全部执行后,每个结果各一条 tool 消息(tool_call_id 一一对应),一起发回。
Anthropic 格式
原生格式中工具用 input_schema 描述,调用结果以 tool_use / tool_result 内容块往返:
resp = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
tools=[{
"name": "get_weather",
"description": "Get the current weather for a city",
"input_schema": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
}],
messages=[{"role": "user", "content": "What's the weather in Tokyo?"}],
)
# When stop_reason == "tool_use", content holds tool_use blocks; run them and reply with:
# {"role": "user", "content": [{"type": "tool_result", "tool_use_id": block.id, "content": "..."}]}建议
- 函数名和描述写清楚「做什么、何时用」,这是模型选择工具的主要依据。
- 参数 schema 尽量严格:用
enum、required,避免含糊的自由文本。 - 执行前校验参数:模型给出的参数可能不合法,始终用 JSON 解析而不是字符串匹配。
- 工具返回结果尽量精简,只给模型需要的字段,可以节省输入 tokens。