博客 AI / Structured Output

2026 AI Structured Output 是什么?JSON Schema 如何让 ChatGPT、Gemini 输出稳定 JSON

你在接 ChatGPT 或 Gemini API,文档里同时出现response_format.json_schema和 Google 的responseSchema——它们都承诺「结构化 JSON 输出」,但保证程度和使用方式并不相同。

Structured Output(结构化输出)是 2026 年 LLM API 的核心能力:在生成前用JSON Schema2020-12)声明输出必须有哪些字段、什么类型,让模型输出从「尽量像 JSON」变成「可机器校验的契约数据」。

本文将说明:

先记住这一点:「输出 JSON」和「输出符合 schema 的 JSON」是两回事。JSON Mode 只解决前者;Structured Output + Strict Schema 解决后者。下面按「概念 → 为什么不稳定 → Schema 原理 → ChatGPT → Gemini → 路径对比 → 怎么写 → 怎么校验」拆开。

Structured Output 是什么

Structured Output 是 LLM API 的一项能力:你在请求里附带 JSON Schema,模型在生成最终回答时被约束,使输出 conform 到该 schema 定义的字段、类型和必填项。

2026 年,主流模型厂商都已将其作为生产级特性推广:

官方文档:OpenAI Structured OutputsGemini JSON Mode

为什么 LLM 的 JSON 输出不稳定

如果你只在 prompt 里写「请返回 JSON」,常见失败模式如下:

失败模式 典型表现 根因
语法错误 缺引号、尾随逗号、单引号 模型按自然语言习惯生成,未约束 token 序列
字段漂移 同 prompt 两次输出字段名不同 无 schema 契约,模型自由发挥
类型错误 数字变字符串、数组变对象 prompt 描述模糊,无 type 硬约束
多余字段 出现 schema 未声明的 key 无 additionalProperties: false

这些问题在 demo 阶段可以靠重试或二次解析掩盖,但在生产 Agent、数据管道和自动化流程里会直接导致下游崩溃。Structured Output 的目标就是在 API 层消除这些不确定性。

JSON Schema 如何约束模型输出

JSON Schema 是描述 JSON 数据结构的标准。在 Structured Output 场景里,它扮演「输出契约」:

  1. 1
    声明字段名和类型

    properties 里每个 key 对应一个输出字段,type 指定 string / integer / array 等。

  2. 2
    限定必填与枚举

    required 数组列出必填字段;enum 限制取值范围,避免模型「创造性」填值。

  3. 3
    推理阶段硬约束

    Strict Schema 模式下,模型在 token 生成时被 schema 引导——不是生成后再校验,而是生成时就只能产出 conform 的 JSON。

Schema 在 Agent 栈的更多位置(Tool Calling、MCP)见AI Agent 与 JSON Schema 完整解析

ChatGPT / OpenAI:Strict Schema 实战

OpenAI 从 gpt-4o-2024-08-06 起正式支持 Structured Outputs。核心配置在gpt-4o 及后续模型的response_format 字段:

OpenAI Strict Structured Output 请求
{
  "model": "gpt-4o-2024-08-06",
  "messages": [
    { "role": "user", "content": "Extract product info from this review text." }
  ],
  "response_format": {
    "type": "json_schema",
    "json_schema": {
      "name": "product_review",
      "strict": true,
      "schema": {
        "type": "object",
        "properties": {
          "product_name": { "type": "string" },
          "rating": { "type": "integer", "minimum": 1, "maximum": 5 },
          "pros": { "type": "array", "items": { "type": "string" } },
          "cons": { "type": "array", "items": { "type": "string" } }
        },
        "required": ["product_name", "rating", "pros", "cons"],
        "additionalProperties": false
      }
    }
  }
}

关键参数:strict: true开启推理阶段硬约束;additionalProperties: false防止模型添加未声明字段。

DeepSeek 等 OpenAI 兼容 API 也支持相同格式,详见DeepSeek V4-Pro 一文。

Google Gemini:responseSchema 实战

Gemini 2.0 系列(如gemini-2.0-flash)通过responseSchema 实现结构化输出:

Gemini Python SDK — responseSchema
from google import genai
from google.genai import types

client = genai.Client()
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents="Summarize this customer ticket into structured fields.",
    config=types.GenerateContentConfig(
        response_mime_type="application/json",
        response_schema={
            "type": "object",
            "properties": {
                "category": {
                    "type": "string",
                    "enum": ["billing", "technical", "account", "other"]
                },
                "priority": {
                    "type": "string",
                    "enum": ["low", "medium", "high"]
                },
                "summary": { "type": "string" }
            },
            "required": ["category", "priority", "summary"]
        }
    )
)
print(response.text)

Gemini 的response_mime_type: application/json 声明 MIME 类型为 JSON;responseSchema 传入 JSON Schema 对象(结构与 OpenAI 的 schema 字段类似)。

