跳到正文

函数调用与结构化输出

用 tools 让模型调用你的函数,用 response_format 让模型按 JSON Schema 输出,附完整的往返示例。

两种能力都是对话补全接口上的参数:

  • 函数调用:在请求里用 tools 描述你的函数,模型需要时会返回 tool_calls(要调用哪个函数、参数是什么);你执行函数后,把结果用 role: tool 的消息发回去,模型再给出最终回答。
  • 结构化输出:用 response_format 要求模型只输出 JSON,或者输出符合指定 JSON Schema 的 JSON。

能不能用取决于模型本身:先在模型广场里看这个模型的说明,拿不准时用一个简单的函数实际请求一次确认。能用哪些模型还取决于密钥的分组。

POST https://codaapi.com/v1/chat/completions

请求头

名称 必填 说明
Authorization 是 Bearer sk-…,你的 API 密钥
Content-Type 是 application/json

请求参数

下表只列这两种能力用到的参数,其余参数见对话补全。

参数 类型 必填 说明
tools array 否 可调用的函数列表
tools[].type string 是 固定为 function
tools[].function.name string 是 函数名
tools[].function.description string 否 函数的用途,模型据此决定什么时候调用
tools[].function.parameters object 否 参数的 JSON Schema
tools[].function.strict boolean 否 为 true 时要求模型严格按 Schema 生成参数,是否支持取决于模型
tool_choice string 或 object 否 auto(默认,模型自己决定)、none(不调用)、required(必须调用一个),或 {"type": "function", "function": {"name": "…"}} 指定函数
parallel_tool_calls boolean 否 是否允许一次返回多个函数调用
messages[].tool_calls array 否 回填时,原样带上模型上一条回复里的 tool_calls(role: assistant)
messages[].tool_call_id string 否 回填结果时(role: tool)对应的调用 id
response_format object 否 结构化输出:{"type": "json_object"} 或 {"type": "json_schema", "json_schema": {…}}
response_format.json_schema.name string 是 Schema 的名字
response_format.json_schema.schema object 是 JSON Schema
response_format.json_schema.strict boolean 否 为 true 时严格按 Schema 输出

转给不同上游时的差别:

  • OpenAI、Grok:上面的字段原样转给上游。
  • Claude:tools、tool_choice、tool_calls 和 role: tool 的结果都会转换成 Claude 的格式;response_format 不会转换,Claude 模型不受它约束。需要结构化输出时,在提示词里要求 JSON,或者用一个函数的参数来接收结构化结果。
  • Gemini:函数调用会转换;response_format 的 json_object 和 json_schema 会转成 Gemini 的 JSON 输出设置。

参数最终是否生效,取决于模型和上游。

请求示例

下面是一次完整的往返:用户问天气,模型调用 get_current_weather,你执行函数并回填结果,模型给出回答。

第一步:带上 tools 发请求

curl https://codaapi.com/v1/chat/completions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-5.4-mini",
    "messages": [{"role": "user", "content": "北京今天天气怎么样?"}],
    "tools": [{
      "type": "function",
      "function": {
        "name": "get_current_weather",
        "description": "查询某个地点当前的天气",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {"type": "string", "description": "城市名,例如 北京"},
            "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
          },
          "required": ["location"]
        }
      }
    }]
  }'

parameters 是一段 JSON Schema:required 里的参数模型一定会给,其余的可给可不给;enum 限定取值,这里的 unit 只能是 celsius 或 fahrenheit。

第二步:模型返回 tool_calls,finish_reason 是 tool_calls,content 为空。arguments 是一个 JSON 字符串,要自己解析:

{
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": null,
        "tool_calls": [
          {
            "id": "call_abc123",
            "type": "function",
            "function": { "name": "get_current_weather", "arguments": "{\"location\":\"北京\",\"unit\":\"celsius\"}" }
          }
        ]
      },
      "finish_reason": "tool_calls"
    }
  ]
}

