# 结构化输出 JSON 模式返回意外字段：输出包含模式中未定义的键

- **ID:** `llm/structured-output-json-mode-returns-unexpected-field`
- **领域:** llm
- **类别:** data_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

使用 JSON 模式（response_format={type: 'json_object'}）时，LLM 生成包含请求模式中不存在的键的 JSON 对象，导致下游解析失败或验证拒绝输出。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| openai>=1.0.0 | active | — | — |
| pydantic>=2.0.0 | active | — | — |
| python>=3.9 | active | — | — |

## 解决方案

1. ```
   Use Pydantic's 'extra' parameter set to 'forbid' to reject extra fields, and re-prompt the LLM on failure.
   ```
2. ```
   Post-process the JSON output to filter out unexpected keys before validation.
   ```

## 无效尝试

- **Add more examples to the system prompt showing the exact JSON structure** — LLMs may still hallucinate extra fields even with examples; examples reduce but don't eliminate the issue. (60% 失败率)
- **Use a stronger model like GPT-4 instead of GPT-3.5** — While GPT-4 is more reliable, it can still produce extra fields in JSON mode, especially with complex schemas. (50% 失败率)
