Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(backends/litellm): align streaming usage tokens with the non-streaming path (#2688)

Abhay Singh90a68e029101
diff --git a/headroom/backends/litellm.py b/headroom/backends/litellm.py
index 9f66ed6d3..799c9d439 100644
--- a/headroom/backends/litellm.py
+++ b/headroom/backends/litellm.py
@@ -1431,6 +1431,14 @@ class LiteLLMBackend(Backend):
final_input_tokens = 0
final_cache_read_tokens = 0
final_cache_write_tokens = 0
+ # Real output-token count from the trailing usage chunk. The
+ # ``output_tokens`` counter incremented per content_block_delta below
+ # is only a delta *count* (one per SSE chunk), which undercounts the
+ # true token total several-fold. Prefer the provider's
+ # completion_tokens when the usage chunk carries it, exactly like the
+ # non-streaming path (_anthropic_usage_from_litellm), and fall back to
+ # the delta count only when no usage chunk arrives.
+ final_output_tokens = 0
# Extended thinking is BUFFERED, not streamed live. A thinking block
# is only legal to replay if it leads the turn and carries a real
@@ -1533,6 +1541,7 @@ class LiteLLMBackend(Backend):
final_cache_write_tokens = int(
getattr(cu, "cache_creation_input_tokens", 0) or 0
)
+ final_output_tokens = int(getattr(cu, "completion_tokens", 0) or 0)
if not hasattr(chunk, "choices") or not chunk.choices:
continue
@@ -1669,9 +1678,21 @@ class LiteLLMBackend(Backend):
data={"type": "content_block_stop", "index": current_block_index},
)
- delta_usage: dict[str, Any] = {"output_tokens": output_tokens}
+ delta_usage: dict[str, Any] = {"output_tokens": final_output_tokens or output_tokens}
if final_input_tokens or final_cache_read_tokens or final_cache_write_tokens:
- delta_usage["input_tokens"] = final_input_tokens
+ # LiteLLM's prompt_tokens is the *total* prompt size, inclusive
+ # of the cache-read and cache-write tokens (Bedrock reports raw
+ # inputTokens and LiteLLM's AmazonConverseConfig._transform_usage
+ # adds cacheReadInputTokens + cacheWriteInputTokens onto it).
+ # Anthropic's input_tokens must exclude both, since the cache
+ # fields below report them separately and clients treat the three
+ # buckets as disjoint. Without the subtraction a cached streaming
+ # turn double-counts the cached prefix in input_tokens at the full
+ # input rate. Mirrors the non-streaming path in
+ # _anthropic_usage_from_litellm (#1345 / #1848).
+ delta_usage["input_tokens"] = max(
+ final_input_tokens - final_cache_read_tokens - final_cache_write_tokens, 0
+ )
if final_cache_read_tokens:
delta_usage["cache_read_input_tokens"] = final_cache_read_tokens
if final_cache_write_tokens:
diff --git a/tests/test_bedrock_tool_result_cache_and_streaming_stats.py b/tests/test_bedrock_tool_result_cache_and_streaming_stats.py
index 59591f011..6475c0d89 100644
--- a/tests/test_bedrock_tool_result_cache_and_streaming_stats.py
+++ b/tests/test_bedrock_tool_result_cache_and_streaming_stats.py
@@ -118,7 +118,11 @@ class TestStreamingCacheStatsCompletion:
"""stream_message must request usage and re-surface real cache stats."""
def _mock_stream_with_final_usage(
- self, cache_read: int = 0, cache_write: int = 0, prompt_tokens: int = 0
+ self,
+ cache_read: int = 0,
+ cache_write: int = 0,
+ prompt_tokens: int = 0,
+ completion_tokens: int = 50,
):
async def mock_stream():
chunk1 = MagicMock()
@@ -136,6 +140,7 @@ class TestStreamingCacheStatsCompletion:
]
chunk2.usage = MagicMock(
prompt_tokens=prompt_tokens,
+ completion_tokens=completion_tokens,
cache_read_input_tokens=cache_read,
cache_creation_input_tokens=cache_write,
)
@@ -169,8 +174,12 @@ class TestStreamingCacheStatsCompletion:
patch("headroom.backends.litellm.acompletion", new_callable=AsyncMock) as mock_acomp,
patch("headroom.backends.litellm._fetch_bedrock_inference_profiles", return_value={}),
):
+ # LiteLLM's prompt_tokens is inclusive of the cache tokens, so this
+ # 1600-token prompt is 100 uncached + 1200 cache-read + 300
+ # cache-write. Anthropic's input_tokens must report only the 100
+ # uncached tokens; the cache fields carry the rest.
mock_acomp.return_value = self._mock_stream_with_final_usage(
- cache_read=1200, cache_write=300, prompt_tokens=1500
+ cache_read=1200, cache_write=300, prompt_tokens=1600
)()
backend = LiteLLMBackend(provider="bedrock", region="us-east-1")
@@ -191,9 +200,117 @@ class TestStreamingCacheStatsCompletion:
message_deltas = [e for e in events if e.event_type == "message_delta"]
assert len(message_deltas) == 1
final_usage = message_deltas[0].data["usage"]
- assert final_usage["input_tokens"] == 1500
+ assert final_usage["input_tokens"] == 100
assert final_usage["cache_read_input_tokens"] == 1200
assert final_usage["cache_creation_input_tokens"] == 300
+ # Real completion_tokens from the usage chunk, not the 1 content delta.
+ assert final_usage["output_tokens"] == 50
+
+ @pytest.mark.asyncio
+ async def test_terminal_message_delta_input_tokens_excludes_cache_tokens(self):
+ """input_tokens must be disjoint from the cache buckets (#1345/#1848).
+
+ LiteLLM/Bedrock reports prompt_tokens inclusive of cache-read and
+ cache-write tokens, but Anthropic's three input buckets are disjoint:
+ a client sums input_tokens + cache_read_input_tokens +
+ cache_creation_input_tokens to get the total prompt, and bills each at
+ a different rate (cache-read 0.1x, cache-write 1.25x). Emitting the
+ inclusive prompt_tokens as input_tokens double-counts the whole cached
+ prefix at the full input rate on every cached streaming turn. The
+ non-streaming path already subtracts; the streaming path must match.
+ """
+ with (
+ patch("headroom.backends.litellm.acompletion", new_callable=AsyncMock) as mock_acomp,
+ patch("headroom.backends.litellm._fetch_bedrock_inference_profiles", return_value={}),
+ ):
+ mock_acomp.return_value = self._mock_stream_with_final_usage(
+ cache_read=4000, cache_write=500, prompt_tokens=5000
+ )()
+ backend = LiteLLMBackend(provider="bedrock", region="us-east-1")
+
+ events = [
+ e
+ async for e in backend.stream_message(
+ {"model": "test", "messages": [{"role": "user", "content": "hi"}]}, {}
+ )
+ ]
+
+ final_usage = next(e.data["usage"] for e in events if e.event_type == "message_delta")
+ # 5000 inclusive - 4000 read - 500 write = 500 genuinely-uncached.
+ assert final_usage["input_tokens"] == 500
+ assert final_usage["cache_read_input_tokens"] == 4000
+ assert final_usage["cache_creation_input_tokens"] == 500
+ # The disjoint-bucket invariant: the three sum back to prompt_tokens.
+ assert (
+ final_usage["input_tokens"]
+ + final_usage["cache_read_input_tokens"]
+ + final_usage["cache_creation_input_tokens"]
+ == 5000
+ )
+
+ @pytest.mark.asyncio
+ async def test_output_tokens_uses_real_completion_tokens_not_delta_count(self):
+ """output_tokens must be the provider's completion_tokens, not the SSE
+ delta count.
+
+ The streaming loop increments output_tokens once per
+ content_block_delta, which is a chunk count and undercounts the true
+ token total several-fold. When the trailing usage chunk carries a real
+ completion_tokens (stream_options.include_usage), report that instead,
+ matching the non-streaming path. Here the stream emits a single content
+ delta but the usage chunk reports 137 output tokens.
+ """
+ with (
+ patch("headroom.backends.litellm.acompletion", new_callable=AsyncMock) as mock_acomp,
+ patch("headroom.backends.litellm._fetch_bedrock_inference_profiles", return_value={}),
+ ):
+ mock_acomp.return_value = self._mock_stream_with_final_usage(
+ prompt_tokens=200, completion_tokens=137
+ )()
+ backend = LiteLLMBackend(provider="bedrock", region="us-east-1")
+
+ events = [
+ e
+ async for e in backend.stream_message(
+ {"model": "test", "messages": [{"role": "user", "content": "hi"}]}, {}
+ )
+ ]
+
+ final_usage = next(e.data["usage"] for e in events if e.event_type == "message_delta")
+ # One content delta streamed, but the real count is 137.
+ assert final_usage["output_tokens"] == 137
+
+ @pytest.mark.asyncio
+ async def test_output_tokens_falls_back_to_delta_count_without_usage_chunk(self):
+ """When no usage chunk arrives, output_tokens falls back to the delta
+ count so a value is still reported."""
+
+ async def mock_stream():
+ for text in ("a", "b", "c"):
+ chunk = MagicMock()
+ chunk.usage = None
+ chunk.choices = [
+ MagicMock(delta=MagicMock(content=text, tool_calls=None), finish_reason=None)
+ ]
+ yield chunk
+
+ with (
+ patch("headroom.backends.litellm.acompletion", new_callable=AsyncMock) as mock_acomp,
+ patch("headroom.backends.litellm._fetch_bedrock_inference_profiles", return_value={}),
+ ):
+ mock_acomp.return_value = mock_stream()
+ backend = LiteLLMBackend(provider="openrouter")
+
+ events = [
+ e
+ async for e in backend.stream_message(
+ {"model": "test", "messages": [{"role": "user", "content": "hi"}]}, {}
+ )
+ ]
+
+ final_usage = next(e.data["usage"] for e in events if e.event_type == "message_delta")
+ # Three content deltas, no usage chunk -> fall back to the count of 3.
+ assert final_usage["output_tokens"] == 3
@pytest.mark.asyncio
async def test_no_extra_message_start_when_usage_never_reported(self):