Repository navigation
fix(streaming): preserve upstream usage with non-empty choices - #36170
daleselaji-dev wants to merge 3 commits into
Conversation
|
|
Greptile SummaryThe PR changes streaming usage precedence so an already-normalized LiteLLM usage object is not replaced by raw SDK usage, preserving provider token details such as cached tokens.
Confidence Score: 4/5The PR appears safe to merge after addressing the non-blocking source-comment convention issue. The usage-precedence change preserves normalized upstream accounting data, and the only accepted concern is the newly added explanatory source comment. Files Needing Attention: litellm/litellm_core_utils/streaming_handler.py
|
| Filename | Overview |
|---|---|
| litellm/litellm_core_utils/streaming_handler.py | Adds the intended usage-precedence guard, with one non-blocking violation of the repository’s no-new-source-comments convention. |
| tests/litellm/test_streaming_usage_with_choices.py | Adds focused coverage confirming prompt-token and cached-token details survive processing of a usage-bearing chunk with non-empty choices. |
Reviews (1): Last reviewed commit: "fix(streaming): preserve usage with non-..." | Re-trigger Greptile
|
|
||
| if hasattr(chunk, "usage") and chunk.usage is not None: | ||
| # OpenAI-compatible chunks may expose an SDK-specific usage model. | ||
| # The branch above already normalizes that model to LiteLLM's Usage; |
There was a problem hiding this comment.
This explanatory block adds source-code commentary contrary to the repository’s no-new-comments convention, increasing maintenance overhead where the guard and regression test already convey the behavior.
Context Used: CLAUDE.md (source)
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
lets-order-some-fries
left a comment
There was a problem hiding this comment.
Reviewed against the current staging code paths (I've been working in this file recently — disclosure: my open #36678 touches only the dispatch-level dict-usage arm and overlaps none of these hunks).
What this gets right: smallest possible diff for the reported scenario, and the mechanism is sound — model_response is created fresh per chunk, so the usage is None guard correctly means 'the dispatch-level conversion already set a properly-typed litellm.Usage for THIS chunk; don't clobber it with the raw SDK object'. The end-to-end test with real CompletionUsage/PromptTokensDetails types proves the consumer now receives a typed Usage with cached_tokens intact for the exact #36168 shape (usage + non-empty choices).
Two gaps worth being aware of (may be acceptable scope):
- Any path where
_dispatch_provider_chunkdoes not setmodel_response.usage(provider branches that don't copy usage into the response, or chunks whose usage only exists as the.usageattribute) still assigns the raw object — so downstream membership-style checks in the aggregators remain exposed to non-Usageshapes there. - The proxy-side
stream_chunk_builderpath (_extract_usage_chunk) is untouched, which is the mirror surface the issue's 'LiteLLM emits a shape it cannot itself parse' observation points at.
#36089 and #36169 each harden one of those two aggregation surfaces (different ones — they're complementary). If the maintainers want minimal-first, this PR + a follow-up on the aggregators would also get there.
|
Thanks for the contribution! I'm closing this because #43047 converts chunk usage to |
Problem
OpenAI-compatible providers can put the final streaming
usageobject on a chunk that still contains a content-freechoicesentry. LiteLLM currently loses the provider's prompt-token counts andprompt_tokens_details.cached_tokensin that shape, so downstream aggregation falls back to local tokenization and can overbill cached input.Root Cause
The OpenAI-compatible streaming path first normalizes provider usage into LiteLLM's
Usagemodel. A later generic assignment overwrites that normalized value with the raw OpenAI SDK usage object. The raw object is not handled by the streaming usage accumulator's nested detail parser, so cached-token details and provider counts are discarded.Solution
Keep the already-normalized LiteLLM usage value when it exists, and only copy the raw chunk usage when no normalized value was produced.
Changes
CustomStreamWrapper.chunk_creator()so it cannot clobber normalized usage.choicesarray with provider-reported cached tokens.Testing
choices=[]andchoices=[{"delta":{}}]preserveprompt_tokens=39779andcached_tokens=39424.py -3 -m ruff check litellm/litellm_core_utils/streaming_handler.py— passed.py -3 -m ruff format --check litellm/litellm_core_utils/streaming_handler.py— passed.py -3 -m py_compile litellm/litellm_core_utils/streaming_handler.py— passed.git diff --check— passed.basedpyright— not run; the executable is not installed in this environment.Compatibility/Risk
Low risk. This changes only the precedence of usage objects in the OpenAI-compatible streaming path. Providers that do not supply a normalized usage value retain the existing fallback assignment.
Notes for Reviewer
The regression is isolated to ingress parsing of provider chunks with non-empty choices. It is distinct from PR #28736, which changes LiteLLM's egress shape to emit usage-only chunks with empty choices, and from PR #32130, which prevents a later usage chunk from clobbering an earlier prompt-token detail object. The test now lives under
tests/test_litellm/litellm_core_utils, which is covered by the repository's Core Utilities CI job.Linked Issue
Closes #36168