fix(openai): 修复流式响应末尾usage信息丢失问题 (#8306)

- 修复在流式处理过程中,因跳过 delta=None 且 choices=[] 的 usage chunk 导致最终 completion 丢失 usage 数据的问题
- 在 handle_chunk 调用条件中增加 chunk.usage 判断,确保末尾 usage chunk 能被正常传递给 state 处理
- 更新相关注释,说明 usage chunk 的例外情况,保障流式响应的 usage 信息完整性
This commit is contained in:
NayukiChiba
2026-05-23 23:17:44 +08:00
committed by GitHub
parent dcc99e6b9b
commit ff28eca9ca

View File

@@ -672,7 +672,9 @@ class ProviderOpenAIOfficial(Provider):
# 跳过 delta=None 的 chunk避免 SDK 内部 _convert_initial_chunk_into_snapshot
# 第 747 行 choice.delta.to_dict() 抛出 NoneType 错误。
# refs: AstrBot#6689 / openai-python#5069 / #5047
if delta is not None:
# 例外:流末尾的 usage chunkchoices=[]delta=None 但有 usage 数据)
# 需要传给 state否则最终 completion 会丢失 usage 信息
if delta is not None or chunk.usage:
try:
state.handle_chunk(chunk)
except Exception as e: