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: Handle Anthropic format tool_use/tool_result as atomic units
Prakersh Maheshwarif83f92a51b57
diff --git a/headroom/parser.py b/headroom/parser.pyindex 78e4185c2..a477ab8c1 100644--- a/headroom/parser.py+++ b/headroom/parser.py@@ -242,6 +242,10 @@ def find_tool_units(messages: list[dict[str, Any]]) -> list[tuple[int, list[int]A tool unit is atomic - if the assistant message is dropped, all itstool responses must also be dropped.+ Supports both OpenAI and Anthropic formats:+ - OpenAI: assistant.tool_calls[] + tool messages with tool_call_id+ - Anthropic: assistant.content[type=tool_use] + user.content[type=tool_result]+Args:messages: List of message dicts.@@ -253,24 +257,49 @@ def find_tool_units(messages: list[dict[str, Any]]) -> list[tuple[int, list[int]# Build map of tool_call_id -> message index for tool responsestool_response_map: dict[str, int] = {}for i, msg in enumerate(messages):+ # OpenAI format: role="tool" with tool_call_idif msg.get("role") == "tool":tc_id = msg.get("tool_call_id")if tc_id:tool_response_map[tc_id] = i- # Find assistant messages with tool_calls+ # Anthropic format: role="user" with content blocks containing tool_result+ if msg.get("role") == "user":+ content = msg.get("content")+ if isinstance(content, list):+ for block in content:+ if isinstance(block, dict) and block.get("type") == "tool_result":+ tc_id = block.get("tool_use_id")+ if tc_id:+ tool_response_map[tc_id] = i++ # Find assistant messages with tool callsfor i, msg in enumerate(messages):- if msg.get("role") == "assistant" and msg.get("tool_calls"):- tool_calls = msg["tool_calls"]- response_indices: list[int] = []+ if msg.get("role") != "assistant":+ continue++ response_indices: list[int] = []+ # OpenAI format: tool_calls array+ tool_calls = msg.get("tool_calls")+ if tool_calls:for tc in tool_calls:tc_id = tc.get("id")if tc_id and tc_id in tool_response_map:response_indices.append(tool_response_map[tc_id])- if response_indices:- units.append((i, sorted(response_indices)))+ # Anthropic format: content blocks with type=tool_use+ content = msg.get("content")+ if isinstance(content, list):+ for block in content:+ if isinstance(block, dict) and block.get("type") == "tool_use":+ tc_id = block.get("id")+ if tc_id and tc_id in tool_response_map:+ response_indices.append(tool_response_map[tc_id])++ if response_indices:+ # Use set to deduplicate in case same message has both formats+ units.append((i, sorted(set(response_indices))))return unitsdiff --git a/headroom/transforms/rolling_window.py b/headroom/transforms/rolling_window.pyindex 9452cc72e..7bc6333b1 100644--- a/headroom/transforms/rolling_window.py+++ b/headroom/transforms/rolling_window.py@@ -225,13 +225,44 @@ class RollingWindow(Transform):# Also protect any tool responses that belong to protected assistant messagesfor i in list(protected):msg = messages[i]- if msg.get("role") == "assistant" and msg.get("tool_calls"):+ if msg.get("role") == "assistant":+ tool_call_ids: set[str] = set()++ # OpenAI format: tool_calls array+ if msg.get("tool_calls"):+ tool_call_ids.update(+ tc.get("id") for tc in msg.get("tool_calls", []) if tc.get("id")+ )++ # Anthropic format: content blocks with type=tool_use+ content = msg.get("content")+ if isinstance(content, list):+ for block in content:+ if isinstance(block, dict) and block.get("type") == "tool_use":+ tc_id = block.get("id")+ if tc_id:+ tool_call_ids.add(tc_id)+# Find and protect corresponding tool responses- tool_call_ids = {tc.get("id") for tc in msg.get("tool_calls", [])}- for j, other_msg in enumerate(messages):- if other_msg.get("role") == "tool":- if other_msg.get("tool_call_id") in tool_call_ids:- protected.add(j)+ if tool_call_ids:+ for j, other_msg in enumerate(messages):+ # OpenAI format: role="tool"+ if other_msg.get("role") == "tool":+ if other_msg.get("tool_call_id") in tool_call_ids:+ protected.add(j)++ # Anthropic format: role="user" with tool_result blocks+ if other_msg.get("role") == "user":+ other_content = other_msg.get("content")+ if isinstance(other_content, list):+ for block in other_content:+ if (+ isinstance(block, dict)+ and block.get("type") == "tool_result"+ and block.get("tool_use_id") in tool_call_ids+ ):+ protected.add(j)+ breakreturn protecteddiff --git a/tests/test_parser.py b/tests/test_parser.pyindex 28686ee67..e1753dcde 100644--- a/tests/test_parser.py+++ b/tests/test_parser.py@@ -483,6 +483,112 @@ class TestFindToolUnits:_, response_indices = units[0]assert response_indices == sorted(response_indices)+ def test_anthropic_format_tool_use_and_result(self):+ """Finds Anthropic format tool_use/tool_result pairs in content blocks."""+ messages = [+ {"role": "system", "content": "You are helpful."},+ {"role": "user", "content": "Take a screenshot"},+ {+ "role": "assistant",+ "content": [+ {"type": "text", "text": "Let me take a screenshot."},+ {+ "type": "tool_use",+ "id": "toolu_123",+ "name": "browser_screenshot",+ "input": {},+ },+ ],+ },+ {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "toolu_123",+ "content": "Screenshot taken successfully",+ }+ ],+ },+ {"role": "user", "content": "Thanks!"},+ ]+ units = find_tool_units(messages)+ assert len(units) == 1+ assistant_idx, response_indices = units[0]+ assert assistant_idx == 2+ assert response_indices == [3]++ def test_anthropic_format_multiple_tool_uses(self):+ """Finds multiple Anthropic format tool_use blocks from same assistant."""+ messages = [+ {"role": "user", "content": "Do two things"},+ {+ "role": "assistant",+ "content": [+ {"type": "tool_use", "id": "toolu_a", "name": "first", "input": {}},+ {"type": "tool_use", "id": "toolu_b", "name": "second", "input": {}},+ ],+ },+ {+ "role": "user",+ "content": [+ {"type": "tool_result", "tool_use_id": "toolu_a", "content": "first done"},+ {"type": "tool_result", "tool_use_id": "toolu_b", "content": "second done"},+ ],+ },+ ]+ units = find_tool_units(messages)+ assert len(units) == 1+ assistant_idx, response_indices = units[0]+ assert assistant_idx == 1+ assert response_indices == [2]++ def test_anthropic_format_orphaned_tool_result(self):+ """Anthropic tool_result without matching tool_use is not included."""+ messages = [+ {"role": "user", "content": "Hi"},+ {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "orphan_toolu",+ "content": "orphaned result",+ }+ ],+ },+ {"role": "assistant", "content": "Hello!"},+ ]+ units = find_tool_units(messages)+ assert units == []++ def test_mixed_openai_and_anthropic_formats(self):+ """Both OpenAI and Anthropic formats can coexist (edge case)."""+ messages = [+ {"role": "user", "content": "Do things"},+ # OpenAI format+ {+ "role": "assistant",+ "tool_calls": [{"id": "call_1", "function": {"name": "openai_tool", "arguments": "{}"}}],+ },+ {"role": "tool", "tool_call_id": "call_1", "content": "openai result"},+ # Anthropic format+ {+ "role": "assistant",+ "content": [{"type": "tool_use", "id": "toolu_2", "name": "anthropic_tool", "input": {}}],+ },+ {+ "role": "user",+ "content": [{"type": "tool_result", "tool_use_id": "toolu_2", "content": "anthropic result"}],+ },+ ]+ units = find_tool_units(messages)+ assert len(units) == 2+ # First unit: OpenAI format (assistant at 1, tool response at 2)+ assert units[0] == (1, [2])+ # Second unit: Anthropic format (assistant at 3, user with tool_result at 4)+ assert units[1] == (3, [4])+# --- TestGetMessageContentText ---