llm runtime_error ai_generated true

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

KeyError: 'content' — streaming response chunk missing 'content' field in assistant message delta

ID: llm/streaming-assistant-content-empty

其他格式: JSON · Markdown 中文 · English
90%修复率
87%置信度
1证据数
2024-03-22首次发现

版本兼容性

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

根因分析

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

English

When streaming responses that include tool calls, some chunks may contain only tool_calls without content; code that expects 'content' in every delta raises KeyError.

generic

官方文档

https://platform.openai.com/docs/guides/streaming-responses/streaming-tool-calls

解决方案

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

无效尝试

常见但无效的做法:

  1. 60% 失败

    This masks the error but does not handle tool_calls; the application may miss tool call data entirely

  2. 80% 失败

    Skipping chunks may lose tool call data or other important deltas, corrupting the response

  3. 40% 失败

    Disabling streaming eliminates the error but increases latency and defeats the purpose of streaming for user experience