Skip to content

fix(streaming): keep an explicit provider prompt_tokens=0 or completion_tokens=0 in streamed usage - #42323

Merged
mateo-berri merged 1 commit into
mainfrom
litellm_stream_usage_keep_explicit_zero
Sep 21, 2026
Merged

mateo-berri merged 1 commit into
mainfrom
litellm_stream_usage_keep_explicit_zero

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • A streamed usage chunk saying prompt_tokens: 0 got replaced by litellm's tokenizer estimate
  • Same for an explicit completion_tokens: 0
  • Clients, logging callbacks, and the spend log all saw the invented count
  • Ollama chat streaming attached 0/0 usage to every chunk before the last one

How it solves it:

  • The stream builder now tracks "no chunk reported this count" as None, not 0
  • A reported 0 stays 0; the tokenizer only runs when nothing was reported
  • A later chunk's 0 never overwrites a reported nonzero count
  • Ollama chat only attaches usage on the done chunk, and only with both counts present

User Flow

Before: a developer whose provider reports a cache-served prompt as prompt_tokens: 0 is billed for that prompt anyway

  1. They send POST https://litellm-domain/v1/chat/completions with "model": "zero-usage", "stream": true, and "stream_options": {"include_usage": true}
  2. The provider's final usage chunk says prompt_tokens: 0, completion_tokens: 17, total_tokens: 17
  3. The last SSE chunk they receive carries "usage": {"prompt_tokens": 13, "completion_tokens": 17, "total_tokens": 30}, 13 being litellm's own count of their request messages
  4. GET https://litellm-domain/spend/logs?request_id= shows prompt_tokens: 13, total_tokens: 30, and their logging callback (Langfuse, Datadog, a custom logger) records the same 13

After: the same request comes back with the zero the provider reported

  1. They send the same POST https://litellm-domain/v1/chat/completions with "model": "zero-usage", "stream": true, and "stream_options": {"include_usage": true}
  2. The provider's final usage chunk says prompt_tokens: 0, completion_tokens: 17, total_tokens: 17
  3. The last SSE chunk they receive carries "usage": {"prompt_tokens": 0, "completion_tokens": 17, "total_tokens": 17}
  4. GET https://litellm-domain/spend/logs?request_id= shows prompt_tokens: 0, total_tokens: 17, and their logging callback records the same
  5. A provider that sends no usage chunk at all (or an Ollama done chunk without prompt_eval_count) still gets litellm's tokenizer estimate, exactly as before

