You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix(llm): cache token usage (cache_read_tokens) always reported as 0 when streaming is enabled #2896
When stream=true is set in the LLM config, cache_read_tokens and cache_write_tokens are always reported as 0 in the SDK's usage metrics, even though prompt caching is working correctly at the provider level.
This is a reporting/display bug only — actual caching at the provider still works and cost savings are realized. But cache hit rate monitoring, cost tracking dashboards, and telemetry are affected.
Reproduction
Configure the SDK with stream: true and caching_prompt: true
Make multiple LLM calls through a LiteLLM proxy (e.g., llm-proxy.app.all-hands.dev)
Observe that cache_read_tokens is always 0 in the metrics
With stream: false, cache_read_tokens correctly shows non-zero values.
Root Cause
When the SDK makes a streaming request to a LiteLLM proxy:
The proxy auto-adds stream_options={"include_usage": True} to the upstream provider call, so the provider sends cache token usage in the final streaming chunk.
The proxy correctly builds a usage-only final chunk (with prompt_tokens_details.cached_tokens) and sends it to the client.
The client's LiteLLM streaming handler discards the usage-only chunk because the SDK doesn't pass stream_options={"include_usage": True}. In streaming_handler.py:
else: # no choices in chunkif (self.stream_optionsisnotNoneandself.stream_options["include_usage"] isTrue):
returnmodel_response# ← Not taken (stream_options is None)return# ← Usage-only chunk silently discarded!
The client falls back to calculate_total_usage() which only extracts prompt_tokens and completion_tokens, dropping prompt_tokens_details (which contains cached_tokens).
Proposed Fix
When streaming is enabled, the SDK should automatically set stream_options={"include_usage": True} on the request kwargs. This ensures the client-side streaming handler properly receives and propagates the usage-only chunk with cache token details.
Activity