Repository navigation
Conversation
OpenAI 兼容的流式响应,最后一个 chunk 携带 usage 且 choices 为空数组。 原实现先访问 choices[0],空列表触发 IndexError 后直接 break, 该 chunk 的 usage 从未被读取,导致 UniResponse.usage 恒为 None, 只有非流式的工具轮次会计入 ledger,最终用量远小于实际。 - usage 提取移到 try 之前,与 call_tools 的写法对齐 - IndexError 分支由 break 改为 continue,避免跳过后续 chunk - 新增回归测试:构造 choices 为空的尾块并断言 usage 被捕获
Contributor
Reviewer's GuideImplementationExtract usage before accessing choices and continue past empty-choice chunks so streaming tail usage is retained.
TestsAdd a regression test for usage on an empty-choices tail chunk and import its usage type.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
问题
流式请求下
UniResponse.usage恒为None,ledger 里只有非流式轮次的记录,最终统计的 token 用量远小于实际消耗。原因
OpenAI 兼容的流式响应,最后一个 chunk 携带 usage,而它的
choices是空数组:{"choices": [], "usage": {"prompt_tokens": 100, "completion_tokens": 20, "total_tokens": 120}}call_api的流式分支里,usage 提取写在try内部,且排在chunk.choices[0]之后:空列表访问
choices[0]抛IndexError,except直接break,那个带 usage 的 chunk 被整个跳过。call_tools的分支写法是对的——先取 usage,再if not chunk.choices: continue。两处不一致。改动
try之前IndexError分支由break改为continue验证
新增回归测试
test_call_api_streaming_usage_in_tail_chunk,构造一个正文 chunk 加一个choices=[]的尾块,断言usage的prompt_tokens/completion_tokens/total_tokens都能拿到。回退源码后该测试失败(
usage为null),应用修复后通过。全量测试:687 passed。
Summary by Sourcery
Fix streaming response accounting so token usage from the final usage-only chunk is retained.
Bug Fixes:
Tests: