# KeyError: 'content'——流式响应块中助手消息增量缺少'content'字段

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

## 根因

当流式响应包含工具调用时，某些块可能仅包含 tool_calls 而没有 content；期望每个 delta 中都有 'content' 的代码会引发 KeyError。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| openai>=1.0.0 | active | — | — |
| gpt-4-turbo-2024-04-09 | active | — | — |
| gpt-4o-2024-05-13 | active | — | — |

## 解决方案

1. ```
   在每个 delta 中检查 'content' 和 'tool_calls'：如果存在 'tool_calls'，则单独处理；如果缺少 'content'，则初始化为空字符串。
   ```
2. ```
   使用 OpenAI SDK 内置的流式处理辅助函数，自动将 delta 解析为完整消息，例如 client.beta.chat.completions.stream()
   ```
3. ```
   实现一个健壮的 delta 累加器，跨块跟踪 content 和 tool_calls，在处理前组装成完整消息。
   ```

## 无效尝试

- **** — This masks the error but does not handle tool_calls; the application may miss tool call data entirely (60% 失败率)
- **** — Skipping chunks may lose tool call data or other important deltas, corrupting the response (80% 失败率)
- **** — Disabling streaming eliminates the error but increases latency and defeats the purpose of streaming for user experience (40% 失败率)