第三步:执行函数,回填结果再请求一次。messages 里依次放:原来的用户消息、模型上一条回复(带 tool_calls)、每个调用的结果(role: tool,tool_call_id 对上 id)。tools 继续带上:

curl https://codaapi.com/v1/chat/completions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-5.4-mini",
    "messages": [
      {"role": "user", "content": "北京今天天气怎么样?"},
      {"role": "assistant", "content": null, "tool_calls": [
        {"id": "call_abc123", "type": "function", "function": {"name": "get_current_weather", "arguments": "{\"location\":\"北京\",\"unit\":\"celsius\"}"}}
      ]},
      {"role": "tool", "tool_call_id": "call_abc123", "content": "{\"location\": \"北京\", \"weather\": \"晴\", \"temperature\": 18, \"unit\": \"celsius\"}"}
    ],
    "tools": [{
      "type": "function",
      "function": {
        "name": "get_current_weather",
        "description": "查询某个地点当前的天气",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {"type": "string", "description": "城市名,例如 北京"},
            "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
          },
          "required": ["location"]
        }
      }
    }]
  }'

模型这次返回普通的文字回答,例如「北京今天晴,18 °C」,finish_reason 是 stop。模型也可能一次返回多个 tool_calls,或者在拿到结果后再调用别的函数,所以代码里一般写成循环。

Python(pip install openai)

import json
from openai import OpenAI

client = OpenAI()  # 读取 OPENAI_BASE_URL 和 OPENAI_API_KEY

tools = [{
    "type": "function",
    "function": {
        "name": "get_current_weather",
        "description": "查询某个地点当前的天气",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {"type": "string", "description": "城市名,例如 北京"},
                "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
            },
            "required": ["location"],
        },
    },
}]

def get_current_weather(location, unit="celsius"):
    return {"location": location, "weather": "晴", "temperature": 18, "unit": unit}  # 换成你自己的实现

messages = [{"role": "user", "content": "北京今天天气怎么样?"}]

while True:
    response = client.chat.completions.create(model="gpt-5.4-mini", messages=messages, tools=tools)
    message = response.choices[0].message
    if not message.tool_calls:
        break
    messages.append(message)  # 模型的这条回复(含 tool_calls)原样加回对话
    for call in message.tool_calls:
        result = get_current_weather(**json.loads(call.function.arguments))
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": json.dumps(result, ensure_ascii=False),
        })

print(message.content)

Node.js(npm install openai)

import OpenAI from 'openai';

const client = new OpenAI(); // 读取 OPENAI_BASE_URL 和 OPENAI_API_KEY

const tools = [{
  type: 'function',
  function: {
    name: 'get_current_weather',
    description: '查询某个地点当前的天气',
    parameters: {
      type: 'object',
      properties: {
        location: { type: 'string', description: '城市名,例如 北京' },
        unit: { type: 'string', enum: ['celsius', 'fahrenheit'] },
      },
      required: ['location'],
    },
  },
}];

function getCurrentWeather({ location, unit = 'celsius' }) {
  return { location, weather: '晴', temperature: 18, unit }; // 换成你自己的实现
}

const messages = [{ role: 'user', content: '北京今天天气怎么样?' }];

let message;
while (true) {
  const completion = await client.chat.completions.create({ model: 'gpt-5.4-mini', messages, tools });
  message = completion.choices[0].message;
  if (!message.tool_calls?.length) break;
  messages.push(message); // 模型的这条回复(含 tool_calls)原样加回对话
  for (const call of message.tool_calls) {
    const result = getCurrentWeather(JSON.parse(call.function.arguments));
    messages.push({ role: 'tool', tool_call_id: call.id, content: JSON.stringify(result) });
  }
}

console.log(message.content);

结构化输出

用 json_schema 让模型输出符合 Schema 的 JSON。下面让模型按步骤解一道方程,每一步写成 steps 里的一项,最后的答案放在 final_answer:

