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(proxy): let an explicit compress-user-messages off beat the profile (#3936)
gglucass822c886d7902
diff --git a/docs/content/docs/proxy.mdx b/docs/content/docs/proxy.mdxindex f29891899..b83fb3a0b 100644--- a/docs/content/docs/proxy.mdx+++ b/docs/content/docs/proxy.mdx@@ -231,7 +231,7 @@ Fine-grained control over what gets compressed and how hard. Most users pick a [| `--mode` / `HEADROOM_MODE` | `cache` | `cache` compresses only the newest delta (prefix-cache safe); `token` maximizes removal. || `--target-ratio` / `HEADROOM_TARGET_RATIO` | unset | Keep-ratio for ML text compression; lower = more aggressive (e.g. `0.10`). || `HEADROOM_MIN_TOKENS` | `500` | Minimum block size before a tool output is compressed. |-| `HEADROOM_COMPRESS_USER_MESSAGES` | `false` | Compress content inside user-role messages (tool results live there). The `coding` profile turns this on. No `--compress-user-messages` flag on `headroom proxy`; the direct module entry point (`python -m headroom.proxy.server`) does accept one. |+| `HEADROOM_COMPRESS_USER_MESSAGES` | profile | Compress text inside user-role messages. The `coding` profile turns this on; set `0` to keep user text verbatim under it. Anthropic `tool_result` blocks compress either way. No `--compress-user-messages` flag on `headroom proxy`; the direct module entry point (`python -m headroom.proxy.server`) does accept one. || `HEADROOM_COMPRESS_SYSTEM_MESSAGES` | unset | Compress system prompts. Off by default to keep the hottest cache prefix stable. || `HEADROOM_PROTECT_RECENT` | profile | Never compress the N most recent turns. || `--protect-tool-results` / `HEADROOM_PROTECT_TOOL_RESULTS` | empty | Comma-separated tool names whose output is never lossy-compressed. |diff --git a/headroom/agent_savings.py b/headroom/agent_savings.pyindex a5b0f92cb..0c9271407 100644--- a/headroom/agent_savings.py+++ b/headroom/agent_savings.py@@ -336,8 +336,9 @@ def proxy_pipeline_kwargs(config: object) -> dict[str, object]:if profile.min_chars_for_block is not None:kwargs["min_chars_for_block_compression"] = profile.min_chars_for_block- if getattr(config, "compress_user_messages", False):- kwargs["compress_user_messages"] = True+ compress_user_messages = getattr(config, "compress_user_messages", None)+ if compress_user_messages is not None:+ kwargs["compress_user_messages"] = bool(compress_user_messages)compress_system_messages = getattr(config, "compress_system_messages", None)if compress_system_messages is not None:diff --git a/headroom/cli/proxy.py b/headroom/cli/proxy.pyindex 57dd8b390..2045f45da 100644--- a/headroom/cli/proxy.py+++ b/headroom/cli/proxy.py@@ -1147,6 +1147,7 @@ def proxy(# Import here to avoid slow startupfrom headroom.proxy.server import (ProxyConfig,+ _get_env_optional_bool,_parse_csv_tools,_parse_exclude_tools,_parse_tool_profiles,@@ -1346,7 +1347,8 @@ def proxy(rate_limit_enabled=not no_rate_limit,rate_limit_requests_per_minute=rpm if rpm is not None else 60,rate_limit_tokens_per_minute=tpm,- compress_user_messages=_get_env_bool("HEADROOM_COMPRESS_USER_MESSAGES", False),+ # Same parse as the server entry points: empty means unset (profile).+ compress_user_messages=_get_env_optional_bool("HEADROOM_COMPRESS_USER_MESSAGES"),periodic_malloc_trim_enabled=_get_env_bool("HEADROOM_MALLOC_TRIM", default_periodic_malloc_trim()),diff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.pyindex d14a283fe..4dbee1e0a 100644--- a/headroom/proxy/handlers/openai.py+++ b/headroom/proxy/handlers/openai.py@@ -2166,6 +2166,9 @@ class OpenAIHandlerMixin:unit_target_ratio = profile_kwargs.get("target_ratio")if unit_target_ratio is not None:unit_target_ratio = float(unit_target_ratio)+ # Earlier user turns follow the same compress_user_messages resolution+ # as the message pipeline (profile default, or an explicit override).+ compress_user_units = profile_kwargs.get("compress_user_messages") is not Falsetry:tokenizer = self.openai_provider.get_token_counter(model)@@ -2636,7 +2639,7 @@ class OpenAIHandlerMixin:metadata: dict[str, str] = {}if role == "assistant":metadata["compress_assistant"] = "true"- if role == "user" and item_idx != last_user_item_idx:+ if role == "user" and item_idx != last_user_item_idx and compress_user_units:metadata["compress_user"] = "true"min_bytes = (self.OPENAI_RESPONSES_MESSAGE_ROUTER_MIN_BYTESdiff --git a/headroom/proxy/models.py b/headroom/proxy/models.pyindex add92f0e2..87ec9663c 100644--- a/headroom/proxy/models.py+++ b/headroom/proxy/models.py@@ -283,8 +283,10 @@ class ProxyConfig:# prefix-cache zone. Enable for OpenAI/Azure chat workloads where the bulk# of input lives in user messages (pasted code/text, RAG context) and the# router would otherwise have nothing eligible to compress.- # CLI: --compress-user-messages; env: HEADROOM_COMPRESS_USER_MESSAGES=1.- compress_user_messages: bool = False+ # None follows the savings profile (`coding` turns it on); an explicit+ # True/False overrides the profile either way.+ # CLI: --compress-user-messages; env: HEADROOM_COMPRESS_USER_MESSAGES=1/0.+ compress_user_messages: bool | None = None# Named savings policy shared across Claude/Codex/Cursor proxy handlers.# CLI/env: HEADROOM_SAVINGS_PROFILE=agent-90.savings_profile: str | None = Nonediff --git a/headroom/proxy/server.py b/headroom/proxy/server.pyindex ce8ccfd91..6324e5dfa 100644--- a/headroom/proxy/server.py+++ b/headroom/proxy/server.py@@ -6104,6 +6104,7 @@ def _proxy_config_from_env() -> ProxyConfig:# posture (compress_user, protect_recent, min_tokens). HEADROOM_SAVINGS_PROFILE# overrides.savings_profile=os.environ.get("HEADROOM_SAVINGS_PROFILE") or "coding",+ compress_user_messages=_get_env_optional_bool("HEADROOM_COMPRESS_USER_MESSAGES"),read_maturation=rollout.is_enabled("read_maturation"),read_maturation_quiesce_turns=_get_env_int("HEADROOM_READ_MATURATION_QUIESCE_TURNS", 5),read_maturation_max_hold_turns=_get_env_int("HEADROOM_READ_MATURATION_MAX_HOLD_TURNS", 25),@@ -6895,8 +6896,11 @@ if __name__ == "__main__":if protect_tool_resultselse frozenset(),mode=normalize_proxy_mode(_get_env_str("HEADROOM_MODE", PROXY_MODE_CACHE)),- compress_user_messages=args.compress_user_messages- or _get_env_bool("HEADROOM_COMPRESS_USER_MESSAGES", False),+ compress_user_messages=(+ True+ if args.compress_user_messages+ else _get_env_optional_bool("HEADROOM_COMPRESS_USER_MESSAGES")+ ),savings_profile=os.environ.get("HEADROOM_SAVINGS_PROFILE") or "coding",# Default 0.4 keep-ratio so the Kompress text (prose/code) path compresses# meaningfully out of the box; HEADROOM_TARGET_RATIO overrides.diff --git a/tests/test_agent_savings.py b/tests/test_agent_savings.pyindex 5adcd2def..e9dd76eb8 100644--- a/tests/test_agent_savings.py+++ b/tests/test_agent_savings.py@@ -500,6 +500,17 @@ def test_proxy_explicit_config_overrides_agent_90_profile() -> None:assert kwargs["min_tokens_to_compress"] == 300+def test_proxy_explicit_compress_user_messages_off_overrides_coding_profile() -> None:+ # coding turns user-message compression on; an explicit off+ # (HEADROOM_COMPRESS_USER_MESSAGES=0) must win like every other override,+ # and leaving it unset must keep the profile default.+ explicit_off = ProxyConfig(savings_profile="coding", compress_user_messages=False)+ unset = ProxyConfig(savings_profile="coding")++ assert proxy_pipeline_kwargs(explicit_off)["compress_user_messages"] is False+ assert proxy_pipeline_kwargs(unset)["compress_user_messages"] is True++def test_agent_90_router_uses_ccr_sampling_not_lossless_table() -> None:router = ContentRouter(ContentRouterConfig(diff --git a/tests/test_cli_proxy_env.py b/tests/test_cli_proxy_env.pyindex 5a7d74538..0c611cc05 100644--- a/tests/test_cli_proxy_env.py+++ b/tests/test_cli_proxy_env.py@@ -291,6 +291,31 @@ class TestCLIProxyEnvVars:assert result.exit_code == 0, result.outputassert captured_config["config"].min_tokens_to_crush == 120+ @pytest.mark.parametrize(+ ("env", "expected"),+ [+ ({"HEADROOM_COMPRESS_USER_MESSAGES": "0"}, False),+ ({"HEADROOM_COMPRESS_USER_MESSAGES": ""}, True),+ ({}, True),+ ],+ )+ def test_compress_user_messages_env_off_overrides_profile(self, runner, env, expected):+ """HEADROOM_COMPRESS_USER_MESSAGES=0 must turn off the coding profile's+ user-message compression; unset or empty keeps the profile default (on)."""+ from headroom.agent_savings import proxy_pipeline_kwargs++ captured_config = {}++ def mock_run_server(config, **kwargs):+ captured_config["config"] = config++ with patch("headroom.proxy.server.run_server", mock_run_server):+ result = runner.invoke(main, ["proxy"], env=env, catch_exceptions=False)++ assert result.exit_code == 0, result.output+ kwargs = proxy_pipeline_kwargs(captured_config["config"])+ assert kwargs["compress_user_messages"] is expected+def test_headroom_min_tokens_zero_is_preserved(self, runner):"""HEADROOM_MIN_TOKENS=0 is a legitimate value ("crush everything") andmust not be discarded by an `or 500` fallback (regression)."""@@ -778,6 +803,20 @@ class TestCLIProxyEnvVars:assert captured["kwargs"].get("print_banner") is False[email protected](("value", "expected"), [("0", False), ("", True), (None, True)])+def test_proxy_config_from_env_compress_user_messages(monkeypatch, value, expected):+ """The uvicorn factory and `python -m headroom.proxy.server` read+ HEADROOM_COMPRESS_USER_MESSAGES the same way `headroom proxy` does."""+ from headroom.agent_savings import proxy_pipeline_kwargs+ from headroom.proxy.server import _proxy_config_from_env++ if value is not None:+ monkeypatch.setenv("HEADROOM_COMPRESS_USER_MESSAGES", value)++ kwargs = proxy_pipeline_kwargs(_proxy_config_from_env())+ assert kwargs["compress_user_messages"] is expected++class TestCLIProxyBackend:"""Test that litellm-* backends are accepted by the CLI."""diff --git a/tests/test_openai_responses_compression_units.py b/tests/test_openai_responses_compression_units.pyindex 9828153d6..3037d97cc 100644--- a/tests/test_openai_responses_compression_units.py+++ b/tests/test_openai_responses_compression_units.py@@ -1415,3 +1415,60 @@ def test_openai_responses_adapter_compresses_historical_messages_not_current_useassert new_payload["input"][2]["content"][0]["text"] == current_textassert units_by_category == {"applied": 2}assert any(t.startswith("router:openai:responses:message:") for t in transforms)+++ ("compress_user_messages", "expected_user_text"),+ [(False, None), (None, "compressed history")],+)+def test_openai_responses_adapter_historical_user_follows_compress_user_messages(+ compress_user_messages, expected_user_text+):+ # An explicit off (HEADROOM_COMPRESS_USER_MESSAGES=0) keeps earlier user+ # turns verbatim on Responses too; unset keeps the coding profile's default.+ from headroom.proxy.models import ProxyConfig++ router = ContentRouter()++ def compress(self, content: str, **_kwargs) -> RouterCompressionResult:+ return RouterCompressionResult(+ compressed="compressed history",+ original=content,+ strategy_used=CompressionStrategy.KOMPRESS,+ )++ router.compress = MethodType(compress, router)+ handler = _handler_with_router(router)+ handler.config = ProxyConfig(+ savings_profile="coding", compress_user_messages=compress_user_messages+ )+ historical_text = " ".join(f"history{i}" for i in range(2000))+ tool_output = " ".join(f"line{i}" for i in range(2000))+ current_text = " ".join(f"current{i}" for i in range(2000))+ payload = {+ "model": "gpt-5",+ "input": [+ {+ "type": "message",+ "role": "user",+ "content": [{"type": "input_text", "text": historical_text}],+ },+ {"type": "function_call_output", "call_id": "c1", "output": tool_output},+ {+ "type": "message",+ "role": "user",+ "content": [{"type": "input_text", "text": current_text}],+ },+ ],+ }++ new_payload, modified, _saved, _transforms, _units, _chain, _attempted = (+ handler._compress_openai_responses_live_text_units_with_router(+ payload, model="gpt-5", request_id="req_user_flag"+ )+ )++ assert modified is True+ assert new_payload["input"][0]["content"][0]["text"] == (expected_user_text or historical_text)+ assert new_payload["input"][1]["output"] == "compressed history"+ assert new_payload["input"][2]["content"][0]["text"] == current_text