跳转到主要内容

结构化输出

通过 response_format 参数,可以让模型按照指定的 JSON Schema 返回结构化数据,确保输出格式可靠且可解析。

JSON 模式

最简单的结构化输出方式,强制模型返回有效的 JSON:
curl https://crazyrouter.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {"role": "system", "content": "你是一个数据提取助手,请以 JSON 格式返回结果。"},
      {"role": "user", "content": "提取以下文本中的人名和职位:张三是公司的技术总监,李四是产品经理。"}
    ],
    "response_format": {"type": "json_object"}
  }'

响应

{
  "people": [
    {"name": "张三", "title": "技术总监"},
    {"name": "李四", "title": "产品经理"}
  ]
}

JSON Schema 模式

使用 json_schema 类型可以精确定义输出结构,模型会严格遵循 schema:
curl https://crazyrouter.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {"role": "user", "content": "分析这段代码的质量:def add(a, b): return a + b"}
    ],
    "response_format": {
      "type": "json_schema",
      "json_schema": {
        "name": "code_review",
        "strict": true,
        "schema": {
          "type": "object",
          "properties": {
            "score": {
              "type": "integer",
              "description": "代码质量评分,1-10"
            },
            "issues": {
              "type": "array",
              "items": {
                "type": "object",
                "properties": {
                  "severity": {
                    "type": "string",
                    "enum": ["low", "medium", "high"]
                  },
                  "description": {
                    "type": "string"
                  }
                },
                "required": ["severity", "description"],
                "additionalProperties": false
              }
            },
            "suggestions": {
              "type": "array",
              "items": {"type": "string"}
            }
          },
          "required": ["score", "issues", "suggestions"],
          "additionalProperties": false
        }
      }
    }
  }'

响应

{
  "score": 7,
  "issues": [
    {
      "severity": "low",
      "description": "缺少类型注解"
    },
    {
      "severity": "low",
      "description": "缺少文档字符串"
    }
  ],
  "suggestions": [
    "添加类型注解:def add(a: int, b: int) -> int",
    "添加 docstring 说明函数用途",
    "考虑添加输入验证"
  ]
}
使用 json_schema 模式时,设置 "strict": true 可以确保模型严格遵循 schema 定义。additionalProperties 必须设为 false
使用 json_object 模式时,必须在 system 或 user 消息中明确提示模型返回 JSON,否则可能导致无限生成。