Design decisions

  1. No existing PR was built on: fix(streaming): update cache tokens on explicit zero update (#40736) #40743, fix: resolve zero token usage in Google GenAI adapter streaming path #33050, and fix(streaming): read a streamed usage chunk that is an OpenAI SDK object #41429 touch streamed usage but fix different bugs, none of them the explicit-zero replacement
  2. "Reported" means a usage chunk carried the count. Usage coerces a missing count to 0 on 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 outcome
  3. A later chunk's 0 never overwrites a reported nonzero count, mirroring what the builder already does for cache tokens. Ollama sends 0/0 on every chunk before the done one, and pure last-wins would have turned every Ollama stream into 0/0
  4. The Anthropic message_start cursor reset now yields None (unreported) instead of 0, so a cancelled Anthropic stream keeps getting the text-based estimate rather than a reported 0
  5. Ollama chat attaches usage only on the done chunk and only when both prompt_eval_count and eval_count are 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 invented 0
  6. total_tokens is still recomputed as the sum of the two counts, so a provider's total_tokens is not adopted as reported; changing that is out of scope here
  7. Every other streaming transformation that fills a missing count with 0 was audited and left alone. Anthropic merges message_start into message_delta before 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 later 0 (decision 3); guarding them here would touch four more providers with no repro for any of them
  8. A negative reported count is adopted like any other reported value; the base's > 0 gate 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 sign

Relevant issues

Affected release

Linear ticket

Resolves LIT-7616

Pre-Submission checklist

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

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. 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
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • 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)

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 (two multiprocessing.spawn uvicorn 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 serves qwen3:0.6b locally. Clients: OpenAI SDK 2.33.0, Anthropic SDK 0.84.0, curl

Config (config.yaml), the same on both legs:

model_list:
  - model_name: zero-usage
    litellm_params:
      model: zero-usage-provider/cached-backend
  - model_name: gpt-5.6
    litellm_params:
      model: openai/gpt-5.6
      api_key: os.environ/OPENAI_API_KEY
  - model_name: claude-sonnet-5
    litellm_params:
      model: anthropic/claude-sonnet-5
      api_key: os.environ/ANTHROPIC_API_KEY
  - model_name: ollama-openai
    litellm_params:
      model: openai/qwen3:0.6b
      api_base: http://127.0.0.1:11434/v1
      api_key: ollama
  - model_name: ollama-native
    litellm_params:
      model: ollama_chat/qwen3:0.6b
      api_base: http://127.0.0.1:11434

litellm_settings:
  custom_provider_map:
    - provider: zero-usage-provider
      custom_handler: zero_usage_provider.zero_prompt_usage_llm
  callbacks: zero_usage_provider.usage_file_logger

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
  database_url: os.environ/DATABASE_URL

zero_usage_provider.py is a documented CustomLLM standing 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 with usage={"prompt_tokens": 0, "completion_tokens": 17, "total_tokens": 17}; usage_file_logger is a CustomLogger that appends prompt_tokens, completion_tokens, total_tokens, and response_cost from the standard_logging_object (what a Langfuse or Datadog integration receives) to a file

REPLY_WORDS = ("Cached", " prompt", ", billed", " zero", " input", " tokens", ".")
REPORTED_USAGE = {"prompt_tokens": 0, "completion_tokens": 17, "total_tokens": 17}


def _chunks() -> list[GenericStreamingChunk]:
    text_chunks: list[GenericStreamingChunk] = [
        {"text": word, "tool_use": None, "is_finished": False, "finish_reason": "", "usage": None, "index": 0}
        for word in REPLY_WORDS
    ]
    final: GenericStreamingChunk = {
        "text": "",
        "tool_use": None,
        "is_finished": True,
        "finish_reason": "stop",
        "usage": dict(REPORTED_USAGE),
        "index": 0,
    }
    return [*text_chunks, final]


class ZeroPromptUsageLLM(CustomLLM):
    def streaming(self, *args, **kwargs) -> Iterator[GenericStreamingChunk]:
        yield from _chunks()

    async def astreaming(self, *args, **kwargs) -> AsyncIterator[GenericStreamingChunk]:
        for chunk in _chunks():
            yield chunk

Boot, both legs (<port> random and free, $L the leg's directory):

~/.claude/bin/detach run proxy-lit7616-qa-<leg> -- zsh -c 'set -a; source $L/qa_<leg>.env; set +a; cd $L && PYTHONPATH=$L $L/qa_<leg>/.venv/bin/python $L/qa_<leg>/litellm/proxy/proxy_cli.py --config $L/config.yaml --port <port> --num_workers 2 --use_v2_migration_resolver'

The client (client_three_endpoints.py) sends Say hi in three words. to every model on the three unified endpoints, reads the x-litellm-call-id response header, and prints one JSON line per call with the usage the SDK handed back: /v1/chat/completions via openai_client.chat.completions.create(model=..., messages=[...], stream=True, stream_options={"include_usage": True}) (usage from the last chunk), /v1/responses via openai_client.responses.create(model=..., input=..., stream=True) (usage from the response.completed event), /v1/messages via anthropic_client.messages.create(model=..., max_tokens=512, messages=[...], stream=True) (input_tokens from message_start, output_tokens from message_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 files

Before (3597d61)

/v1/chat/completions

  1. 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"'

    data: {"id":"chatcmpl-9aa2420d-ab5d-4b59-82ec-befe18382f7e","created":1790025270,"model":"zero-usage","object":"chat.completion.chunk","choices":[{"index":0,"delta":{}}],"usage":{"completion_tokens":17,"prompt_tokens":13,"total_tokens":30,"completion_tokens_details":{"reasoning_tokens":0,"text_tokens":17}}}
    

    The provider said prompt_tokens: 0, total_tokens: 17; the client got prompt_tokens: 13, total_tokens: 30 (13 is litellm's tokenizer count of the request messages)

  2. OpenAI SDK, same request:

    {"endpoint": "/v1/chat/completions", "model": "zero-usage", "call_id": "4b0fbf12-9b04-4bfe-a1aa-dc292a8882cd", "usage": {"prompt_tokens": 13, "completion_tokens": 17, "total_tokens": 30}, "text": "Cached prompt, billed zero input tokens."}
    

/v1/responses

  1. OpenAI SDK responses.create(stream=True):

    {"endpoint": "/v1/responses", "model": "zero-usage", "call_id": "e6bd90ef-7dbf-4a23-8507-c3cc12a5fcfe", "usage": {"total_tokens": 30, "input_tokens": 13, "output_tokens": 17}, "text": "Cached prompt, billed zero input tokens."}
    

/v1/messages

  1. Anthropic SDK messages.create(stream=True):

    {"endpoint": "/v1/messages", "model": "zero-usage", "call_id": "d699e4e0-8dc0-4bdc-8033-87e8f4c89d7a", "usage": {"input_tokens": 13, "output_tokens": 17}, "text": "Cached prompt, billed zero input tokens."}
    

GET /spend/logs and the logging callback

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

    [{"request_id": "chatcmpl-cf003f69-fe99-4e4f-ae82-d1c7096a9606", "call_type": "acompletion", "model": "zero-usage-provider/cached-backend", "prompt_tokens": 13, "completion_tokens": 17, "total_tokens": 30, "spend": 0.0}]
    [{"request_id": "chatcmpl-abf46120-b44c-4a96-b637-2e4395f3253d", "call_type": "aresponses", "model": "zero-usage-provider/cached-backend", "prompt_tokens": 13, "completion_tokens": 17, "total_tokens": 30, "spend": 0.0}]
    [{"request_id": "msg_6a29b734-00a2-41ba-8d6c-e424258c49a1", "call_type": "anthropic_messages", "model": "zero-usage-provider/cached-backend", "prompt_tokens": 13, "completion_tokens": 17, "total_tokens": 30, "spend": 0.0}]
    [{"request_id": "chatcmpl-9aa2420d-ab5d-4b59-82ec-befe18382f7e", "call_type": "acompletion", "model": "zero-usage-provider/cached-backend", "prompt_tokens": 13, "completion_tokens": 17, "total_tokens": 30, "spend": 0.0}]
    
  2. grep zero-usage-provider qa_before_callback_usage.jsonl (the file the CustomLogger wrote):

    {"id": "chatcmpl-cf003f69-fe99-4e4f-ae82-d1c7096a9606", "model": "zero-usage-provider/cached-backend", "prompt_tokens": 13, "completion_tokens": 17, "total_tokens": 30, "response_cost": 0.0}
    {"id": "chatcmpl-abf46120-b44c-4a96-b637-2e4395f3253d", "model": "zero-usage-provider/cached-backend", "prompt_tokens": 13, "completion_tokens": 17, "total_tokens": 30, "response_cost": 0.0}
    {"id": "msg_6a29b734-00a2-41ba-8d6c-e424258c49a1", "model": "zero-usage-provider/cached-backend", "prompt_tokens": 13, "completion_tokens": 17, "total_tokens": 30, "response_cost": 0.0}
    {"id": "chatcmpl-9aa2420d-ab5d-4b59-82ec-befe18382f7e", "model": "zero-usage-provider/cached-backend", "prompt_tokens": 13, "completion_tokens": 17, "total_tokens": 30, "response_cost": 0.0}
    

Real-provider controls (nonzero usage must pass through unchanged)

  1. Same client, the other four models on all three endpoints:

    {"endpoint": "/v1/chat/completions", "model": "gpt-5.6", "call_id": "ef27b7b7-fb69-41f1-ad1b-acb274eeb199", "usage": {"prompt_tokens": 12, "completion_tokens": 32, "total_tokens": 44}, "text": "Hi there, friend!"}
    {"endpoint": "/v1/responses", "model": "gpt-5.6", "call_id": "7ad2bb86-1d08-472e-af2b-9ded10453571", "usage": {"total_tokens": 47, "input_tokens": 12, "output_tokens": 35}, "text": "Hi there, friend!"}
    {"endpoint": "/v1/messages", "model": "gpt-5.6", "call_id": "4dbe30be-57c8-490a-9764-52e446d59252", "usage": {"input_tokens": 12, "output_tokens": 45}, "text": "Hi there, friend!"}
    {"endpoint": "/v1/chat/completions", "model": "claude-sonnet-5", "call_id": "94f7ac8b-1125-4403-b547-fd93448d49ea", "usage": {"prompt_tokens": 14, "completion_tokens": 48, "total_tokens": 62}, "text": "Hi there, friend!"}
    {"endpoint": "/v1/responses", "model": "claude-sonnet-5", "call_id": "e4ba323c-72b9-418e-a42b-c2ef827ce1fa", "usage": {"total_tokens": 24, "input_tokens": 14, "output_tokens": 10}, "text": "Hi there, friend!"}
    {"endpoint": "/v1/messages", "model": "claude-sonnet-5", "call_id": "6cb8e6c8-5e5f-4ecd-9488-0522a5cefe0d", "usage": {"input_tokens": 14, "output_tokens": 10}, "text": "Hi there, friend!"}
    {"endpoint": "/v1/chat/completions", "model": "ollama-openai", "call_id": "2317f9e5-54c2-4467-9766-ef367ed26f8f", "usage": {"prompt_tokens": 16, "completion_tokens": 331, "total_tokens": 347}, "text": "Hi there!"}
    {"endpoint": "/v1/responses", "model": "ollama-openai", "call_id": "953ca3ae-9b43-4c87-a35d-ca7cc2ff2704", "usage": {"total_tokens": 232, "input_tokens": 16, "output_tokens": 216}, "text": "Hello!"}
    {"endpoint": "/v1/messages", "model": "ollama-openai", "call_id": "f6fec6f2-eedc-4d8d-bfc4-96619b0ca0a0", "usage": {"input_tokens": 1, "output_tokens": 302}, "text": "Hi!"}
    {"endpoint": "/v1/chat/completions", "model": "ollama-native", "call_id": "834c9442-e5b9-42a7-b4d0-581c8db96633", "usage": {"prompt_tokens": 16, "completion_tokens": 242, "total_tokens": 258}, "text": "Hi there!"}
    {"endpoint": "/v1/responses", "model": "ollama-native", "call_id": "f84588ef-45dd-4b1a-bab8-34f16b57aca1", "usage": {"total_tokens": 101, "input_tokens": 16, "output_tokens": 85}, "text": "Hello!"}
    {"endpoint": "/v1/messages", "model": "ollama-native", "call_id": "162e77c8-87a9-493a-bb27-ba6e4a5276d5", "usage": {"input_tokens": 16, "output_tokens": 512}, "text": ""}
    

    Every spend log row and callback line for these twelve calls carried the same counts the client saw (with /v1/messages input_tokens plus cache_read_input_tokens as prompt_tokens)

Public SDK litellm.stream_chunk_builder

  1. PYTHONPATH=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):

    explicit 0/17/17             provider usage={'prompt_tokens': 0, 'completion_tokens': 17, 'total_tokens': 17}  ->  litellm usage=(8, 17, 25)
    explicit 5/0/5               provider usage={'prompt_tokens': 5, 'completion_tokens': 0, 'total_tokens': 5}  ->  litellm usage=(5, 2, 7)
    explicit 5/17/22             provider usage={'prompt_tokens': 5, 'completion_tokens': 17, 'total_tokens': 22}  ->  litellm usage=(5, 17, 22)
    no usage chunk               provider usage=None  ->  litellm usage=(8, 2, 10)
    explicit 0/0/0               provider usage={'prompt_tokens': 0, 'completion_tokens': 0, 'total_tokens': 0}  ->  litellm usage=(8, 2, 10)
    

After (a64febb)

/v1/chat/completions

  1. 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"'

    data: {"id":"chatcmpl-4ae996f6-22d2-4966-ba91-c6e7e650fe34","created":1790025236,"model":"zero-usage","object":"chat.completion.chunk","choices":[{"index":0,"delta":{}}],"usage":{"completion_tokens":17,"prompt_tokens":0,"total_tokens":17,"completion_tokens_details":{"reasoning_tokens":0,"text_tokens":17}}}
    

    The client gets the prompt_tokens: 0, total_tokens: 17 the provider reported

  2. OpenAI SDK, same request:

    {"endpoint": "/v1/chat/completions", "model": "zero-usage", "call_id": "9fea7015-76b8-48ec-baf2-6402e9f6bedc", "usage": {"prompt_tokens": 0, "completion_tokens": 17, "total_tokens": 17}, "text": "Cached prompt, billed zero input tokens."}
    

/v1/responses

  1. OpenAI SDK responses.create(stream=True):

    {"endpoint": "/v1/responses", "model": "zero-usage", "call_id": "3670b2cc-969f-4fc3-a9ad-4ed195ea15a4", "usage": {"total_tokens": 17, "input_tokens": 0, "output_tokens": 17}, "text": "Cached prompt, billed zero input tokens."}
    

/v1/messages

  1. Anthropic SDK messages.create(stream=True):

    {"endpoint": "/v1/messages", "model": "zero-usage", "call_id": "cd3ddcde-b77a-427e-b02b-5e05ba91df19", "usage": {"input_tokens": 0, "output_tokens": 17}, "text": "Cached prompt, billed zero input tokens."}
    

GET /spend/logs and the logging callback

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

    [{"request_id": "chatcmpl-a260d9ac-183b-458f-b7a4-575fb7a5d481", "call_type": "acompletion", "model": "zero-usage-provider/cached-backend", "prompt_tokens": 0, "completion_tokens": 17, "total_tokens": 17, "spend": 0.0}]
    [{"request_id": "chatcmpl-b49e9ef3-84cf-48de-8c0d-12bffb40d893", "call_type": "aresponses", "model": "zero-usage-provider/cached-backend", "prompt_tokens": 0, "completion_tokens": 17, "total_tokens": 17, "spend": 0.0}]
    [{"request_id": "msg_13d0d167-7982-455f-ae11-3d52e9b41395", "call_type": "anthropic_messages", "model": "zero-usage-provider/cached-backend", "prompt_tokens": 0, "completion_tokens": 17, "total_tokens": 17, "spend": 0.0}]
    [{"request_id": "chatcmpl-4ae996f6-22d2-4966-ba91-c6e7e650fe34", "call_type": "acompletion", "model": "zero-usage-provider/cached-backend", "prompt_tokens": 0, "completion_tokens": 17, "total_tokens": 17, "spend": 0.0}]
    
  2. grep zero-usage-provider qa_after_callback_usage.jsonl:

    {"id": "chatcmpl-a260d9ac-183b-458f-b7a4-575fb7a5d481", "model": "zero-usage-provider/cached-backend", "prompt_tokens": 0, "completion_tokens": 17, "total_tokens": 17, "response_cost": 0.0}
    {"id": "chatcmpl-b49e9ef3-84cf-48de-8c0d-12bffb40d893", "model": "zero-usage-provider/cached-backend", "prompt_tokens": 0, "completion_tokens": 17, "total_tokens": 17, "response_cost": 0.0}
    {"id": "msg_13d0d167-7982-455f-ae11-3d52e9b41395", "model": "zero-usage-provider/cached-backend", "prompt_tokens": 0, "completion_tokens": 17, "total_tokens": 17, "response_cost": 0.0}
    {"id": "chatcmpl-4ae996f6-22d2-4966-ba91-c6e7e650fe34", "model": "zero-usage-provider/cached-backend", "prompt_tokens": 0, "completion_tokens": 17, "total_tokens": 17, "response_cost": 0.0}
    

Real-provider controls (nonzero usage must pass through unchanged)

  1. Same client, the other four models on all three endpoints:

    {"endpoint": "/v1/chat/completions", "model": "gpt-5.6", "call_id": "c000b505-4c1c-4dde-8fa0-56dc7cbcab24", "usage": {"prompt_tokens": 12, "completion_tokens": 36, "total_tokens": 48}, "text": "Hi there, friend!"}
    {"endpoint": "/v1/responses", "model": "gpt-5.6", "call_id": "f66ee4b5-f2ad-4fbd-9dda-4e86a63104f1", "usage": {"total_tokens": 48, "input_tokens": 12, "output_tokens": 36}, "text": "Hi there, friend!"}
    {"endpoint": "/v1/messages", "model": "gpt-5.6", "call_id": "73b369c0-4016-493d-9eb3-68985841e2e7", "usage": {"input_tokens": 12, "output_tokens": 44}, "text": "Hi there, friend!"}
    {"endpoint": "/v1/chat/completions", "model": "claude-sonnet-5", "call_id": "68a4c456-9934-4df0-ae3b-0fde3a088fbb", "usage": {"prompt_tokens": 14, "completion_tokens": 31, "total_tokens": 45}, "text": "Hi there, friend!"}
    {"endpoint": "/v1/responses", "model": "claude-sonnet-5", "call_id": "ceea0a75-d826-4b92-8c50-94389f6028d3", "usage": {"total_tokens": 24, "input_tokens": 14, "output_tokens": 10}, "text": "Hi there, friend!"}
    {"endpoint": "/v1/messages", "model": "claude-sonnet-5", "call_id": "2c830b4f-1317-4fae-81bf-03f61eea99cd", "usage": {"input_tokens": 14, "output_tokens": 10}, "text": "Hi there, friend!"}
    {"endpoint": "/v1/chat/completions", "model": "ollama-openai", "call_id": "deff56bf-55e5-4050-ac9e-02b3526c2eca", "usage": {"prompt_tokens": 16, "completion_tokens": 104, "total_tokens": 120}, "text": "hi"}
    {"endpoint": "/v1/responses", "model": "ollama-openai", "call_id": "ec3ce8d9-4cdf-43bf-bbba-a423923635b4", "usage": {"total_tokens": 195, "input_tokens": 16, "output_tokens": 179}, "text": "Hi!"}
    {"endpoint": "/v1/messages", "model": "ollama-openai", "call_id": "07238dd2-ef5e-4c6c-b7db-09c96f5d1047", "usage": {"input_tokens": 1, "output_tokens": 490}, "text": "Hi!"}
    {"endpoint": "/v1/chat/completions", "model": "ollama-native", "call_id": "a4b63d60-9d1d-42a2-949e-f9da30431fb6", "usage": {"prompt_tokens": 16, "completion_tokens": 263, "total_tokens": 279}, "text": "helo"}
    {"endpoint": "/v1/responses", "model": "ollama-native", "call_id": "a26bb15e-4f36-4e95-a67a-8069f4fba793", "usage": {"total_tokens": 346, "input_tokens": 16, "output_tokens": 330}, "text": "Hi!"}
    {"endpoint": "/v1/messages", "model": "ollama-native", "call_id": "9607df25-cf38-4cf3-bb6c-4603d3778fdf", "usage": {"input_tokens": 16, "output_tokens": 197}, "text": "Hi there!"}
    

    Every spend log row and callback line for these twelve calls carried the same counts the client saw (with /v1/messages input_tokens plus cache_read_input_tokens as prompt_tokens)

Public SDK litellm.stream_chunk_builder

  1. PYTHONPATH=qa_after .venv/bin/python sdk_builder_repro.py, same chunks:

    explicit 0/17/17             provider usage={'prompt_tokens': 0, 'completion_tokens': 17, 'total_tokens': 17}  ->  litellm usage=(0, 17, 17)
    explicit 5/0/5               provider usage={'prompt_tokens': 5, 'completion_tokens': 0, 'total_tokens': 5}  ->  litellm usage=(5, 0, 5)
    explicit 5/17/22             provider usage={'prompt_tokens': 5, 'completion_tokens': 17, 'total_tokens': 22}  ->  litellm usage=(5, 17, 22)
    no usage chunk               provider usage=None  ->  litellm usage=(8, 2, 10)
    explicit 0/0/0               provider usage={'prompt_tokens': 0, 'completion_tokens': 0, 'total_tokens': 0}  ->  litellm usage=(0, 0, 0)
    

Observations from the run, none caused or changed by this PR:

  • /v1/messages ollama-openai input_tokens 1: Anthropic semantics, cache_read_input_tokens 15, both legs
  • Ollama cached_tokens shows on /v1/responses, not /v1/chat/completions, both legs
  • total_tokens is always the recomputed sum, both legs
  • Before, an explicit 0/0/0 chunk equals no usage chunk
  • ollama-native /v1/messages before leg: empty text, 512 thinking tokens

Type

🐛 Bug Fix

Caveats (if any)

Low

  • Explicit 0 is now billed as 0, also when the stream breaks after the 0 chunk (failure row 13 -> 0); intended, this is the fix
  • An Ollama done chunk missing a count now estimates both sides; before it billed the missing side as 0
  • A negative reported count is adopted as reported (decision 8); no provider emits one, guarding it is validation the builder never did
  • Zero-reporting legs use a CustomLLM, since no public vendor emits an in-stream explicit 0; the gpt-5.6, claude-sonnet-5, and Ollama legs cover no-regression
  • Residual .get(..., 0) sites (decision 7) only matter on streams that break mid-way; no repro on any provider
  • Test file overlaps with sibling PR fix(streaming): let a later usage event zero out stale cache counts (#40736) #42330; whichever lands second takes a small test-file merge
  • Non-required CircleCI reds are fleet-wide: fireworks, bedrock, e2e_budgeting, and bad_database_url also red on main 89979 and 89974 to 89977; the 12 jev classifier tests and the fal video test are red on every litellm_ pipeline tonight (90004, 90000, 89998, 89991) and green on main, and pass locally on this tip; the gpt-5.6 responses 403 also hits fix(streaming): let a later usage event zero out stale cache counts (#40736) #42330; one fireworks stream job hit a server disconnect on one of two runs. Fixing any of them here is out of scope

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

  • a64febb passes /live-pr-risk

…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
@devin-ai-integration

devin-ai-integration Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor Author

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@codspeed

codspeed Bot commented Sep 21, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_stream_usage_keep_explicit_zero (a64febb) with main (89de508)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 4/5

The PR is not yet safe to merge because an existing streamed-usage contract issue remains unresolved for usage objects constructed from partial provider data.

Findings

  1. P1 Missing Counts Become Zero ▶

Summary

This PR distinguishes unreported streamed token counts from explicit provider-reported zeroes and limits Ollama chat usage emission to complete chunks with both counts present.

  • Uses None to trigger tokenizer fallback only when a count was not reported.
  • Preserves explicit zero prompt and completion counts.
  • Prevents preliminary Ollama 0/0 values from overriding final usage.
  • Adds regression coverage for explicit zeroes, missing usage, Anthropic cursor handling, and Ollama done chunks.

Reviews (2) · Last reviewed commit: "fix(streaming): keep an explicit provide..."

Comment on lines +884 to 887
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"]

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.

P1 Missing Counts Become Zero

For usage={"prompt_tokens": 5}, the omitted completion count becomes zero, suppressing fallback and producing incorrect usage and billing for streamed output

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.

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

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.

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

codecov Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

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

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

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

LGTM

@mateo-berri
mateo-berri merged commit 7ae61b6 into main Sep 21, 2026
144 of 152 checks passed
@mateo-berri
mateo-berri deleted the litellm_stream_usage_keep_explicit_zero branch September 21, 2026 22:13
mateo-berri added a commit that referenced this pull request Oct 20, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant