用户指南
工具调用使用指南
使用 tools 描述外部函数,校验模型参数、执行工具并回传结果。
使用 tools 描述外部函数,校验模型参数、执行工具并回传结果。
模型不会直接执行你的函数。它返回结构化调用意图,应用校验并执行工具,再把结果作为 tool 消息加入下一次请求。
完整执行流程
定义 tools 发送用户问题 → 模型返回 tool_calls → 应用执行工具 回传 tool 消息
天气工具示例
import json
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["APIQIK_API_KEY"],
base_url="https://api.dimleap.cn/v1",
)
tools = [{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "获取指定城市的当前天气",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "城市名称,例如:北京",
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
},
},
"required": ["city"],
"additionalProperties": False,
},
},
}]
messages = [
{"role": "user", "content": "北京现在天气怎么样?请用摄氏度回答。"}
]
first = client.chat.completions.create(
model="glm-5.1",
messages=messages,
tools=tools,
tool_choice="auto",
)
assistant = first.choices[0].message
if not assistant.tool_calls:
print(assistant.content)
raise SystemExit
messages.append({
"role": "assistant",
"content": assistant.content,
"tool_calls": [
{
"id": call.id,
"type": call.type,
"function": {
"name": call.function.name,
"arguments": call.function.arguments,
},
}
for call in assistant.tool_calls
],
})
for call in assistant.tool_calls:
if call.function.name != "get_current_weather":
raise ValueError("不允许的工具")
arguments = json.loads(call.function.arguments)
city = arguments["city"]
unit = arguments.get("unit", "celsius")
# 实际项目在这里调用真实天气服务。
result = {
"city": city,
"temperature": 22,
"unit": unit,
"condition": "晴",
}
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result, ensure_ascii=False),
})
final = client.chat.completions.create(
model="glm-5.1",
messages=messages,
tools=tools,
)
print(final.choices[0].message.content)参数结构
| 字段 | 说明 |
|---|---|
tools[].type | 函数工具使用 function。 |
function.name | 应用能够识别并允许执行的函数名称。 |
function.description | 说明何时应该使用该工具,帮助模型正确选择。 |
function.parameters | 用 JSON Schema 描述参数类型、枚举和必填字段。 |
tool_choice | auto 让模型选择回复文本或调用工具。 |
message.tool_calls | 模型生成的调用列表,可能同时包含多个调用。 |
function.arguments | JSON 字符串;解析后仍必须做业务校验。 |
tool_call_id | 把工具结果关联回对应的模型调用。 |
安全边界
- 工具名称采用允许列表,不执行模型凭空生成的函数。
- 参数通过 JSON Schema 和业务规则双重校验。
- 写数据库、付款、发消息等有副作用操作必须做权限校验和确认。
- 为工具设置超时、返回大小限制和错误格式,避免无限等待。
- 工具结果属于不可信输入,回传模型前做清洗和必要的脱敏。