# 当可选字段在上下文中缺失时，LLM 会为结构化输出中的可选字段生成虚假值

- **ID:** `llm/structured-output-hallucination-on-null-fields`
- **领域:** llm
- **类别:** data_error
- **验证级别:** ai_generated
- **修复率:** 82%

## 根因

当使用带有可选字段的 Pydantic 模式的 response_format 时，模型会虚构看似合理但不正确的值，而不是省略或设置为 null，因为省略指令对模型的自回归生成不够强烈。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| openai==1.30.0 | active | — | — |
| pydantic==2.7.0 | active | — | — |
| langchain==0.2.0 | active | — | — |

## 解决方案

1. ```
   后处理 LLM 输出：收到结构化响应后，遍历模式中所有 Optional 字段，如果原始输入上下文中不包含该字段的证据，则将其设置为 None。示例：

def clean_optional_fields(response: dict, schema: Type[BaseModel], context: str) -> dict:
    for field_name, field in schema.model_fields.items():
        if field.is_required():
            continue
        if field_name not in context:
            response[field_name] = None
    return response
   ```
2. ```
   修改系统提示，明确指示模型：'如果提供的上下文中没有可选字段的信息，请将该字段设置为 null。不要虚构值。'
   ```
3. ```
   使用受限解码库（如 'outlines' 或 'lm-format-enforcer'），在生成时强制可选字段为 null 标记，而不是依赖事后 JSON 解析。
   ```

## 无效尝试

- **Setting temperature=0 to force determinism** — Temperature=0 reduces randomness but does not change the model's autoregressive tendency to fill in plausible values. It still hallucinates optional fields. (75% 失败率)
- **Adding 'strict=True' to response_format schema** — Strict mode only enforces JSON schema compliance (e.g., no extra fields), it does not prevent the model from generating values for optional fields when context is missing. (90% 失败率)
- **Using a simpler schema with all required fields** — This removes the optionality, forcing the model to always provide a value, which makes the hallucination problem worse, not better. (60% 失败率)
