# openai.BadRequestError: 错误代码：400 - {'error': {'message': "无效的 'response_format'：'type' 必须是 ['text', 'json_object', 'json_schema'] 之一。", 'type': 'invalid_request_error'}}

- **ID:** `llm/openai-structured-output-enum-violation`
- **领域:** llm
- **类别:** config_error
- **错误码:** `OAI-ERR-0400`
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

response_format.type 参数设置为无效或不支持的值（例如，'json' 而不是 'json_object' 或 'json_schema'），或者模型版本不支持指定的格式类型。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| openai==1.30.0 | active | — | — |
| openai==1.35.0 | active | — | — |
| gpt-4o-mini-2024-07-18 | active | — | — |

## 解决方案

1. ```
   将 response_format 更正为使用有效类型：`response_format={"type": "json_object"}` 用于非结构化 JSON，或 `response_format={"type": "json_schema", "json_schema": {"name": "my_schema", "schema": {...}}}` 用于结构化 JSON。示例：`client.chat.completions.create(model="gpt-4o-mini", messages=[{"role": "user", "content": "Hello"}], response_format={"type": "json_object"})`。
   ```
2. ```
   如果使用 'json_schema'，请确保模型支持它（gpt-4o-mini 及更高版本，或特定版本的 gpt-4-turbo）。通过 API 检查模型的能力：`model = client.models.retrieve("gpt-4o-mini"); print(model.supported_features)`。
   ```
3. ```
   对于不支持 'json_schema' 的旧模型，回退到 'json_object' 并使用 JSON 模式验证器（如 `jsonschema.validate()`）手动解析输出。
   ```

## 无效尝试

- **** — The API strictly requires the 'type' key; an empty dict causes a different validation error: 'response_format must be a valid object with a type field'. (90% 失败率)
- **** — The API only accepts 'text', 'json_object', or 'json_schema' (for newer models). 'json' is not recognized and triggers the exact error. (95% 失败率)
- **** — Older versions don't support 'json_schema' at all, and may have different validation rules. This breaks other features and is not a sustainable fix. (85% 失败率)
