模型 API
工具调用与结构化输出
构建工具调用回合、校验函数参数,并用 JSON Schema 约束可验证的模型输出。
更新于
工具调用生命周期
tools 声明模型可以请求的函数,模型返回调用意图而非实际执行结果。你的应用负责校验参数、鉴权、执行工具,再把结果和 tool_call_id 一起放回后续消息。仅当模型和供应路线支持工具调用时启用。
Chat Completions body
{
"model": "YOUR_MODEL_ID",
"messages": [
{
"role": "user",
"content": "What is the weather in Hangzhou?"
}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Read the current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string"
}
},
"required": [
"city"
],
"additionalProperties": false
}
}
}
],
"tool_choice": "auto"
}参数校验与副作用
- 函数 arguments 通常是 JSON 字符串,需要解析并按自己的 schema 校验。
- 写入、支付、删除等操作应有应用侧授权和幂等控制,不能仅因为模型提出调用就执行。
- 为工具回合设置次数、耗时和输出长度预算,避免无限循环。
结构化输出
支持结构化输出的模型可使用 response_format 或协议对应配置。JSON Schema 支持范围依赖模型;先验证一份简单 schema,再加入嵌套结构。模型拒答、截断或工具调用时,不能假设一定会得到符合 schema 的最终文本。
Optional Chat Completions field
{
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "summary",
"strict": true,
"schema": {
"type": "object",
"properties": {
"summary": {
"type": "string"
}
},
"required": [
"summary"
],
"additionalProperties": false
}
}
}
}即使使用严格模式,应用仍应解析并验证返回对象;对外部数据不要执行 eval。