指南
工具调用
两个模型都使用 OpenAI 格式调用工具:你描述函数,模型请求调用其中一个,你运行它并把结果发回。
核对于 2026年10月26日
循环流程
- 发送
tools:每一项都是一个函数,包含名称、描述和 JSON Schema 格式的参数。 - 当模型需要调用工具时,回复的
finish_reason为tool_calls,message.tool_calls列出这些调用,参数为 JSON 字符串。 - 逐一运行它们,并添加一条
tool消息,附上对应的tool_call_id和结果。 - 再次发送对话。重复此过程,直到
finish_reason为stop。
import json
import os
from openai import OpenAI
client = OpenAI(
base_url="https://nokeep.ai/v1",
api_key=os.environ["NOKEEP_API_KEY"],
)
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Today's weather in a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
def get_weather(city):
return {"city": city, "high_c": 21, "sky": "clear"}
messages = [{"role": "user", "content": "Should I bring a jacket in Lisbon today?"}]
while True:
reply = client.chat.completions.create(model="deepseek-v4.1-flash-uncensored", messages=messages, tools=tools)
message = reply.choices[0].message
messages.append(message)
if not message.tool_calls:
print(message.content)
break
for call in message.tool_calls:
result = get_weather(**json.loads(call.function.arguments))
messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})tool_choice
| 模型 | 支持 |
|---|---|
deepseek-v4.1-flash-uncensored | auto、none、required,或指定的函数名。另支持 parallel_tool_calls。 |
glm-5.3-flash-uncensored | auto 或 none。它自行选择工具;其他任何值都会返回 400 unsupported_tool_choice。 |
注意事项
- 每条
tool消息都必须带有它所回应的tool_call_id,否则该调用会被拒绝,返回400 invalid_messages。 - 工具的 schema 会随每个请求一起发送,并计为输入 token。
- 模型本身不运行任何东西。由你的代码运行工具,因此由你决定它们能访问什么。