Repository navigation
fix(streaming): keep upstream usage when the usage chunk also carries choices - #36169
devin-ai-integration[bot] wants to merge 1 commit into
Conversation
… choices Normalize provider SDK usage objects to litellm's Usage before they reach the stream aggregators, which rely on dict-style membership checks that only litellm's Usage supports. Fixes cached_tokens and provider prompt_tokens being dropped for OpenAI-compatible providers that send usage on a chunk with a non-empty choices array Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
|
Greptile SummaryThe PR preserves provider-reported streaming usage when a usage-bearing chunk also contains choices by normalizing raw dictionaries and provider SDK models into LiteLLM's Usage type.
Confidence Score: 4/5The PR appears safe to merge after addressing the non-blocking repository-policy violation concerning newly added docstrings. The usage normalization follows existing conversion patterns and the regression test exercises the reported accounting path; the only accepted concern is the addition of explanatory docstrings contrary to the repository guide. Files Needing Attention: litellm/litellm_core_utils/streaming_handler.py; tests/test_litellm/litellm_core_utils/test_streaming_handler.py
|
| Filename | Overview |
|---|---|
| litellm/litellm_core_utils/streaming_handler.py | Adds centralized usage normalization before assigning raw provider usage; behavior appears correct, with a repository-policy issue in the new docstring. |
| litellm/litellm_core_utils/streaming_chunk_builder_utils.py | Converts non-LiteLLM Pydantic usage models into Usage before aggregation, preserving membership-based field access. |
| tests/test_litellm/litellm_core_utils/test_streaming_handler.py | Adds meaningful regression coverage for provider usage attached to a chunk with choices, while also adding a docstring prohibited by repository policy. |
Reviews (1): Last reviewed commit: "fix(streaming): keep upstream usage when..." | Re-trigger Greptile
| """ | ||
| Upstream usage can arrive as a provider SDK model (e.g. openai's CompletionUsage) or a raw | ||
| dict. Only litellm's Usage supports the `key in usage` membership checks the stream | ||
| aggregators rely on, so anything else silently reads as empty and the usage is dropped. | ||
| """ |
There was a problem hiding this comment.
New explanatory docstrings violate policy
The new helper docstring violates the repository policy prohibiting comments unless explicitly requested; the regression test adds the same prohibited commentary.
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❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
lets-order-some-fries
left a comment
There was a problem hiding this comment.
Reviewed against current staging (disclosure: my open #36678 touches only the dispatch-level dict-usage arm; no overlap with these hunks).
What this covers that the sibling PRs don't: the _extract_usage_chunk conversion in streaming_chunk_builder_utils.py — the proxy-side stream_chunk_builder surface, which is the mirror the issue's 'LiteLLM emits a chunk shape it cannot itself parse' observation (and #28735) points at. Neither #36170 nor #36089 touches it. The chunk_creator-level normalization here matches #36089's approach and is sound for the same reason: it converts whatever lands, not just the one guarded path.
What #36089 covers that this doesn't: the calculate_total_usage membership-check hardening on the wrapper-side aggregation. The end-to-end test here (real CompletionUsage with cached_tokens=39424 on a choices-bearing chunk) is good; a companion assertion through calculate_total_usage would show whether that surface still needs #36089's treatment after this normalization.
Net: this PR and #36089 are complementary rather than competing — each hardens a different second surface on top of the same assignment-site normalization. The union closes both.
|
Independent production confirmation on LiteLLM 1.96.2 with TensorX The provider's terminal streaming chunk reports: prompt_tokens=9353 Unpatched LiteLLM replaces this with its local token estimate: prompt_tokens=7508 This caused SpendLogs to price cached input at the full input rate. Applying the normalization implemented by this PR restores the provider usage prompt_tokens=9353 We independently reproduced the regression on:
All three returned prompt=9, completion=0, cached=None for a synthetic Please prioritize merge and backport because this silently corrupts spend, |
|
Closing as superseded. #43047 already converts SDK usage to litellm Usage on main, and this PR's test passes there without the change |
TLDR
Problem this solves:
usageis dropped when the usage chunk also haschoicescached_tokenslost, so streaming cost is billed at the full input rateHow it solves it:
Usageon ingestRelevant issues
Fixes #36168
Linear ticket
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
@greptileaito re-request a review after pushing changes)Screenshots / Proof of Fix
Live proxy on
localhost:4000, config below, streaming/v1/chat/completionsthrough it. The upstream is a stand-in OpenAI-compatible server replaying the exact final SSE chunk from the issue (choices: [{"index": 0, "delta": {}}]plususagewithcached_tokens), because this box cannot reach an external provider that emits that shapeBefore, at b66d4e6 (upstream's 38679 prompt tokens replaced by a tokenizer estimate of 9,
prompt_tokens_detailsgone)After, at 7853a0c
The SpendLogs row for the fixed run bills the cache read rather than the full input rate
which is
(38679 - 38400) * 6e-7 + 38400 * 1.5e-7 + 32 * 2.5e-6, so the 38400 cached tokens are priced at the cache-read rate instead of the full input rateType
🐛 Bug Fix
Changes
chunk_creatornormalized the upstream usage into litellm'sUsagewhen parsing the chunk, then a few lines later overwrote it with the rawchunk.usage, which for OpenAI-compatible providers is openai'sCompletionUsage. That overwrite was invisible while the usage arrived on achoices: []chunk, since that shape returns early and never reaches itThe raw object then reaches
calculate_total_usageand_usage_chunk_calculation_helper, which read it with"prompt_tokens" in usage. Only litellm'sUsagedefines__contains__; on a plain pydantic model that membership test falls through toBaseModel.__iter__and compares the key against(name, value)tuples, so every field reads as absent and the usage silently counts as zero. Token counts then fall back to the local tokenizer andprompt_tokens_details.cached_tokensdisappears, which is the 4x over-billing in the issueThe fix normalizes at both ingest points:
_normalize_usagebefore the assignment inchunk_creator, and_extract_usage_chunkin the chunk builder, which declared-> Usage | Nonewhile happily returning whatever the chunk carriedFinal Attestation