fix(llm): collect usage stats from final stream chunk#276
Merged
Conversation
The early break on </function> prevented receiving the final chunk that contains token usage data (input_tokens, output_tokens).
Contributor
Greptile SummaryThis PR fixes a regression where input tokens were always showing as zero in usage stats. The issue was caused by an early The fix replaces the immediate
This ensures usage statistics are properly captured while maintaining protection against misbehaving models. Confidence Score: 5/5
Important Files Changed
|
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.
Problem
Input tokens were always showing as zero in usage stats. This regression was introduced in commit
56526cbwhich added an earlybreakwhen</function>was found in the streamed response.When using streaming with
stream_options: {"include_usage": True}, the LLM API sends token usage data in a separate final chunk after all content chunks:The early
breakcaused us to exit the loop before receiving chunk 3, sostream_chunk_builder(chunks)built a response with no usage data.Solution
Instead of breaking immediately when
</function>is found, we now:usagedata (ideal case)This ensures we capture the usage chunk while still protecting against models that don't properly end their streams.
Thanks to @bearsyankees for catching this issue!