OpenAI 400 invalid_json_schema 报错排查:严格结构化输出与工具 Schema 修复
核心要点
- 典型报错原文:
400 {"error":{"message":"Invalid schema for response_format '...': In context=(), 'additionalProperties' is required to be supplied and to be false.","type":"invalid_request_error","param":"response_format","code":"invalid_json_schema"}}。- 核心根因:在
strict: true模式下直接手写或传入原生 Pydantic.model_json_schema(),导致嵌套对象缺少"additionalProperties": false、可选字段未放进"required"、根节点写了"type": "array",或误用了oneOf等受限关键字。- 1 分钟速修:在根节点与每一层嵌套
object补齐"additionalProperties": false,把properties的全部键名写进required(可选字段改写为["string", "null"]),顶层数组外包一层对象,或直接改用pydantic_function_tool()/zodResponseFormat()自动转换。
调用 OpenAI 结构化输出(/v1/chat/completions 的 response_format、/v1/responses 的 text.format)或开启 strict: true 的函数工具时,服务端会在生成前将 JSON Schema 编译成受限解码状态机。只要 Schema 违反严格子集规范,请求就会在预检阶段直接拦截并返回 HTTP 400 invalid_json_schema。
高频报错原文与逐条对照
{
"error": {
"message": "Invalid schema for response_format 'invoice_extract': In context=(), 'additionalProperties' is required to be supplied and to be false.",
"type": "invalid_request_error",
"param": "response_format",
"code": "invalid_json_schema"
}
}先看 error.message 里的 In context=(...) 路径提示 —— 它会精确指出是哪一层嵌套节点不合规:
| 报错关键英文提示 | 触发原因 | 对应修法 |
|---|---|---|
'additionalProperties' is required to be supplied and to be false | 根对象或嵌套对象(如 properties.item、$defs.Sub)漏写了 "additionalProperties": false | 规则 1 |
'required' is required to be supplied and to be an array including every key in properties | properties 里定义的某个字段没写进当前对象的 required 数组 | 规则 2 |
root type must be 'object' / 'anyOf' is not permitted at top level | 顶层 Schema 写成了 "type": "array" 或顶层直接放了 "anyOf" | 规则 3 |
'oneOf' is not permitted 或正则/$ref 同级属性报错 | 误用了 oneOf、$ref 旁带了同级 default/description,或传入了未清洗的 Pydantic 原始输出 | 规则 4 |
Missing required parameter: 'text.format.name'(/v1/responses) | 把 Chat Completions 的 response_format.json_schema 嵌套结构原样搬到了 /v1/responses | 规则 5 |
错误 vs 正确 JSON Schema 对照(可直接复制替换)
错误写法(同时踩中 3 个典型 400 陷阱)
- 顶层直接用了
"type": "array"; - 嵌套的订单项对象漏写了
"additionalProperties": false; - 可选字段
coupon_code没有放进"required"。
{
"type": "json_schema",
"json_schema": {
"name": "order_items",
"strict": true,
"schema": {
"type": "array",
"items": {
"type": "object",
"properties": {
"sku": { "type": "string" },
"qty": { "type": "integer" },
"coupon_code": { "type": "string" }
},
"required": ["sku", "qty"]
}
}
}
}正确写法(通过 strict: true 严格校验)
{
"type": "json_schema",
"json_schema": {
"name": "order_items",
"strict": true,
"schema": {
"type": "object",
"properties": {
"items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"sku": { "type": "string" },
"qty": { "type": "integer" },
"coupon_code": {
"type": ["string", "null"],
"description": "有优惠码则填字符串,无则返回 null"
}
},
"required": ["sku", "qty", "coupon_code"],
"additionalProperties": false
}
}
},
"required": ["items"],
"additionalProperties": false
}
}
}strict: true 必须遵守的 5 条硬规则
规则 1:每一层 object 都必须显式声明 "additionalProperties": false
只给最外层加 "additionalProperties": false 不够 —— properties、数组 items、anyOf 分支以及 $defs 里的每一个 "type": "object" 都必须写上 "additionalProperties": false。此外,严格模式不支持任意动态字典(如 "additionalProperties": { "type": "string" }),遇到动态键值对请改建成 [{"key": "...", "value": "..."}] 数组结构。
规则 2:properties 中的所有键必须全量进 required(可选字段用 "null")
普通 JSON Schema 靠不写进 required 来表达可选字段,但 OpenAI strict: true 要求 required 数组必须包含 properties 中的每一个键。要表达「该字段可为空」,请把键名留在 required 中,并将类型写成联合 "null":
"middle_name": {
"type": ["string", "null"]
}如果可空字段引用的是 $ref 子对象,则用 anyOf 包裹:
"shipping_address": {
"anyOf": [
{ "$ref": "#/$defs/Address" },
{ "type": "null" }
]
}规则 3:根节点必须是 type: "object"(禁止顶层数组或顶层 anyOf)
无论是 response_format 还是工具参数 parameters,顶层 Schema 都必须是 "type": "object"。需要输出列表或多态分支时,统一在外层包一个单字段对象(如 {"items": [...]} 或 {"result": {"anyOf": [...]}})。
规则 4:避开不支持的关键字与裸 .model_json_schema()
即便是现役主力 gpt-6.2-sol 与 gpt-6-luna,严格语法编译器仍有明确边界:
- 多选一请用
anyOf,禁止oneOf与allOf。 $ref同级不能并列其它字段:含"$ref": "#/$defs/Item"的节点若同级带有"default"或"description",部分编译器会直接拒收。- 校验类关键字注意兼容性:旧快照及部分跨厂商兼容层不支持
minLength、maxLength、pattern(尤其带先行断言的正则)或数值上下界,或者会导致首次编译耗时飙升。工程最佳实践是:Schema 只锁死结构与类型,复杂正则/范围放在字段description并在拿到响应后由业务代码做二次校验。
规则 5:区分 Chat Completions 与 Responses API 的外层包装差异
在应对 2026-12-11 OpenAI gpt-5 / o3 停服迁移 并切往 /v1/responses 时,结构化输出字段从 response_format.json_schema 变成了扁平的 text.format:
{
"model": "gpt-6.2-sol",
"input": "提取账单金额与到期日:应付 USD 420,截止 2026-12-30",
"max_output_tokens": 4096,
"text": {
"format": {
"type": "json_schema",
"name": "invoice_extract",
"strict": true,
"schema": {
"type": "object",
"properties": {
"amount": { "type": "number" },
"due_date": { "type": ["string", "null"] }
},
"required": ["amount", "due_date"],
"additionalProperties": false
}
}
}
}同时注意在 gpt-6.2-sol 上不要传旧版 max_tokens 或 temperature,详见 OpenAI max_tokens 与采样参数报错修复。
SDK 标准写法:Python(Pydantic)与 TypeScript(Zod)
Python + Pydantic v2(替代手动调 .model_json_schema())
直接传 InvoiceExtract.model_json_schema() 会漏掉 additionalProperties: false 并把带默认值的字段移出 required。请直接使用 OpenAI Python SDK 的 .parse() 或 pydantic_function_tool():
from typing import Optional
from pydantic import BaseModel, ConfigDict
from openai import OpenAI, pydantic_function_tool
client = OpenAI(
api_key="sk-YOUR_TOKEN",
base_url="https://byesu.com/v1",
)
class LineItem(BaseModel):
model_config = ConfigDict(extra="forbid")
sku: str
quantity: int
discount_code: Optional[str]
class InvoiceExtract(BaseModel):
model_config = ConfigDict(extra="forbid")
vendor: str
items: list[LineItem]
notes: Optional[str]
# 方式 A:使用 .parse() 自动递归注入 additionalProperties: false 与全量 required
completion = client.beta.chat.completions.parse(
model="gpt-6.2-sol",
messages=[{"role": "user", "content": "供应商:Acme Corp,2 件 SKU-99,无优惠码"}],
response_format=InvoiceExtract,
max_completion_tokens=4096,
)
invoice: InvoiceExtract = completion.choices[0].message.parsed
print(invoice.model_dump())
# 方式 B:生成严格模式的 Function Calling 工具定义
strict_tool = pydantic_function_tool(InvoiceExtract, name="save_invoice")若使用框架开发类型安全 Agent,可参考 PydanticAI 接入指南。
TypeScript + Zod(用 .nullable() 代替 .optional())
在 Zod 中写 z.string().optional() 会把该键从 required 数组中删掉,在 strict: true 下必报 400!请一律改用 z.string().nullable() 并搭配官方 zodResponseFormat 辅助函数:
import OpenAI from "openai";
import { zodResponseFormat } from "openai/helpers/zod";
import { z } from "zod";
const client = new OpenAI({
apiKey: process.env.BYESU_API_KEY,
baseURL: "https://byesu.com/v1",
});
// 错误:z.string().optional() 会从 required 中漏掉该键
// 正确:z.string().nullable() 会生成 ["string", "null"] 并保留在 required 中
const InvoiceSchema = z.object({
vendor: z.string(),
items: z.array(
z.object({
sku: z.string(),
quantity: z.number().int(),
discount_code: z.string().nullable(),
})
),
notes: z.string().nullable(),
});
const completion = await client.beta.chat.completions.parse({
model: "gpt-6.2-sol",
messages: [{ role: "user", content: "Vendor: Acme Corp, 2x SKU-99" }],
response_format: zodResponseFormat(InvoiceSchema, "invoice_extract"),
max_completion_tokens: 4096,
});
console.log(completion.choices[0].message.parsed);Next.js / 全栈 TS 项目另见 Vercel AI SDK 接入指南。
5 秒网关连通性自检
在排查复杂 JSON Schema 之前,可先用 5 秒诊断脚本确认令牌与网关连通正常:
curl -fsSL https://docs.byesu.com/setup/test.sh | sh
# 或直接传入令牌免交互测试:
curl -fsSL https://docs.byesu.com/setup/test.sh | bash -s -- sk-YOUR_TOKEN- 核对现役模型代号拼写见 OpenAI 404
model_not_found排查,一键生成各语言初始化代码见 AI 客户端与 SDK 配置生成器。
常见问题
OpenAI 报 400 invalid_json_schema 的核心原因是什么?
开启 strict: true(结构化输出或严格 Function Calling)后,服务端会在推理前将 JSON Schema 编译为上下文无关语法。只要任一层对象漏写 additionalProperties: false、properties 中的键未全部列入 required、根节点不是 type: "object" 或包含不支持的关键字,就会直接返回 HTTP 400 invalid_json_schema。
所有字段都必须写进 required,那可选字段(Optional)该怎么表示?
字段名仍然保留在 required 数组中,同时把类型声明为可空联合类型,例如 ["string", "null"](或使用 anyOf 搭配 {"type": "null"})。在 Python Pydantic 中配合 SDK 的 .parse() 使用 Optional[str];在 TypeScript Zod 中必须用 z.string().nullable() 代替 z.string().optional()。
为什么直接传 Pydantic 的 MyModel.model_json_schema() 会报 400?
Pydantic 原生的 model_json_schema() 默认不会给每层对象注入 additionalProperties: false,且会把带默认值的字段从 required 数组中剔除。请改用 OpenAI SDK 内置的 client.beta.chat.completions.parse、client.responses.parse 或 openai.pydantic_function_tool(MyModel) 自动完成严格 Schema 转换。
OpenAI 结构化输出的顶层 Schema 可以是数组(type: "array")吗?
不可以。顶层 Schema 必须是 type: "object"(不能是顶层 array 或顶层 anyOf)。需要返回列表时,请在外层包一个对象字段,例如 {"type": "object", "properties": {"items": {"type": "array", ...}}, "required": ["items"], "additionalProperties": false}。
Responses API 和 Chat Completions 的 json_schema 参数结构有什么区别?
Chat Completions 嵌套在 response_format: {"type": "json_schema", "json_schema": {"name": "...", "strict": true, "schema": {...}}};而 Responses API 扁平放在 text: {"format": {"type": "json_schema", "name": "...", "strict": true, "schema": {...}}} 下,少一层 json_schema 键。