curl https://codaapi.com/v1/chat/completions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-5.4-mini",
    "messages": [
      {"role": "system", "content": "你是一位数学老师,一步一步讲解解题过程。"},
      {"role": "user", "content": "解方程 8x + 31 = 2"}
    ],
    "response_format": {
      "type": "json_schema",
      "json_schema": {
        "name": "math_response",
        "strict": true,
        "schema": {
          "type": "object",
          "properties": {
            "steps": {
              "type": "array",
              "items": {
                "type": "object",
                "properties": {"explanation": {"type": "string"}, "output": {"type": "string"}},
                "required": ["explanation", "output"],
                "additionalProperties": false
              }
            },
            "final_answer": {"type": "string"}
          },
          "required": ["steps", "final_answer"],
          "additionalProperties": false
        }
      }
    }
  }'

返回的 message.content 是一个符合 Schema 的 JSON 字符串,要自己解析,例如:

{"steps": [{"explanation": "两边同时减去 31", "output": "8x = -29"}, {"explanation": "两边同时除以 8", "output": "x = -29/8"}], "final_answer": "x = -29/8"}

strict 为 true 时,OpenAI 要求每一层对象都写 "additionalProperties": false,并且把全部属性列进 required,上面的 Schema 就是这样写的。

response = client.chat.completions.create(
    model="gpt-5.4-mini",
    messages=[
        {"role": "system", "content": "你是一位数学老师,一步一步讲解解题过程。"},
        {"role": "user", "content": "解方程 8x + 31 = 2"},
    ],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "math_response",
            "strict": True,
            "schema": {
                "type": "object",
                "properties": {
                    "steps": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {"explanation": {"type": "string"}, "output": {"type": "string"}},
                            "required": ["explanation", "output"],
                            "additionalProperties": False,
                        },
                    },
                    "final_answer": {"type": "string"},
                },
                "required": ["steps", "final_answer"],
                "additionalProperties": False,
            },
        },
    },
)
data = json.loads(response.choices[0].message.content)
for step in data["steps"]:
    print(step["explanation"], "→", step["output"])
print(data["final_answer"])  # x = -29/8

只要求输出合法 JSON、不限定结构时,用 {"type": "json_object"}。OpenAI 要求这时消息里明确说明要输出 JSON(例如「用 JSON 回答」),否则会报错。

返回

返回格式与对话补全相同,相关的字段:

字段 说明
choices[].message.tool_calls[].id 这次调用的 id,回填结果时填到 tool_call_id
choices[].message.tool_calls[].function.name 要调用的函数名
choices[].message.tool_calls[].function.arguments 参数,JSON 字符串
choices[].finish_reason 要调用函数时是 tool_calls
choices[].message.content 结构化输出时是 JSON 字符串

流式返回时,函数调用分段出现在 choices[0].delta.tool_calls 里:同一个调用的多个片段带相同的 index,arguments 要按顺序拼起来。

在 Responses 接口里

Responses 接口也支持这两种能力,但写法不同:

项目 对话补全 Responses
定义函数 {"type": "function", "function": {"name": …, "parameters": …}} {"type": "function", "name": …, "parameters": …}(不套 function)
模型要调用函数 message.tool_calls[],用 id 对应 output[] 里 type 为 function_call 的项,用 call_id 对应
回填结果 {"role": "tool", "tool_call_id": …, "content": …} 在 input 里先放模型返回的 function_call 项,再加 {"type": "function_call_output", "call_id": …, "output": …}
结构化输出 response_format text.format,例如 {"type": "json_schema", "name": …, "schema": …}

错误

出错时返回 4xx 或 5xx 状态码和 OpenAI 风格的错误体 {"error": {"message": "…", "type": "…", "code": "…"}},message 末尾带着这次请求的编号(request id)。常见的状态码和处理办法见错误码对照。

计费

按 tokens 计费:tools 的定义、回填的函数结果都算输入 tokens,模型生成的调用参数算输出 tokens。一次往返是两次请求,分别计费。各模型的价格见模型广场和价格表,计费规则见价格与倍率。

更新于