函数调用(也叫工具使用)让模型不直接回答,而是请你的代码去运行某个函数:查询天气 API、查询数据库或做一次计算,然后用结果完成回答。模型自己从不运行任何东西;它只返回一个“用某些参数调用某个函数”的请求,由你的代码决定是否真正执行。
请求结构
你用 JSON Schema 描述每个可用的函数:名称、说明,以及参数的结构。
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"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
},
"required": ["city"],
},
},
}]
模型依靠函数说明和参数说明来决定何时以及如何调用函数,所以要像向另一个人解释这个函数那样去写,而不只是写一个类型签名。
完整的多轮示例
工具调用并不意味着对话结束。模型会暂停,你运行函数,再把结果放进一条新消息发回去,模型才能继续。
import json
from openai import OpenAI
client = OpenAI(base_url="https://aidiscount.ai/v1", api_key=os.environ["AIDISCOUNT_API_KEY"])
def get_weather(city, unit="celsius"):
return {"city": city, "temperature": 18, "unit": unit, "condition": "cloudy"}
messages = [{"role": "user", "content": "What's the weather in Tokyo right now?"}]
resp = client.chat.completions.create(model="gpt-6-luna", messages=messages, tools=tools)
msg = resp.choices[0].message
messages.append(msg)
if msg.tool_calls:
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
result = get_weather(**args)
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result),
})
final = client.chat.completions.create(model="gpt-6-luna", messages=messages, tools=tools)
print(final.choices[0].message.content)
这个示例依赖的几个要点:先追加助手的工具调用消息,再追加工具结果;让每个 tool_call_id 与它所回应的调用对应;content 要以字符串形式发送(对象用 json.dumps 编码)。
一轮中的多个工具调用
模型可以一次请求多个工具调用,比如同时查询三个城市的天气。遍历 msg.tool_calls,为每个调用追加一条 "role": "tool" 消息,各自带上自己的 tool_call_id,然后再调用模型。
Anthropic Messages 格式
结构有所不同:每个工具的 schema 放在 input_schema 而不是 function.parameters 中,工具调用以 tool_use 内容块的形式返回,结果则以 tool_result 内容块的形式放在一条 user 消息中发回。
import anthropic
client = anthropic.Anthropic(base_url="https://aidiscount.ai", api_key=os.environ["AIDISCOUNT_API_KEY"])
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 right now?"}]
resp = client.messages.create(model="claude-opus-4-8", max_tokens=1024, messages=messages, tools=tools)
messages.append({"role": "assistant", "content": resp.content})
tool_use = next(b for b in resp.content if b.type == "tool_use")
result = get_weather(**tool_use.input)
messages.append({
"role": "user",
"content": [{"type": "tool_result", "tool_use_id": tool_use.id, "content": json.dumps(result)}],
})
final = client.messages.create(model="claude-opus-4-8", max_tokens=1024, messages=messages, tools=tools)
print(final.content[0].text)
强制或禁用工具调用
默认由模型决定是否调用工具。要强制调用某个特定工具,传入 tool_choice={"type": "function", "function": {"name": "get_weather"}}(OpenAI 格式)或 tool_choice={"type": "tool", "name": "get_weather"}(Anthropic 格式)。如果想在某次请求中保留工具定义但不让模型调用工具,设置 tool_choice="none"(OpenAI 格式)或 tool_choice={"type": "none"}(Anthropic 格式)。
常见错误
- 用错误的角色返回工具结果。OpenAI 格式要求
"role": "tool";它不接受以普通 user 或 assistant 消息返回的结果。 - 忘记把助手的工具调用消息发回去。模型需要在历史记录中看到自己的工具调用,才能把它和结果对应起来。
- 在
content中发送原始 Python 对象,而不是 JSON 字符串。始终用json.dumps序列化。 - 运行函数前不校验参数。把工具调用参数当作来自模型的不可信输入;在使用之前校验类型和取值范围,尤其是在把它们用于数据库查询或 shell 命令之前。
选择模型
AIDiscount 上的大多数现有模型都支持工具调用;模型市场中模型页面的能力列表会注明。部分支持工具调用的模型当前价格:
| 模型 | 输入 / 百万 tokens | 输出 / 百万 tokens | 对比官方价格 |
|---|---|---|---|
GPT-6 Lunagpt-6-luna | $0.05 | $0.30 | 优惠 40% |
Claude Opus 4.8claude-opus-4-8 | $0.375 | $1.875 | 优惠 92.5% |
DeepSeek V4 Prodeepseek-v4-pro | $0.3857 | $1.1571 | 优惠 41.6% |
Kimi K3kimi-k3 | $1.714 | $8.571 | 优惠 42.9% |
GLM-5.3glm-5.3 | $0.6857 | $2.40 | 优惠 45.5% |