函数调用与工具
函数调用允许模型调用你的代码 — 查询数据、修改状态或调用外部 API — 并把结果带回到后续推理中。你声明可用的工具,模型决定何时以何种参数调用它们。
build
模型永远不会执行你的代码。
它只会以 JSON 参数对象的形式给出结构化意图。
由你的应用执行函数,并将结果作为
tool 消息回传。
工具调用流程
-
声明工具
每个工具都是一份 JSON Schema,包含名称、用途和参数说明。
-
发起请求
在对话补全调用中带上
tools数组。可选地用tool_choice强制或禁止调用。 -
执行并回传
当
finish_reason为tool_calls时,依次执行每次调用,并将结果以role: "tool"消息追加。 -
让模型收尾
带上新的历史再次调用 API。模型将综合工具输出给出自然语言答案。
声明工具
一个工具定义包含三部分:name、description 和 JSON Schema 形式的 parameters。工具自身与每个参数的清晰描述,比其他任何细节都更重要。
[
{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取某个城市的当前气温。",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "IANA 城市名称,例如 '上海'。"},
"unit": {"type": "string", "enum": ["c", "f"]}
},
"required": ["city"]
}
}
}
]
控制工具选择
tool_choice | 行为 |
|---|---|
"auto" (默认) | 由模型决定是否调用工具或直接回答。 |
"none" | 本次请求忽略工具。 |
"required" | 模型必须调用至少一个工具。 |
{"type":"function","function":{"name":"get_weather"}} | 强制调用指定工具。 |
端到端示例
一次完整往返:声明工具、模型请求调用、执行工具、回传结果、获得最终回答。
import json, os
from openai import OpenAI
client = OpenAI(base_url="https://api.wylon.cn/v1", api_key=os.environ["WYLON_API_KEY"])
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取某个城市的当前气温。",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
def get_weather(city):
return {"city": city, "temp_c": 22}
messages = [{"role": "user", "content": "上海现在天气如何?"}]
# 1. 模型决定调用工具
first = client.chat.completions.create(
model="moonshotai/kimi-k2.5", messages=messages, tools=tools,
)
messages.append(first.choices[0].message)
# 2. 执行每次工具调用并追加结果
for call in first.choices[0].message.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),
})
# 3. 让模型生成最终答案
final = client.chat.completions.create(
model="moonshotai/kimi-k2.5", messages=messages, tools=tools,
)
print(final.choices[0].message.content)
import OpenAI from "openai";
const client = new OpenAI({ baseURL: "https://api.wylon.cn/v1", apiKey: process.env.WYLON_API_KEY });
const tools = [{
type: "function",
function: {
name: "get_weather",
description: "获取某个城市的当前气温。",
parameters: { type: "object", properties: { city: { type: "string" } }, required: ["city"] },
},
}];
const getWeather = (city) => ({ city, temp_c: 22 });
const messages = [{ role: "user", content: "上海现在天气如何?" }];
const first = await client.chat.completions.create({ model: "moonshotai/kimi-k2.5", messages, tools });
messages.push(first.choices[0].message);
for (const call of first.choices[0].message.tool_calls ?? []) {
const args = JSON.parse(call.function.arguments);
messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(getWeather(args.city)) });
}
const final = await client.chat.completions.create({ model: "moonshotai/kimi-k2.5", messages, tools });
console.log(final.choices[0].message.content);
并行工具调用
现代模型可以在一轮中发出多次工具调用。遍历 message.tool_calls,
为每次调用追加一条以 tool_call_id 为键的 role: "tool" 消息。
模型会在下一步综合所有结果。
最佳实践
- 工具名以动词命名。
get_weather、create_ticket— 而非weather或ticket。 - 描述每个参数。包含单位、格式、枚举值范围。
- 控制工具数量。单次请求 10–20 个工具较为稳妥;超过时可先用检索筛选短列表。
- 校验输入。Schema 校验可在执行代码前拦截模型臆想出的参数。
- 返回结构化 JSON。比散文更易被模型解读。