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
Pass user query context through proxy pipeline (9 call sites)
chopratejasbd350f92baf2
diff --git a/headroom/compress.py b/headroom/compress.pyindex f220c2dca..47a49ee01 100644--- a/headroom/compress.py+++ b/headroom/compress.py@@ -60,33 +60,9 @@ import loggingfrom dataclasses import dataclass, fieldfrom typing import Any-logger = logging.getLogger(__name__)---def _extract_user_query(messages: list[dict[str, Any]]) -> str:- """Extract the most recent user question from messages.+from .utils import extract_user_query as _extract_user_query- This context is passed through the pipeline so that transforms like- SmartCrusher can score items by relevance to the user's actual question,- not just by statistical properties (position, anomaly, boundary).-- Without this, RAG retriever output gets compressed incorrectly:- SmartCrusher keeps boundary items (first/last) and statistical anomalies,- which may be the LEAST relevant chunks.- """- for msg in reversed(messages):- if msg.get("role") == "user":- content = msg.get("content", "")- if isinstance(content, str) and content.strip():- return content.strip()- # Handle Anthropic list-of-content-blocks format- if isinstance(content, list):- for block in content:- if isinstance(block, dict) and block.get("type") == "text":- text = str(block.get("text", "")).strip()- if text:- return text- return ""+logger = logging.getLogger(__name__)# Lazy-initialized singleton pipelinediff --git a/headroom/proxy/server.py b/headroom/proxy/server.pyindex 56b0d4719..97e047a35 100644--- a/headroom/proxy/server.py+++ b/headroom/proxy/server.py@@ -106,6 +106,7 @@ from headroom.transforms import (TransformPipeline,is_tree_sitter_available,)+from headroom.utils import extract_user_query# Image compression (lazy-loaded to avoid heavy dependencies at startup)_image_compressor = None@@ -2412,6 +2413,7 @@ class HeadroomProxy:messages=working_messages,model=model,model_limit=context_limit,+ context=extract_user_query(working_messages),frozen_message_count=frozen_message_count,biases=biases,)@@ -2438,6 +2440,7 @@ class HeadroomProxy:messages=messages,model=model,model_limit=context_limit,+ context=extract_user_query(messages),frozen_message_count=frozen_message_count,biases=biases,)@@ -3251,6 +3254,7 @@ class HeadroomProxy:messages=messages,model=model,model_limit=context_limit,+ context=extract_user_query(messages),)optimized_messages = result.messages@@ -3703,6 +3707,7 @@ class HeadroomProxy:messages=messages,model=model,model_limit=context_limit,+ context=extract_user_query(messages),)optimized_messages = result.messages@@ -5183,6 +5188,7 @@ class HeadroomProxy:messages=working_messages,model=model,model_limit=context_limit,+ context=extract_user_query(working_messages),frozen_message_count=openai_frozen_count,biases=_hook_biases,)@@ -5207,6 +5213,7 @@ class HeadroomProxy:messages=messages,model=model,model_limit=context_limit,+ context=extract_user_query(messages),frozen_message_count=openai_frozen_count,biases=_hook_biases,)@@ -5950,6 +5957,7 @@ class HeadroomProxy:messages=messages,model=model,model_limit=context_limit,+ context=extract_user_query(messages),)compressed_messages = result.messages# Use pipeline's token counts for consistency with pipeline logs@@ -6435,6 +6443,7 @@ class HeadroomProxy:messages=messages,model=model,model_limit=context_limit,+ context=extract_user_query(messages),)if result.messages != messages:optimized_messages = result.messages@@ -6728,6 +6737,7 @@ class HeadroomProxy:messages=messages,model=model,model_limit=context_limit,+ context=extract_user_query(messages),)if result.messages != messages:optimized_messages = result.messagesdiff --git a/headroom/utils.py b/headroom/utils.pyindex b9d94f604..72cd95e0e 100644--- a/headroom/utils.py+++ b/headroom/utils.py@@ -43,6 +43,27 @@ def fast_hash(data: str | bytes, length: int = 16) -> str:return hashlib.md5(data).hexdigest()[:length]+def extract_user_query(messages: list[dict[str, Any]]) -> str:+ """Extract the most recent user question from messages.++ Used to pass context through the compression pipeline so transforms like+ SmartCrusher can score items by relevance to the user's actual question,+ not just by statistical properties (position, anomaly, boundary).+ """+ for msg in reversed(messages):+ if msg.get("role") == "user":+ content = msg.get("content", "")+ if isinstance(content, str) and content.strip():+ return content.strip()+ if isinstance(content, list):+ for block in content:+ if isinstance(block, dict) and block.get("type") == "text":+ text = str(block.get("text", "")).strip()+ if text:+ return text+ return ""++def compute_messages_hash(messages: list[dict[str, Any]]) -> str:"""Compute hash of messages list for deduplication."""# Serialize deterministically