工具调用
工具调用(Function Calling)让模型在需要时请求执行你提供的函数,例如查询数据库或调用外部接口。模型负责决定调用哪个函数、传什么参数,函数由你的程序执行,结果再交还给模型生成最终回答。
是否支持工具调用因模型而异,在模型列表的「能力」一列查看。
调用流程
- 请求里带上
tools,描述可用的函数。 - 模型认为需要调用函数时,返回
tool_calls,其中有函数名和参数。 - 你的程序执行函数,把结果作为
tool消息追加到对话里,再次请求。 - 模型根据函数结果生成回答。
完整示例
python
import json
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["HIHAI_API_KEY"],
base_url="https://gateway.hihapi.com/v1",
)
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "查询指定城市当前的天气",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名,例如 成都"}
},
"required": ["city"],
},
},
}
]
def get_weather(city: str) -> dict:
return {"city": city, "temperature": 21, "condition": "晴"}
messages = [{"role": "user", "content": "成都今天天气怎么样?"}]
response = client.chat.completions.create(model="deepseek-flash", messages=messages, tools=tools)
message = response.choices[0].message
if message.tool_calls:
messages.append(message)
for call in message.tool_calls:
arguments = json.loads(call.function.arguments)
result = get_weather(**arguments)
messages.append(
{
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result, ensure_ascii=False),
}
)
response = client.chat.completions.create(model="deepseek-flash", messages=messages, tools=tools)
print(response.choices[0].message.content)要点
- 描述写清楚:模型靠
description判断何时调用,函数和每个参数的用途都要写明白。 - 参数是字符串:
function.arguments是 JSON 字符串,使用前先解析。模型偶尔会生成不合法的 JSON,解析失败时要有兜底处理。 - 原样回传模型的消息:把模型返回的那条带
tool_calls的消息完整追加到messages,不要只保留文本。 - 编号要对应:每条
tool消息的tool_call_id必须等于对应调用的id。 - 可能一次调用多个函数:
tool_calls是数组,逐个执行并逐个回传结果。 - 校验参数:函数会真实执行,执行前在你的程序里校验参数,不要直接信任模型的输出。
在 Messages 协议下
Messages 协议同样支持工具调用,结构略有不同:工具用 input_schema 描述参数,模型的调用出现在 type 为 tool_use 的内容块里,函数结果用 type 为 tool_result 的内容块回传。使用 Anthropic SDK 时按它的原生写法即可。
常见问题
模型没有调用工具,直接回答了
通常是函数描述不够明确,或用户的问题不需要工具。完善 description,或在系统指令里说明什么情况下应该调用。
提示模型不支持此功能
该模型不支持工具调用,对应错误 AI_UNSUPPORTED_FEATURE。换用支持工具调用的模型。
第二次请求报参数错误
多数是历史消息不完整:缺少模型返回的带 tool_calls 的消息,或 tool_call_id 对不上。