Repository navigation
fix(streaming): keep an explicit provider prompt_tokens=0 or completion_tokens=0 in streamed usage - #42323
Conversation
…on_tokens=0 in streamed usage The stream chunk builder started its per-chunk accumulators at 0 and adopted only nonzero counts, then fell back to litellm's tokenizer whenever the accumulated value was falsy, so a provider that reported an explicit 0 for prompt or completion tokens was billed the estimate instead. The accumulators now start at None, a usage chunk that reports a count marks it reported (a later chunk's 0 never replaces a reported nonzero), and the estimate only runs when no chunk reported the count. The Anthropic message_start cursor reset now yields None so the estimate still covers a cancelled stream, and Ollama chat streaming only attaches usage on the done chunk when both counts are present instead of inventing 0/0 on every chunk
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
| if usage_chunk_dict["completion_tokens"] is not None and ( | ||
| usage_chunk_dict["completion_tokens"] > 0 or completion_tokens is None | ||
| ): | ||
| completion_tokens = usage_chunk_dict["completion_tokens"] |
There was a problem hiding this comment.
A partial dict never reaches this helper because Usage(**chunk) coerces a missing count to 0 first. Only provider transformations see omission; this PR fixes Ollama's
There was a problem hiding this comment.
You're right — this concern does not apply here. By the time a chunk reaches _usage_chunk_calculation_helper, Usage has already normalized omitted token fields to 0, so a partial usage dict cannot produce a missing-count case in this accumulator. The omission handling belongs in the provider transformation layer, and this PR addresses that for Ollama by emitting usage only when both counts are present. Retracting the comment.
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit a64febb. Configure here.
…sage (#44230) * fix(streaming): restore the token estimate for streams that send no usage A stream without stream_options got a made-up Usage(0, 0) written into its final chunk's hidden params. Since #42323 the chunk builder treats that as a provider-reported zero, so these streams were logged and billed at 0 tokens and $0 instead of the tokenizer estimate. Only attach the summed usage when some chunk actually carried usage. * test(streaming): use a fixed start time and check the estimated cost * fix(streaming): keep reported usage on the synthesized finish chunk and test it * test(streaming): cover explicit zero usage reported by the provider * fix(streaming): set the token estimate on a copy of the final chunk and ignore usage with no counts * fix(streaming): keep final chunk edits in the logged response when the provider sends no usage * fix(streaming): mark the unreported usage placeholder so every chunk rebuild falls back to the estimate * test(streaming): wait on the success callback event instead of sleep-polling --------- Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
TLDR
Problem this solves:
prompt_tokens: 0got replaced by litellm's tokenizer estimatecompletion_tokens: 00/0usage to every chunk before the last oneHow it solves it:
None, not00stays0; the tokenizer only runs when nothing was reported0never overwrites a reported nonzero countUser Flow
Before: a developer whose provider reports a cache-served prompt as
prompt_tokens: 0is billed for that prompt anyway"model": "zero-usage","stream": true, and"stream_options": {"include_usage": true}prompt_tokens: 0, completion_tokens: 17, total_tokens: 17"usage": {"prompt_tokens": 13, "completion_tokens": 17, "total_tokens": 30}, 13 being litellm's own count of their request messagesprompt_tokens: 13, total_tokens: 30, and their logging callback (Langfuse, Datadog, a custom logger) records the same 13After: the same request comes back with the zero the provider reported
"model": "zero-usage","stream": true, and"stream_options": {"include_usage": true}prompt_tokens: 0, completion_tokens: 17, total_tokens: 17"usage": {"prompt_tokens": 0, "completion_tokens": 17, "total_tokens": 17}prompt_tokens: 0, total_tokens: 17, and their logging callback records the sameprompt_eval_count) still gets litellm's tokenizer estimate, exactly as beforeDesign decisions
Usagecoerces a missing count to0on construction, so key presence cannot be recovered downstream; the alternative, threading a "key was present" flag through every provider's usage chunk, was rejected as a much larger change for the same outcome0never overwrites a reported nonzero count, mirroring what the builder already does for cache tokens. Ollama sends0/0on every chunk before the done one, and pure last-wins would have turned every Ollama stream into0/0message_startcursor reset now yieldsNone(unreported) instead of0, so a cancelled Anthropic stream keeps getting the text-based estimate rather than a reported0prompt_eval_countandeval_countare present, the same both-or-nothing rule the Ollama completion sibling already applies. A done chunk missing a count now gets the tokenizer estimate instead of an invented0total_tokensis still recomputed as the sum of the two counts, so a provider'stotal_tokensis not adopted as reported; changing that is out of scope here0was audited and left alone. Anthropic mergesmessage_startintomessage_deltabefore building usage, the Anthropic passthrough logging handler keeps its own accumulator and only overwrites a count that arrived, Gemini and Cohere were streamed live and carry both counts on every usage-bearing chunk, and Bedrock DeepSeek R1 reports its counts once in the final invocation metrics. The remaining.get(..., 0)sites (watsonx, AgentCore, GigaChat, the Llama-shaped Bedrock invoke parser) only matter for a stream that breaks before the chunk carrying the count, since a reported nonzero count is never displaced by a later0(decision 3); guarding them here would touch four more providers with no repro for any of them> 0gate silently replaced it with the estimate. No provider emits one, and inventing a positive number in place of what the provider said is the behavior this PR removes, so the builder does not validate the signRelevant issues
Affected release
Linear ticket
Resolves LIT-7616
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/test_litellm/<your_test_file>.py -v. Leave the suites (make test-unit-*,make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more@greptileaito re-request a review after pushing changes)Delays in PR merge?
If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).
Screenshots / Proof of Fix
Two concurrent legs, each its own worktree, venv (Python 3.12), Postgres database, and random port, each proxy booted with
--num_workers 2(twomultiprocessing.spawnuvicorn workers confirmed in the process tree): the before leg at the merge base 3597d61, the after leg at the PR tip a64febb. Real provider calls (gpt-5.6 through OpenAI, claude-sonnet-5 through Anthropic) cost real money; Ollama 0.34.2 servesqwen3:0.6blocally. Clients: OpenAI SDK 2.33.0, Anthropic SDK 0.84.0, curlConfig (
config.yaml), the same on both legs:zero_usage_provider.pyis a documentedCustomLLMstanding in for a provider that reports a cache-served prompt as zero: its stream yields the words of "Cached prompt, billed zero input tokens." and a final chunk withusage={"prompt_tokens": 0, "completion_tokens": 17, "total_tokens": 17};usage_file_loggeris aCustomLoggerthat appendsprompt_tokens,completion_tokens,total_tokens, andresponse_costfrom thestandard_logging_object(what a Langfuse or Datadog integration receives) to a fileBoot, both legs (
<port>random and free,$Lthe leg's directory):The client (
client_three_endpoints.py) sendsSay hi in three words.to every model on the three unified endpoints, reads thex-litellm-call-idresponse header, and prints one JSON line per call with the usage the SDK handed back:/v1/chat/completionsviaopenai_client.chat.completions.create(model=..., messages=[...], stream=True, stream_options={"include_usage": True})(usage from the last chunk),/v1/responsesviaopenai_client.responses.create(model=..., input=..., stream=True)(usage from theresponse.completedevent),/v1/messagesviaanthropic_client.messages.create(model=..., max_tokens=512, messages=[...], stream=True)(input_tokensfrommessage_start,output_tokensfrommessage_delta). The lines below are condensed to the token counts (python3 condense_usage.py <leg>_client.jsonl); the full lines with the response ids are in the run's filesBefore (3597d61)
/v1/chat/completions
curl -s "$PROXY_BASE/v1/chat/completions" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d '{"model":"zero-usage","messages":[{"role":"user","content":"Say hi in three words."}],"stream":true,"stream_options":{"include_usage":true}}' | grep '"usage"'The provider said
prompt_tokens: 0, total_tokens: 17; the client gotprompt_tokens: 13, total_tokens: 30(13 is litellm's tokenizer count of the request messages)OpenAI SDK, same request:
/v1/responses
OpenAI SDK
responses.create(stream=True):/v1/messages
Anthropic SDK
messages.create(stream=True):GET /spend/logs and the logging callback
for cid in 4b0fbf12-9b04-4bfe-a1aa-dc292a8882cd e6bd90ef-7dbf-4a23-8507-c3cc12a5fcfe d699e4e0-8dc0-4bdc-8033-87e8f4c89d7a chatcmpl-9aa2420d-ab5d-4b59-82ec-befe18382f7e; do curl -s "$PROXY_BASE/spend/logs?request_id=$cid" -H "Authorization: Bearer $LITELLM_MASTER_KEY"; done(rows condensed to the usage columns):grep zero-usage-provider qa_before_callback_usage.jsonl(the file theCustomLoggerwrote):Real-provider controls (nonzero usage must pass through unchanged)
Same client, the other four models on all three endpoints:
Every spend log row and callback line for these twelve calls carried the same counts the client saw (with
/v1/messagesinput_tokenspluscache_read_input_tokensasprompt_tokens)Public SDK
litellm.stream_chunk_builderPYTHONPATH=qa_before .venv/bin/python sdk_builder_repro.py(OpenAI-shaped chunks for[{"role": "user", "content": "hi"}]and the text "Hi there", the last chunk carrying the usage shown):After (a64febb)
/v1/chat/completions
curl -s "$PROXY_BASE/v1/chat/completions" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d '{"model":"zero-usage","messages":[{"role":"user","content":"Say hi in three words."}],"stream":true,"stream_options":{"include_usage":true}}' | grep '"usage"'The client gets the
prompt_tokens: 0, total_tokens: 17the provider reportedOpenAI SDK, same request:
/v1/responses
OpenAI SDK
responses.create(stream=True):/v1/messages
Anthropic SDK
messages.create(stream=True):GET /spend/logs and the logging callback
for cid in 9fea7015-76b8-48ec-baf2-6402e9f6bedc 3670b2cc-969f-4fc3-a9ad-4ed195ea15a4 cd3ddcde-b77a-427e-b02b-5e05ba91df19 chatcmpl-4ae996f6-22d2-4966-ba91-c6e7e650fe34; do curl -s "$PROXY_BASE/spend/logs?request_id=$cid" -H "Authorization: Bearer $LITELLM_MASTER_KEY"; done(rows condensed to the usage columns):grep zero-usage-provider qa_after_callback_usage.jsonl:Real-provider controls (nonzero usage must pass through unchanged)
Same client, the other four models on all three endpoints:
Every spend log row and callback line for these twelve calls carried the same counts the client saw (with
/v1/messagesinput_tokenspluscache_read_input_tokensasprompt_tokens)Public SDK
litellm.stream_chunk_builderPYTHONPATH=qa_after .venv/bin/python sdk_builder_repro.py, same chunks:Observations from the run, none caused or changed by this PR:
/v1/messagesollama-openaiinput_tokens1: Anthropic semantics,cache_read_input_tokens15, both legscached_tokensshows on/v1/responses, not/v1/chat/completions, both legstotal_tokensis always the recomputed sum, both legs0/0/0chunk equals no usage chunk/v1/messagesbefore leg: empty text, 512 thinking tokensType
🐛 Bug Fix
Caveats (if any)
Low
.get(..., 0)sites (decision 7) only matter on streams that break mid-way; no repro on any providerFinal 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
a64febb passes /live-pr-risk