三条结构化输出路径对比

2026 年接入 LLM 时,结构化输出通常有三条路径可选:

路径 API 配置 保证什么 适用场景
纯 Prompt 无特殊配置 不保证格式 快速原型、人工阅读
JSON Mode response_format: json_object 合法 JSON 对象 简单提取、字段结构宽松
Structured Output json_schema + strict: true 严格 conform 到 schema 生产环境、复杂嵌套结构
Function Calling tools[].parameters arguments 尽量符合 parameters schema Agent 工具调用(非最终回答)

2026 年行业趋势见AI Conference 2026 热点梳理。

生产级 schema 写法要点

Structured Output 的成功率高度依赖 schema 质量:

  1. 1
    每个 property 写 description

    模型读 description 决定怎么填值。「City name, e.g. Beijing」比裸字段名准确率高很多。

  2. 2
    用 enum 而非 description 暗示选项

    「可选 low/medium/high」不如enum 可靠。

  3. 3
    设 additionalProperties: false

    OpenAI Strict 模式通常强制此选项;Gemini 也建议在 schema 根对象加上additionalProperties: false

  4. 4
    嵌套不要太深

    超过 3 层嵌套或大量 oneOf 组合会增加模型出错概率。复杂结构拆成多次 API 调用往往更稳。

校验工作流:API 到业务层

推荐的多层防御流水线:API 层选 Strict Schema → 业务层 parse + validate → 监控层记录 schema 违规率。

Python 校验示例
import json
from jsonschema import validate, ValidationError

SCHEMA = {
    "type": "object",
    "properties": {
        "category": {"type": "string", "enum": ["billing", "technical", "account", "other"]},
        "priority": {"type": "string", "enum": ["low", "medium", "high"]},
        "summary": {"type": "string"}
    },
    "required": ["category", "priority", "summary"],
    "additionalProperties": False
}

def parse_llm_json(raw: str) -> dict:
    try:
        data = json.loads(raw)
    except json.JSONDecodeError as e:
        raise ValueError(f"Invalid JSON: {e}") from e
    try:
        validate(instance=data, schema=SCHEMA)
    except ValidationError as e:
        raise ValueError(f"Schema mismatch: {e.message}") from e
    return data

无论数据来自 ChatGPT、Gemini 还是 DeepSeek,都走同一套 parse → validate → 业务逻辑。开发阶段把 schema 和实际输出贴进 JSONNote 做可视化校验,比 print 调试快得多。

用 JSONNote 调试 Structured Output

Structured Output 开发里最耗时的环节是 debug 模型返回的 JSON。JSONNote 在浏览器本地运行:

  1. 1
    校验 schema 与输出

    把 API 返回的 JSON 和你的 schema 贴进JSON Schema 页面,立刻看到哪些字段不符合契约。

  2. 2
    格式化 API 响应

    JSON 格式化检查语法错误和缩进问题。

  3. 3
    对比 prompt 迭代

    JSON Diff 对比两次调用的 structured output 差异,做回归检查。

常见问题

Structured Output 和 JSON Mode 有什么区别?

JSON Mode(response_format.type=json_object)只保证输出是合法 JSON 对象,不约束字段和类型。Structured Output(json_schema + strict:true 或 Gemini responseSchema)在推理阶段用 schema 硬约束输出结构。简单提取用 JSON Mode;生产环境复杂结构用 Structured Output。

ChatGPT 和 Gemini 的配置有什么不同?

OpenAI 用 response_format.type=json_schema,schema 嵌在 json_schema.schema 里,加 strict:true。Gemini 用 response_mime_type=application/json 加 responseSchema 平铺传入。底层都是 JSON Schema,但 SDK 写法不同。

开了 Strict Schema 还需要手动校验吗?

需要。API 层约束不能替代业务层 validate。模型可能返回空 content、网络截断或边缘 case——try/except 解析 + JSON Schema validate 是生产环境的标配。

JSON Schema 用哪个版本?

2026 年 LLM API 和 MCP 工具契约统一使用 JSON Schema 2020-12。支持 type、properties、required、enum、items、additionalProperties 等核心关键字。

Function Calling 和 Structured Output 怎么选?

Function Calling 约束的是 tool_calls.arguments(模型决定调哪个工具);Structured Output 约束的是模型最终回答的 JSON 结构。Agent 场景两者常组合使用:tools 处理外部动作,Structured Output 处理最终结构化结果。

总结

2026 年 LLM 集成的核心变化可以概括为:

Structured Output 成为标配,JSON Schema 是通用契约语言。

ChatGPT 用 json_schema + strict,Gemini 用 responseSchema——配置不同,原理一致。写好 schema、加上业务层 validate、用 JSONNote 本地调试,是从 demo 到生产的必经之路。

← 返回博客