fix(openrouter): Extract usage from separate streaming chunk #829
+6
−4
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
When using OpenRouter with streaming and
stream_options.include_usage=true, usage data (token counts) is not captured in theStreamEndEvent.Root Cause
OpenRouter sends usage data in a separate final chunk after the
finish_reasonchunk:The current code only extracts usage when
finish_reason !== null:Since the usage chunk has
finish_reason: null, usage extraction is skipped.Solution
Move usage extraction outside the
finish_reasoncheck so it runs on every chunk. TheextractUsage()method already safely returnsnullwhen there's no usage data.Testing
Tested with OpenRouter API (via vLLM endpoint):
Before fix:
After fix:
Impact
extractUsage()is idempotent and safe to call on every chunk