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
refactor(ccr): read the expansion query through extract_user_query (#2707)
nangsontaydcec845851d8
diff --git a/headroom/proxy/handlers/anthropic.py b/headroom/proxy/handlers/anthropic.pyindex 75c743155..e7ff84006 100644--- a/headroom/proxy/handlers/anthropic.py+++ b/headroom/proxy/handlers/anthropic.py@@ -2628,19 +2628,11 @@ class AnthropicHandlerMixin:and self.config.ccr_proactive_expansionand ccr_workspace_key):- # Extract user query from messages- user_query = ""- for msg in reversed(messages):- if msg.get("role") == "user":- content = msg.get("content", "")- if isinstance(content, str):- user_query = content- elif isinstance(content, list):- for block in content:- if isinstance(block, dict) and block.get("type") == "text":- user_query = block.get("text", "")- break- break+ # Relevance query for this turn. Same helper the compression+ # pipeline scores with, so both read the query the same way;+ # `latest_user_turn_only` keeps the previous behaviour of not+ # reaching back past the newest user turn.+ user_query = extract_user_query(messages, latest_user_turn_only=True)if user_query:recommendations = self.ccr_context_tracker.analyze_query(diff --git a/headroom/utils.py b/headroom/utils.pyindex 9ff9e0404..b6489f0ea 100644--- a/headroom/utils.py+++ b/headroom/utils.py@@ -49,12 +49,23 @@ def fast_hash(data: str | bytes, length: int = 16) -> str:return hashlib.md5(data).hexdigest()[:length] # nosec B324-def extract_user_query(messages: list[dict[str, Any]]) -> str:+def extract_user_query(+ messages: list[dict[str, Any]], *, latest_user_turn_only: bool = False+) -> str:"""Extract the most recent user question from messages.Used to pass context through the compression pipeline so transforms likeSmartCrusher can score items by relevance to the user's actual question,not just by statistical properties (position, anomaly, boundary).++ Args:+ messages: Conversation messages, oldest first.+ latest_user_turn_only: Stop at the newest user message instead of+ walking back through earlier ones when it yields no text. Callers+ that treat the query as "what this turn is about" want this: on a+ tool_result continuation turn the newest user message carries no+ text, and resurrecting an older turn's question would make them+ act on a stale intent."""for msg in reversed(messages):if msg.get("role") == "user":@@ -67,6 +78,8 @@ def extract_user_query(messages: list[dict[str, Any]]) -> str:text = str(block.get("text", "")).strip()if text:return text+ if latest_user_turn_only:+ return ""return ""diff --git a/tests/test_utils.py b/tests/test_utils.pyindex 84b79e8b5..be4a5a9b3 100644--- a/tests/test_utils.py+++ b/tests/test_utils.py@@ -46,6 +46,33 @@ def test_extract_user_query_and_message_hashes() -> None:assert utils.extract_user_query(messages) == "latest question"assert utils.extract_user_query([{"role": "assistant", "content": "skip"}]) == ""++def test_extract_user_query_latest_user_turn_only() -> None:+ """The flag stops at the newest user turn instead of resurrecting an older one."""+ # A tool_result continuation: the newest user turn carries no text at all.+ messages = [+ {"role": "user", "content": "the original question"},+ {"role": "assistant", "content": "calling a tool"},+ {"role": "user", "content": [{"type": "tool_result", "content": "output"}]},+ ]++ # Default walks back and finds the older turn's question.+ assert utils.extract_user_query(messages) == "the original question"+ # Scoped to this turn, there is no question to score against.+ assert utils.extract_user_query(messages, latest_user_turn_only=True) == ""+++def test_extract_user_query_latest_turn_only_agrees_on_normal_turns() -> None:+ """With text present on the newest user turn, the flag changes nothing."""+ messages = [+ {"role": "user", "content": "older question"},+ {"role": "assistant", "content": "answer"},+ {"role": "user", "content": [{"type": "text", "text": " newest question "}]},+ ]++ assert utils.extract_user_query(messages) == "newest question"+ assert utils.extract_user_query(messages, latest_user_turn_only=True) == "newest question"+hash_one = utils.compute_messages_hash(messages)hash_two = utils.compute_messages_hash(list(messages))assert hash_one == hash_two