Skip to content

fix(streaming): keep upstream usage when the usage chunk also carries choices - #36169

Closed
devin-ai-integration[bot] wants to merge 1 commit into
mainfrom
devin_ai_fix_streaming_usage_non_empty_choices_36168
Closed

devin-ai-integration[bot] wants to merge 1 commit into
mainfrom
devin_ai_fix_streaming_usage_non_empty_choices_36168

Conversation

@devin-ai-integration

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Upstream usage is dropped when the usage chunk also has choices
  • cached_tokens lost, so streaming cost is billed at the full input rate

How it solves it:

  • Normalize provider SDK usage objects to litellm's Usage on ingest

Relevant issues

Fixes #36168

Linear ticket

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to re-request a review after pushing changes)

Screenshots / Proof of Fix

Live proxy on localhost:4000, config below, streaming /v1/chat/completions through it. The upstream is a stand-in OpenAI-compatible server replaying the exact final SSE chunk from the issue (choices: [{"index": 0, "delta": {}}] plus usage with cached_tokens), because this box cannot reach an external provider that emits that shape

model_list:
  - model_name: kimi
    litellm_params:
      model: openai/moonshotai/kimi-k3
      api_base: http://127.0.0.1:8931/v1
      api_key: sk-x
    model_info:
      input_cost_per_token: 0.0000006
      output_cost_per_token: 0.0000025
      cache_read_input_token_cost: 0.00000015
general_settings:
  master_key: sk-1234
curl -s -N -X POST http://127.0.0.1:4000/v1/chat/completions \
  -H 'Authorization: Bearer sk-1234' -H 'Content-Type: application/json' \
  -d '{"model":"kimi","stream":true,"stream_options":{"include_usage":true},"messages":[{"role":"user","content":"ciao"}]}' | tail -3

Before, at b66d4e6 (upstream's 38679 prompt tokens replaced by a tokenizer estimate of 9, prompt_tokens_details gone)

data: {"id":"49c0","created":1786090761,"model":"kimi","object":"chat.completion.chunk","choices":[{"index":0,"delta":{}}],"usage":{"completion_tokens":1,"prompt_tokens":9,"total_tokens":10,"completion_tokens_details":{"reasoning_tokens":32,"text_tokens":0}}}

data: [DONE]

After, at 7853a0c

data: {"id":"49c0","created":1786090907,"model":"kimi","object":"chat.completion.chunk","choices":[{"index":0,"delta":{}}],"usage":{"completion_tokens":32,"prompt_tokens":38679,"total_tokens":38711,"completion_tokens_details":{"reasoning_tokens":32,"text_tokens":0},"prompt_tokens_details":{"cached_tokens":38400}}}

data: [DONE]

The SpendLogs row for the fixed run bills the cache read rather than the full input rate

curl -s 'http://127.0.0.1:4000/spend/logs' -H 'Authorization: Bearer sk-1234'
{'spend': 0.0060074, 'prompt_tokens': 38679, 'completion_tokens': 32}

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 rate

Type

🐛 Bug Fix

Changes

chunk_creator normalized the upstream usage into litellm's Usage when parsing the chunk, then a few lines later overwrote it with the raw chunk.usage, which for OpenAI-compatible providers is openai's CompletionUsage. That overwrite was invisible while the usage arrived on a choices: [] chunk, since that shape returns early and never reaches it

The raw object then reaches calculate_total_usage and _usage_chunk_calculation_helper, which read it with "prompt_tokens" in usage. Only litellm's Usage defines __contains__; on a plain pydantic model that membership test falls through to BaseModel.__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 and prompt_tokens_details.cached_tokens disappears, which is the 4x over-billing in the issue

The fix normalizes at both ingest points: _normalize_usage before the assignment in chunk_creator, and _extract_usage_chunk in the chunk builder, which declared -> Usage | None while happily returning whatever the chunk carried

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

… 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>
@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 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.

  • Normalizes usage at the streaming-handler ingest point.
  • Normalizes non-LiteLLM Pydantic usage objects during chunk building.
  • Adds a regression test covering cached-token details on a non-empty choices chunk.

Confidence Score: 4/5

The 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

Important Files Changed

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

Comment on lines +2248 to +2252
"""
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.
"""

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

codecov Bot commented Aug 7, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.66667% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...itellm_core_utils/streaming_chunk_builder_utils.py 66.66% 1 Missing ⚠️

📢 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 devin_ai_fix_streaming_usage_non_empty_choices_36168 (7853a0c) 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 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.

@oelmaier

Copy link
Copy Markdown

Independent production confirmation on LiteLLM 1.96.2 with TensorX
qwen3.8-2.4t-a95b.

The provider's terminal streaming chunk reports:

prompt_tokens=9353
completion_tokens=6
prompt_tokens_details.cached_tokens=9344

Unpatched LiteLLM replaces this with its local token estimate:

prompt_tokens=7508
prompt_tokens_details=None

This caused SpendLogs to price cached input at the full input rate.

Applying the normalization implemented by this PR restores the provider usage
end-to-end through the proxy:

prompt_tokens=9353
cached_tokens=9344
spend=0.005905

We independently reproduced the regression on:

  • 1.97.0
  • 1.98.0-rc.1
  • main at bc6e7df

All three returned prompt=9, completion=0, cached=None for a synthetic
CompletionUsage(prompt=1000, completion=100, cached=600) regression case.

Please prioritize merge and backport because this silently corrupts spend,
budget, and chargeback accounting for streamed cached input.

@yuneng-berri
yuneng-berri deleted the branch 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

Closing as superseded. #43047 already converts SDK usage to litellm Usage on main, and this PR's test passes there without the change

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