Skip to content

fix(streaming): read a streamed usage chunk that is an OpenAI SDK object - #41429

Closed
mrpavelgoodman wants to merge 6 commits into
BerriAI:mainfrom
mrpavelgoodman:fix/stream-usage-openai-sdk-details
Closed

mrpavelgoodman wants to merge 6 commits into
BerriAI:mainfrom
mrpavelgoodman:fix/stream-usage-openai-sdk-details

Conversation

@mrpavelgoodman

Copy link
Copy Markdown

The problem

ChunkProcessor._usage_chunk_calculation_helper reads the aggregated streaming usage block through the Mapping protocol:

if "prompt_tokens" in usage_chunk:
    prompt_tokens = usage_chunk.get("prompt_tokens", 0) or 0

and accepts token details only as a dict or as litellm's own PromptTokensDetailsWrapper / CompletionTokensDetails.

That holds for a litellm Usage, which implements __contains__ and get. But the chunk is not always one: against an OpenAI-compatible upstream the aggregator receives the OpenAI SDK's CompletionUsage, whose details are openai.types.completion_usage.PromptTokensDetails and CompletionTokensDetails.

CompletionUsage answers neither in nor get, so:

  • every token count read that way came back 0, and calculate_usage fell back to counting the prompt with litellm's own tokenizer;
  • the isinstance chain matched neither detail model, so prompt_tokens_details was dropped and cached_tokens never reached the caller.

Measured

One streamed request against an OpenAI-compatible provider:

prompt completion reasoning prompt_tokens_details
upstream sent 37 110 83 present
litellm reported 14 33 103 None
after this change 37 125 103 present

And on a repeated 5234-token prefix the same streamed request now reports cached_tokens: 4992 where it previously reported nothing at all — so a cache-heavy streaming workload was being billed at the full input rate rather than the cache-read rate.

The change

Attribute access replaces the Mapping reads. A litellm Usage is a pydantic model and answers getattr identically, so nothing changes for the shape that already worked. A small _as_token_details coercion accepts a wrapper, a dict, or anything with model_dump().

Two tests cover both shapes: an SDK CompletionUsage and a litellm Usage.

Related

`_usage_chunk_calculation_helper` reads the aggregated usage block through the
Mapping protocol (`"prompt_tokens" in usage_chunk`, `usage_chunk.get(...)`) and
accepts token details only as a `dict` or as litellm's own wrapper. That holds
for a litellm `Usage`, which implements `__contains__`/`get`, but the chunk is
not always one: against an OpenAI-compatible upstream the aggregator receives
the OpenAI SDK's `CompletionUsage`, whose details are the SDK's own
`PromptTokensDetails` and `CompletionTokensDetails`.

`CompletionUsage` answers neither `in` nor `get`, so every token count read this
way came back zero and `calculate_usage` fell back to counting the prompt with
litellm's tokenizer; the isinstance chain matched neither detail model, so
`prompt_tokens_details` was dropped and `cached_tokens` never reached the
caller.

Measured against an OpenAI-compatible provider, one streamed request:

    upstream sent      prompt 37, completion 110 (reasoning 83), cached present
    litellm reported   prompt 14, completion  33, prompt_tokens_details None
    after this change  prompt 37, completion 125 (reasoning 103), details present

On a repeated 5234-token prefix the same request reports cached_tokens 4992
where it previously reported none, so a cache-heavy streaming workload was
being costed at the full input rate.

Attribute access replaces the Mapping reads -- a litellm `Usage` is a pydantic
model and answers those identically -- and a small coercion accepts any details
object that can be dumped. Covered both ways: an SDK `CompletionUsage` and a
litellm `Usage`.

Related: BerriAI#36168, BerriAI#37485. BerriAI#36906 restores `prompt_tokens_details` for the same
shape but leaves the token counts themselves at the tokenizer estimate.
@mrpavelgoodman
mrpavelgoodman requested a review from a team September 16, 2026 15:29
@CLAassistant

