Skip to content

fix(streaming): preserve upstream usage with non-empty choices - #36170

Closed
daleselaji-dev wants to merge 3 commits into
BerriAI:mainfrom
daleselaji-dev:codex/preserve-stream-usage-36168
Closed

daleselaji-dev wants to merge 3 commits into
BerriAI:mainfrom
daleselaji-dev:codex/preserve-stream-usage-36168

Conversation

@daleselaji-dev

@daleselaji-dev daleselaji-dev commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Problem

OpenAI-compatible providers can put the final streaming usage object on a chunk that still contains a content-free choices entry. LiteLLM currently loses the provider's prompt-token counts and prompt_tokens_details.cached_tokens in 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 Usage model. 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

  • Guard the generic usage assignment in CustomStreamWrapper.chunk_creator() so it cannot clobber normalized usage.
  • Add a regression test to the existing core streaming-handler test path covering a non-empty choices array with provider-reported cached tokens.

Testing

  • Focused regression logic — passed in the local standalone wrapper/SSE reproduction.
  • Local HTTP/SSE reproduction — both choices=[] and choices=[{"delta":{}}] preserve prompt_tokens=39779 and cached_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.
  • Core test file collection is not locally verifiable because this sparse Windows environment has a pre-existing Pydantic forward-reference failure while importing the existing test module; the new test includes the same model-rebuild setup used to exercise the path.
  • basedpyright — not run; the executable is not installed in this environment.
  • Full suite — not run; repository-wide generated/workspace dependencies are unavailable 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

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@greptile-apps

greptile-apps Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

The 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.

  • Guards the fallback usage assignment in CustomStreamWrapper.chunk_creator().
  • Adds a regression test for usage attached to a non-empty choices chunk.

Confidence Score: 4/5

The 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

Important Files Changed

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

Comment on lines +1452 to +1454

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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 New source-code commentary

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

codecov Bot commented Aug 7, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing daleselaji-dev:codex/preserve-stream-usage-36168 (70859b2) with litellm_internal_staging (e1717c5)

Open in CodSpeed

@lets-order-some-fries lets-order-some-fries left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):

  1. Any path where _dispatch_provider_chunk does not set model_response.usage (provider branches that don't copy usage into the response, or chunks whose usage only exists as the .usage attribute) still assigns the raw object — so downstream membership-style checks in the aggregators remain exposed to non-Usage shapes there.
  2. The proxy-side stream_chunk_builder path (_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.

@yuneng-berri
yuneng-berri deleted the branch BerriAI:main September 13, 2026 04:39
@yuneng-berri yuneng-berri reopened this Sep 13, 2026
@devin-ai-integration
devin-ai-integration Bot changed the base branch from litellm_internal_staging to main September 23, 2026 15:14
@devin-ai-integration
devin-ai-integration Bot requested a review from a team September 23, 2026 15:14
@mateo-berri

Copy link
Copy Markdown
Contributor

Thanks for the contribution!

I'm closing this because #43047 converts chunk usage to litellm.Usage on main and keeps cached_tokens intact

@mateo-berri mateo-berri closed this Nov 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: streaming drops upstream usage when the final chunk has a non-empty choices array (cached_tokens lost, cost billed at full input rate)

5 participants