# KeyError: 流式响应块中缺少 'content' 字段

- **ID:** `llm/streaming-chunk-missing-content-field`
- **领域:** llm
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

来自 LLM API 的流式块可能省略 'content' 字段，当它们仅包含元数据（如 finish_reason、使用信息）或由于内部处理而为空时。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| openai-python>=1.0.0 | active | — | — |
| gpt-4-1106-preview | active | — | — |
| gpt-3.5-turbo-1106 | active | — | — |

## 解决方案

1. ```
   Use robust parsing that handles all chunk structures. Example: `for chunk in response: if chunk.choices and chunk.choices[0].delta and chunk.choices[0].delta.content: yield chunk.choices[0].delta.content`
   ```
2. ```
   Use the OpenAI Python library's built-in streaming iterator which handles these edge cases internally: `for chunk in client.chat.completions.create(..., stream=True):` and access via `chunk.choices[0].delta.content` with null checks.
   ```
3. ```
   Implement a retry with exponential backoff for chunks that raise KeyError, logging the raw chunk for debugging.
   ```

## 无效尝试

- **** — This handles missing content but doesn't account for chunks that have no 'choices' array at all, which can still cause errors. (60% 失败率)
- **** — This causes silent data loss or crashes when the error occurs. (90% 失败率)
- **** — Streaming inherently delivers partial data; the issue is about chunk structure, not completeness. (70% 失败率)