CLAassistant commented Sep 16, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@codspeed

codspeed Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing mrpavelgoodman:fix/stream-usage-openai-sdk-details (0708982) with main (4e99640)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Sep 16, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR changes streamed usage parsing to use attributes and adds token-detail coercion for OpenAI SDK models

  • Preserves prompt, completion, cache, and reasoning token details from SDK-shaped usage objects
  • Adds focused SDK and LiteLLM usage tests
  • Needs stronger typing, shorter documentation, and a regression test through the real aggregation path

Confidence Score: 4/5

The behavior appears low risk, but repository requirements must be satisfied before merging

The parsing change has no established runtime failure, but its untyped helper, excessive comments, and production-path test gap violate explicit repository guidance

Files Needing Attention: litellm/litellm_core_utils/streaming_chunk_builder_utils.py, tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py

Important Files Changed
Filename Overview
litellm/litellm_core_utils/streaming_chunk_builder_utils.py Adds SDK token-detail coercion and attribute-based usage reads, but introduces an explicitly untyped parameter and excessive documentation
tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py Adds coverage for SDK and LiteLLM objects, but the SDK test bypasses the production extraction and aggregation path

Reviews (1): Last reviewed commit: "fix(streaming): read a streamed usage ch..." | Re-trigger Greptile

_TokenDetails = TypeVar("_TokenDetails", CompletionTokensDetails, PromptTokensDetailsWrapper)


def _as_token_details(value: Any, wrapper: type[_TokenDetails]) -> _TokenDetails | None:

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 Untyped helper parameter _as_token_details accepts Any, violating the requirement that every function parameter be strongly typed. This must be fixed before merging

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!

Comment on lines +216 to +224
"""Coerce a token-details object of any shape into litellm's own model.

A streamed usage block does not always arrive as a litellm ``Usage``. When the
upstream is OpenAI-compatible, the OpenAI SDK's ``CompletionUsage`` reaches the
aggregator with ``openai.types.completion_usage.PromptTokensDetails`` and
``CompletionTokensDetails`` inside it, which are neither a ``dict`` nor
litellm's wrapper, so the previous isinstance chain dropped them and
``cached_tokens`` was reported as absent on every streamed request.
"""

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 Excessive explanatory docstrings The new source and test docstrings restate straightforward behavior, violating the requirement to reserve comments for complex business logic. Fix before merging

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!

completion_tokens_details=SDKCompletionTokensDetails(reasoning_tokens=103),
)

summary: Final = ChunkProcessor.__new__(ChunkProcessor)._usage_chunk_calculation_helper(usage_chunk)

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 Regression test bypasses production The SDK test calls the private helper directly, skipping normalization and aggregation, so it does not protect the real production path. Fix before merging

Context Used: CLAUDE.md (source)

@codecov

codecov Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Codecov Report

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

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

📢 Thoughts on this report? Let us know!

The strict-rule gate counts ANN401, and `Any` here bought nothing: the function
only ever tests the value with `isinstance` and looks for `model_dump`, both of
which `object` allows.
…prose

Review asked for three things. The `Any` annotation is gone in the previous
commit. The remaining two, here: the tests now drive the real aggregation path
rather than calling the private helper, using the existing
`_fail_prompt_token_count` so a silent fall back to the tokenizer fails the
test rather than passing quietly; and the docstrings say what the code does
once instead of restating it.
LIT002 counts mutable-collection literals, and these do not need to be
mutable: the aggregator only reads them.
LIT002 counts it, and it was doing nothing: both wrappers accept the unset
fields of a model_dump as None, which is what they already hold.
Both branches of the coercion are reachable through calculate_usage, so they
are tested there rather than against the private helper.
@mateo-berri

Copy link
Copy Markdown
Contributor

Thanks for the contribution!

#44349 now converts SDK usage objects to LiteLLM Usage in extract_usage_chunk on main, so I'm closing this

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

3 participants