结构化输出

Structured Outputs (JSON Mode)

结构化输出指一类 API 能力:通过 response_format、JSON Schema 等参数约束模型 100% 返回合法 JSON/指定格式,避免空白字符、语法错误、字段缺失。

详细解释

结构化输出(Structured Outputs,俗称 JSON Mode) 是 2024 年以后大模型 API 逐渐标配的一项”解放工程师”能力。在此之前,你要从模型输出里拿结构化数据,只能靠 System Prompt 里写 “Please output valid JSON with keys: id, name, price…”——但模型偶尔会输出 Markdown 代码块、解释文字、多余逗号、漏掉字段……你不得不写一堆”兜底正则 + 解析失败重试”。

Structured Outputs 彻底解决了这个问题:你把 JSON Schema(或者至少 type: json_object)告诉模型,服务端会在推理过程中按语法约束每一步 Token 选择——非法 Token(会导致 JSON 语法错误的 Token)直接被 mask 掉,最终返回必然合法。

参考官方:OpenAI Structured Outputs

两种使用方式(精度由低到高)

方式 1:JSON Object 模式(仅保证语法合法)

client.chat.completions.create(
    model="...", messages=messages,
    response_format={ "type": "json_object" }
)
# 返回文本一定是合法 JSON 对象,但字段由模型"凭记忆"遵守你 Prompt 里写的 schema

方式 2:严格 Structured Outputs(字段级校验,2025 后主流机型支持)

client.responses.create(
    model="...", input=messages,
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "product_extraction",
            "schema": {
                "type": "object",
                "properties": {
                    "items": {
                        "type": "array",
                        "items": {"type": "object", "properties": {
                            "name": {"type": "string"},
                            "price": {"type": "number"}
                        }, "required": ["name", "price"]}
                    }
                }, "required": ["items"], "additionalProperties": False
            }
        }
    }
)
# 返回对象字段、类型、required 全满足,几乎 0 解析失败

常见坑

  1. 别忘了在 Prompt 里也明确告诉模型要输出 JSON:即使开了 JSON mode,如果模型完全没接收到这个任务意图,可能会一直生成空白填充到 max_tokens——浪费钱又慢。
  2. Schema 写得越具体,成功率越高additionalProperties: false + 对每个字符串字段写 enumpattern
  3. 部分模型版本不支持严格 Structured Outputs:需要在代码里做降级(fallback 到纯 JSON mode + 解析失败重试)。唯元智创(Weimeta)的聚合网关会自动根据你调用的模型能力做兼容:支持严格模式的就传严格 schema,不支持的降级到 response_format=json_object + 后端 JSON 修复兜底。

常见问题

开了 Structured Outputs 准确率一定 100% 吗?
JSON 语法/字段结构 100% 合法,但内容的语义正确性不是——例如要抽”价格”模型可能错把文字填成数字、required 字段内容为空字符串但结构满足。语义正确性仍靠 Prompt / 模型能力保证。