openai.BadRequestError:response_format 的架构无效:'properties' 必须是一个对象
openai.BadRequestError: Invalid schema for response_format: 'properties' must be an object
ID: llm/structured-output-schema-mismatch-on-retry
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| openai==1.30.0 | active | — | — | — |
| openai==1.35.0 | active | — | — | — |
| pydantic==2.7.0 | active | — | — | — |
根因分析
OpenAI API 对 response_format 强制执行严格的 JSON Schema 验证;空的或格式错误的 'properties' 字段(例如在架构转换或缓存后)会在重试时触发此错误。
English
OpenAI API enforces strict JSON Schema validation for response_format; an empty or malformed 'properties' field (e.g., after schema transformation or caching) triggers this error on retry.
官方文档
https://platform.openai.com/docs/api-reference/chat/create#chat-create-response_format解决方案
-
Validate the schema before sending: ensure 'properties' is a non-empty object with valid JSON Schema types. Example: `if not isinstance(schema.get('properties'), dict) or len(schema['properties']) == 0: raise ValueError('Invalid schema')` -
Use a schema generation library like Pydantic to create the JSON Schema, then convert to dict with `model_json_schema()`. Example: `from pydantic import BaseModel; class MyModel(BaseModel): name: str; schema = MyModel.model_json_schema()`
-
If caching schemas, deep-copy the schema dict before modification to avoid mutating the cached version (which may become empty). Example: `import copy; schema = copy.deepcopy(cached_schema)`
无效尝试
常见但无效的做法:
-
95% 失败
The schema is fundamentally broken; the API will reject it consistently until the schema is corrected.
-
85% 失败
Removing structured output forces the LLM to return free-form text, breaking downstream parsing logic that expects a JSON object.
-
90% 失败
The API expects the schema directly under 'response_format', not nested; this causes a different validation error.