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.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(backends/litellm): preserve tool_result cache_control, complete streaming cache stats (#2144)
Ingmar Krusch0ad7dc7c1ce3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 675b0f670..410fe2651 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## Unreleased### Fixed+- **backends/litellm:** preserve `cache_control` on `tool_result` blocks when converting Anthropic messages for the Bedrock Converse path, and complete streaming cache-stats surfacing in `stream_message`. Complements [#1390](https://github.com/headroomlabs-ai/headroom/pull/1390), which preserves `cache_control` on the system prompt and plain text blocks but explicitly leaves `tool_result` out of scope — in agent loops the moving cache breakpoint lands on the tail `tool_result` far more often than on the system prompt, so that gap left most of the caching benefit on the table. Separately, `stream_message` never requested `stream_options.include_usage`, so LiteLLM/Bedrock never returned a usage chunk over SSE and `cache_read_input_tokens`/`cache_creation_input_tokens` always reported 0 downstream even when the prompt cache was genuinely engaged; the terminal `message_delta` now carries the real cache values captured from the trailing usage chunk once the stream completes.- **shared_context:** `SharedContext.put` no longer evicts an unrelated entry when it merely updates a key that is already cached at capacity — same defect class fixed for `SemanticCache` in [#2094](https://github.com/headroomlabs-ai/headroom/pull/2094).- **compress:** stop mutating the caller's `CompressConfig`. `compress(config=my_cfg, protect_recent=0, target_ratio=0.2)` used to write those kwargs onto `my_cfg`, so a shared per-agent config was silently rewritten by every request that overrode a single option.- **paths:** reject `.`, `..`, and NUL as plugin names so `plugin_config_dir` / `plugin_workspace_dir` cannot resolve outside the `plugins/` sandbox. Previously `plugin_config_dir("..")` returned the entire config root and `plugin_workspace_dir("..")` returned the workspace root (savings ledger, memory DB, license cache, logs).diff --git a/headroom/backends/litellm.py b/headroom/backends/litellm.pyindex 134ae7e17..8954f2412 100644--- a/headroom/backends/litellm.py+++ b/headroom/backends/litellm.py@@ -669,13 +669,20 @@ class LiteLLMBackend(Backend):tr_content = "\n".join(b.get("text", "") for b in tr_content if b.get("type") == "text")- converted.append(- {- "role": "tool",- "tool_call_id": tr["tool_use_id"],- "content": str(tr_content),- }- )+ tool_msg: dict[str, Any] = {+ "role": "tool",+ "tool_call_id": tr["tool_use_id"],+ "content": str(tr_content),+ }+ # Claude Code's moving cache breakpoint usually lands on the+ # tail tool_result, not just the system prompt. Carry+ # cache_control through so LiteLLM's Bedrock Converse+ # transformation can inject a cachePoint here too (#1390+ # covers the system-prompt/text-block case; this is the+ # tool_result case, out of scope there).+ if "cache_control" in tr:+ tool_msg["cache_control"] = tr["cache_control"]+ converted.append(tool_msg)continue# tool_use blocks → OpenAI assistant message with tool_calls@@ -966,6 +973,13 @@ class LiteLLMBackend(Backend):},)+ # Request usage in the final streaming chunk so cache metrics+ # (cache_read_input_tokens / cache_creation_input_tokens) come back at+ # all. Without this, LiteLLM/Bedrock never emits a usage chunk over SSE+ # and the caller's cache stats always read 0, even when caching is+ # working server-side.+ kwargs["stream_options"] = {"include_usage": True}+# Stream content — blocks emitted dynamically based on responseresponse = await acompletion(**kwargs)output_tokens = 0@@ -973,8 +987,25 @@ class LiteLLMBackend(Backend):active_block_type: str | None = None # "text" or "tool_use"tool_block_map: dict[int, int] = {} # litellm tc.index → SSE block indexstop_reason = "end_turn"+ # Populated from the final usage chunk (stream_options.include_usage=True+ # above). The message_start emitted before this loop always carries+ # input_tokens=0 and no cache fields because LiteLLM/Bedrock only reports+ # usage on the trailing chunk. Carry the final cache stats on the terminal+ # message_delta instead of emitting a second protocol-invalid+ # message_start after content has already streamed.+ final_input_tokens = 0+ final_cache_read_tokens = 0+ final_cache_write_tokens = 0async for chunk in response:+ if hasattr(chunk, "usage") and chunk.usage:+ cu = chunk.usage+ final_input_tokens = int(getattr(cu, "prompt_tokens", 0) or 0)+ final_cache_read_tokens = int(getattr(cu, "cache_read_input_tokens", 0) or 0)+ final_cache_write_tokens = int(+ getattr(cu, "cache_creation_input_tokens", 0) or 0+ )+if not hasattr(chunk, "choices") or not chunk.choices:continue@@ -1080,13 +1111,21 @@ class LiteLLMBackend(Backend):data={"type": "content_block_stop", "index": current_block_index},)+ delta_usage: dict[str, Any] = {"output_tokens": output_tokens}+ if final_input_tokens or final_cache_read_tokens or final_cache_write_tokens:+ delta_usage["input_tokens"] = final_input_tokens+ if final_cache_read_tokens:+ delta_usage["cache_read_input_tokens"] = final_cache_read_tokens+ if final_cache_write_tokens:+ delta_usage["cache_creation_input_tokens"] = final_cache_write_tokens+# Emit message_delta with correct stop reasonyield StreamEvent(event_type="message_delta",data={"type": "message_delta","delta": {"stop_reason": stop_reason, "stop_sequence": None},- "usage": {"output_tokens": output_tokens},+ "usage": delta_usage,},)diff --git a/headroom/proxy/handlers/streaming.py b/headroom/proxy/handlers/streaming.pyindex 9da56dbb0..5162cdd88 100644--- a/headroom/proxy/handlers/streaming.py+++ b/headroom/proxy/handlers/streaming.py@@ -1716,6 +1716,16 @@ class StreamingMixin:usage = event.data.get("usage", {})if "output_tokens" in usage:stream_state["output_tokens"] = usage["output_tokens"]+ if "input_tokens" in usage:+ stream_state["input_tokens"] = usage["input_tokens"]+ if "cache_read_input_tokens" in usage:+ stream_state["cache_read_input_tokens"] = usage[+ "cache_read_input_tokens"+ ]+ if "cache_creation_input_tokens" in usage:+ stream_state["cache_creation_input_tokens"] = usage[+ "cache_creation_input_tokens"+ ]# Handle errorsif event.event_type == "error":diff --git a/tests/test_bedrock_tool_result_cache_and_streaming_stats.py b/tests/test_bedrock_tool_result_cache_and_streaming_stats.pynew file mode 100644index 000000000..f29e0ccc7--- /dev/null+++ b/tests/test_bedrock_tool_result_cache_and_streaming_stats.py@@ -0,0 +1,254 @@+"""Two Bedrock Converse gaps left after #1390 (system-prompt/text-block cache_control):++1. ``_convert_messages_for_litellm`` preserved ``cache_control`` on text blocks+ and the system prompt, but not on ``tool_result`` blocks. Claude Code's+ moving cache breakpoint lands on the tail ``tool_result`` far more often+ than on the system prompt or a plain text block, so this is the case that+ matters most in agent loops.++2. ``LiteLLMBackend.stream_message`` never requested+ ``stream_options.include_usage``, so LiteLLM/Bedrock never returned a usage+ chunk over SSE — cache_read/cache_write always reported 0 downstream even+ when the Bedrock prompt cache was genuinely engaged. The ``message_start``+ emitted before streaming begins is necessarily sent before any usage is+ known (hardcoded ``input_tokens: 0``, no cache fields); once the real+ values are captured from the trailing usage chunk, the terminal+ ``message_delta.usage`` carries them so the public Anthropic event order+ remains valid.+"""++from __future__ import annotations++from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from tests._dotenv import importorskip_no_env_leak++importorskip_no_env_leak("litellm")++from headroom.backends.litellm import LiteLLMBackend # noqa: E402+++def _backend(provider: str = "bedrock") -> LiteLLMBackend:+ with patch("headroom.backends.litellm._fetch_bedrock_inference_profiles", return_value={}):+ return LiteLLMBackend(provider=provider, region="us-east-1")+++class TestToolResultCacheControlPreserved:+ """tool_result blocks must carry cache_control onto the emitted tool message."""++ def test_tool_result_with_cache_control_preserved(self):+ backend = _backend()+ messages = [+ {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "toolu_01",+ "content": "big tool output",+ "cache_control": {"type": "ephemeral"},+ },+ ],+ },+ ]+ converted = backend._convert_messages_for_litellm(messages)+ assert len(converted) == 1+ assert converted[0]["role"] == "tool"+ assert converted[0]["cache_control"] == {"type": "ephemeral"}++ def test_tool_result_without_cache_control_unaffected(self):+ backend = _backend()+ messages = [+ {+ "role": "user",+ "content": [+ {"type": "tool_result", "tool_use_id": "toolu_02", "content": "no marker"},+ ],+ },+ ]+ converted = backend._convert_messages_for_litellm(messages)+ assert "cache_control" not in converted[0]++ def test_multiple_tool_results_only_marked_one_preserved(self):+ backend = _backend()+ messages = [+ {+ "role": "user",+ "content": [+ {"type": "tool_result", "tool_use_id": "toolu_a", "content": "Result A"},+ {+ "type": "tool_result",+ "tool_use_id": "toolu_b",+ "content": "Result B",+ "cache_control": {"type": "ephemeral"},+ },+ ],+ },+ ]+ converted = backend._convert_messages_for_litellm(messages)+ assert len(converted) == 2+ assert "cache_control" not in converted[0]+ assert converted[1]["cache_control"] == {"type": "ephemeral"}++ def test_tool_result_cache_control_not_forwarded_for_non_bedrock(self):+ """The conversion is provider-agnostic; other providers get the same+ block shape, and LiteLLM/that provider's own transformation is+ responsible for ignoring cache_control it doesn't understand."""+ backend = _backend(provider="openrouter")+ messages = [+ {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "toolu_03",+ "content": "output",+ "cache_control": {"type": "ephemeral"},+ },+ ],+ },+ ]+ converted = backend._convert_messages_for_litellm(messages)+ assert converted[0]["cache_control"] == {"type": "ephemeral"}+++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+ ):+ async def mock_stream():+ chunk1 = MagicMock()+ chunk1.usage = None+ chunk1.choices = [+ MagicMock(delta=MagicMock(content="hi", tool_calls=None), finish_reason=None)+ ]+ yield chunk1++ # Final chunk: content-less, usage-carrying (mirrors+ # stream_options.include_usage's trailing chunk shape).+ chunk2 = MagicMock()+ chunk2.choices = [+ MagicMock(delta=MagicMock(content=None, tool_calls=None), finish_reason="stop")+ ]+ chunk2.usage = MagicMock(+ prompt_tokens=prompt_tokens,+ cache_read_input_tokens=cache_read,+ cache_creation_input_tokens=cache_write,+ )+ yield chunk2++ return mock_stream++ @pytest.mark.asyncio+ async def test_stream_options_include_usage_requested(self):+ 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()()+ backend = LiteLLMBackend(provider="bedrock", region="us-east-1")++ events = [+ e+ async for e in backend.stream_message(+ {"model": "test", "messages": [{"role": "user", "content": "hi"}]}, {}+ )+ ]+ assert events++ call_kwargs = mock_acomp.call_args[1]+ assert call_kwargs["stream_options"] == {"include_usage": True}++ @pytest.mark.asyncio+ async def test_terminal_message_delta_carries_real_cache_stats(self):+ 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=1200, cache_write=300, prompt_tokens=1500+ )()+ backend = LiteLLMBackend(provider="bedrock", region="us-east-1")++ events = [+ e+ async for e in backend.stream_message(+ {"model": "test", "messages": [{"role": "user", "content": "hi"}]}, {}+ )+ ]++ message_starts = [e for e in events if e.event_type == "message_start"]+ assert len(message_starts) == 1, "stream should keep a single initial message_start"++ first_usage = message_starts[0].data["message"]["usage"]+ assert first_usage["input_tokens"] == 0+ assert "cache_read_input_tokens" not in first_usage++ 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["cache_read_input_tokens"] == 1200+ assert final_usage["cache_creation_input_tokens"] == 300++ @pytest.mark.asyncio+ async def test_no_extra_message_start_when_usage_never_reported(self):+ """Non-Bedrock LiteLLM providers (or any response that never carries a+ usage chunk) must not get a spurious trailing message_start."""++ async def mock_stream():+ chunk = MagicMock()+ chunk.usage = None+ chunk.choices = [+ MagicMock(delta=MagicMock(content="hi", tool_calls=None), finish_reason="stop")+ ]+ 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"}]}, {}+ )+ ]++ message_starts = [e for e in events if e.event_type == "message_start"]+ assert len(message_starts) == 1++ @pytest.mark.asyncio+ async def test_terminal_message_delta_omits_zero_cache_fields(self):+ """If only input_tokens came back (no caching engaged), the trailing+ message_delta should include input_tokens but no empty cache_* keys."""+ 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=0, cache_write=0, prompt_tokens=42+ )()+ backend = LiteLLMBackend(provider="bedrock", region="us-east-1")++ events = [+ e+ async for e in backend.stream_message(+ {"model": "test", "messages": [{"role": "user", "content": "hi"}]}, {}+ )+ ]++ message_starts = [e for e in events if e.event_type == "message_start"]+ assert len(message_starts) == 1+ message_deltas = [e for e in events if e.event_type == "message_delta"]+ usage = message_deltas[0].data["usage"]+ assert usage["input_tokens"] == 42+ assert "cache_read_input_tokens" not in usage+ assert "cache_creation_input_tokens" not in usage