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): isolate tool call classification (#1937)
JD Davisfd5b9e75ad69
diff --git a/headroom/ccr/__init__.py b/headroom/ccr/__init__.pyindex 7b3ebf592..bb3054b39 100644--- a/headroom/ccr/__init__.py+++ b/headroom/ccr/__init__.py@@ -50,6 +50,12 @@ from .response_handler import (StreamingCCRBuffer,StreamingCCRHandler,)+from .tool_calls import (+ extract_tool_calls,+ has_ccr_tool_calls,+ parse_ccr_tool_calls,+ tool_call_id_for_provider,+)from .tool_injection import (CCR_TOOL_NAME,CCRToolInjector,@@ -82,6 +88,10 @@ __all__ = ["ResponseHandlerConfig","StreamingCCRBuffer","StreamingCCRHandler",+ "extract_tool_calls",+ "has_ccr_tool_calls",+ "parse_ccr_tool_calls",+ "tool_call_id_for_provider",# Context tracking"CompressedContext","ContextTracker",diff --git a/headroom/ccr/response_handler.py b/headroom/ccr/response_handler.pyindex 12af7f38a..80bf60998 100644--- a/headroom/ccr/response_handler.py+++ b/headroom/ccr/response_handler.py@@ -20,19 +20,17 @@ from dataclasses import dataclass, fieldfrom typing import Anyfrom ..cache.compression_store import format_retrieval_miss_detail, get_compression_store-from .tool_injection import CCR_TOOL_NAME, parse_tool_call+from .tool_calls import (+ CCRToolCall,+ extract_tool_calls,+ has_ccr_tool_calls,+ parse_ccr_tool_calls,+)+from .tool_injection import CCR_TOOL_NAMElogger = logging.getLogger(__name__)-@dataclass-class CCRToolCall:- """Represents a detected CCR tool call."""-- tool_call_id: str- hash_key: str--@dataclassclass CCRToolResult:"""Result of handling a CCR tool call."""@@ -110,13 +108,7 @@ class CCRResponseHandler:Returns:True if response contains headroom_retrieve tool calls."""- tool_calls = self._extract_tool_calls(response, provider)- return any(- tc.get("name") == CCR_TOOL_NAME- or tc.get("function", {}).get("name") == CCR_TOOL_NAME- or tc.get("functionCall", {}).get("name") == CCR_TOOL_NAME # Google format- for tc in tool_calls- )+ return has_ccr_tool_calls(response, provider)def _extract_tool_calls(self,@@ -124,42 +116,10 @@ class CCRResponseHandler:provider: str,) -> list[dict[str, Any]]:"""Extract tool calls from response based on provider format."""- if provider == "anthropic":- # Anthropic format: content blocks with type=tool_use- content = response.get("content", [])- if isinstance(content, list):- return [block for block in content if block.get("type") == "tool_use"]- return []-- elif provider == "openai":- # OpenAI format: message.tool_calls array- message = response.get("choices", [{}])[0].get("message", {})- tool_calls = message.get("tool_calls", [])- return list(tool_calls) if tool_calls else []-- elif provider == "google":- # Google/Gemini format: candidates[0].content.parts contains functionCall objects- # Each part with a functionCall has: {"functionCall": {"name": "...", "args": {...}}}- candidates = response.get("candidates", [])- if not candidates:- return []- parts = candidates[0].get("content", {}).get("parts", [])- return [part for part in parts if "functionCall" in part]-- elif provider == "openai_responses":- # OpenAI Responses API format: top-level `output[]` array with- # flat `function_call` items (no nested "function" object, no- # `choices[].message.tool_calls` wrapper like chat completions).- output = response.get("output", [])- if isinstance(output, list):- return [- item- for item in output- if isinstance(item, dict) and item.get("type") == "function_call"- ]- return []-- return []+ if provider == "openai" and response.get("choices") == []:+ # Preserve legacy private-method behavior for existing tests/callers.+ raise IndexError("list index out of range")+ return extract_tool_calls(response, provider)def _parse_ccr_tool_calls(self,@@ -171,39 +131,7 @@ class CCRResponseHandler:Returns:Tuple of (ccr_tool_calls, other_tool_calls)"""- all_tool_calls = self._extract_tool_calls(response, provider)-- ccr_calls = []- other_calls = []-- for tc in all_tool_calls:- hash_key = parse_tool_call(tc, provider)-- if hash_key is not None:- # This is a CCR tool call - extract tool_call_id based on provider- if provider == "google":- # Google uses function name as identifier for matching responses- # The functionResponse.name must match the functionCall.name- tool_call_id = tc.get("functionCall", {}).get("name", CCR_TOOL_NAME)- elif provider == "openai_responses":- # Responses API function_call items key off `call_id`,- # which is what the matching `function_call_output` item- # must echo back (its own `id` is a separate item id).- tool_call_id = tc.get("call_id", tc.get("id", ""))- else:- # Anthropic and OpenAI use explicit IDs- tool_call_id = tc.get("id", "")- ccr_calls.append(- CCRToolCall(- tool_call_id=tool_call_id,- hash_key=hash_key,- )- )- else:- # Not a CCR tool call- other_calls.append(tc)-- return ccr_calls, other_calls+ return parse_ccr_tool_calls(response, provider)def _execute_retrieval(self, ccr_call: CCRToolCall) -> CCRToolResult:"""Execute a CCR retrieval.diff --git a/headroom/ccr/tool_calls.py b/headroom/ccr/tool_calls.pynew file mode 100644index 000000000..16fa18878--- /dev/null+++ b/headroom/ccr/tool_calls.py@@ -0,0 +1,121 @@+"""Provider-shaped CCR tool-call extraction and classification."""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any++from .tool_injection import CCR_TOOL_NAME, parse_tool_call+++@dataclass+class CCRToolCall:+ """Represents a detected CCR retrieval tool call."""++ tool_call_id: str+ hash_key: str+++def extract_tool_calls(response: dict[str, Any], provider: str) -> list[dict[str, Any]]:+ """Extract provider-native tool-call objects from a response payload."""+ if provider == "anthropic":+ content = response.get("content", [])+ if isinstance(content, list):+ return [+ block+ for block in content+ if isinstance(block, dict) and block.get("type") == "tool_use"+ ]+ return []++ if provider == "openai":+ choices = response.get("choices", [])+ if not isinstance(choices, list) or not choices:+ return []+ first_choice = choices[0]+ if not isinstance(first_choice, dict):+ return []+ message = first_choice.get("message", {})+ if not isinstance(message, dict):+ return []+ tool_calls = message.get("tool_calls", [])+ return list(tool_calls) if isinstance(tool_calls, list) else []++ if provider == "google":+ candidates = response.get("candidates", [])+ if not isinstance(candidates, list) or not candidates:+ return []+ first_candidate = candidates[0]+ if not isinstance(first_candidate, dict):+ return []+ content = first_candidate.get("content", {})+ if not isinstance(content, dict):+ return []+ parts = content.get("parts", [])+ if not isinstance(parts, list):+ return []+ return [part for part in parts if isinstance(part, dict) and "functionCall" in part]++ if provider == "openai_responses":+ output = response.get("output", [])+ if isinstance(output, list):+ return [+ item+ for item in output+ if isinstance(item, dict) and item.get("type") == "function_call"+ ]+ return []++ return []+++def is_ccr_tool_call(tool_call: dict[str, Any]) -> bool:+ """Return true when a provider-native tool call names the CCR retrieval tool."""+ return (+ tool_call.get("name") == CCR_TOOL_NAME+ or tool_call.get("function", {}).get("name") == CCR_TOOL_NAME+ or tool_call.get("functionCall", {}).get("name") == CCR_TOOL_NAME+ )+++def has_ccr_tool_calls(response: dict[str, Any], provider: str) -> bool:+ """Return true when ``response`` contains at least one CCR tool call."""+ return any(is_ccr_tool_call(tool_call) for tool_call in extract_tool_calls(response, provider))+++def tool_call_id_for_provider(tool_call: dict[str, Any], provider: str) -> str:+ """Return the provider-specific identifier used by the matching tool result."""+ if provider == "google":+ function_call = tool_call.get("functionCall", {})+ if isinstance(function_call, dict):+ name = function_call.get("name", CCR_TOOL_NAME)+ return str(name)+ return CCR_TOOL_NAME+ if provider == "openai_responses":+ call_id = tool_call.get("call_id", tool_call.get("id", ""))+ return str(call_id)+ return str(tool_call.get("id", ""))+++def parse_ccr_tool_calls(+ response: dict[str, Any],+ provider: str,+) -> tuple[list[CCRToolCall], list[dict[str, Any]]]:+ """Split provider-native tool calls into CCR retrievals and other tools."""+ ccr_calls: list[CCRToolCall] = []+ other_calls: list[dict[str, Any]] = []++ for tool_call in extract_tool_calls(response, provider):+ hash_key = parse_tool_call(tool_call, provider)+ if hash_key is None:+ other_calls.append(tool_call)+ continue++ ccr_calls.append(+ CCRToolCall(+ tool_call_id=tool_call_id_for_provider(tool_call, provider),+ hash_key=hash_key,+ )+ )++ return ccr_calls, other_callsdiff --git a/tests/test_ccr_tool_calls.py b/tests/test_ccr_tool_calls.pynew file mode 100644index 000000000..b70b16320--- /dev/null+++ b/tests/test_ccr_tool_calls.py@@ -0,0 +1,86 @@+from __future__ import annotations++from headroom.ccr.tool_calls import (+ CCRToolCall,+ extract_tool_calls,+ has_ccr_tool_calls,+ parse_ccr_tool_calls,+ tool_call_id_for_provider,+)+from headroom.ccr.tool_injection import CCR_TOOL_NAME++HASH = "abc123def456abc123def456"+++def test_extract_tool_calls_handles_provider_shapes() -> None:+ anthropic = {"content": [{"type": "tool_use", "id": "t1", "name": CCR_TOOL_NAME}]}+ openai = {+ "choices": [+ {+ "message": {+ "tool_calls": [+ {"id": "c1", "function": {"name": CCR_TOOL_NAME, "arguments": "{}"}}+ ]+ }+ }+ ]+ }+ google = {+ "candidates": [+ {"content": {"parts": [{"functionCall": {"name": CCR_TOOL_NAME, "args": {}}}]}}+ ]+ }+ responses = {"output": [{"type": "function_call", "name": CCR_TOOL_NAME}]}++ assert len(extract_tool_calls(anthropic, "anthropic")) == 1+ assert len(extract_tool_calls(openai, "openai")) == 1+ assert len(extract_tool_calls(google, "google")) == 1+ assert len(extract_tool_calls(responses, "openai_responses")) == 1+++def test_extract_tool_calls_rejects_invalid_shapes() -> None:+ assert extract_tool_calls({"content": "not-a-list"}, "anthropic") == []+ assert extract_tool_calls({"choices": []}, "openai") == []+ assert extract_tool_calls({"choices": ["bad"]}, "openai") == []+ assert extract_tool_calls({"candidates": [{"content": {"parts": "bad"}}]}, "google") == []+ assert extract_tool_calls({"output": "bad"}, "openai_responses") == []+ assert extract_tool_calls({}, "unknown") == []+++def test_has_ccr_tool_calls_uses_provider_native_names() -> None:+ assert has_ccr_tool_calls(+ {"content": [{"type": "tool_use", "name": CCR_TOOL_NAME, "input": {"hash": HASH}}]},+ "anthropic",+ )+ assert not has_ccr_tool_calls(+ {"content": [{"type": "tool_use", "name": "read_file", "input": {"hash": HASH}}]},+ "anthropic",+ )+++def test_parse_ccr_tool_calls_splits_retrievals_from_other_tools() -> None:+ response = {+ "content": [+ {"type": "tool_use", "id": "tool_1", "name": CCR_TOOL_NAME, "input": {"hash": HASH}},+ {"type": "tool_use", "id": "tool_2", "name": "read_file", "input": {"path": "a.py"}},+ ]+ }++ ccr_calls, other_calls = parse_ccr_tool_calls(response, "anthropic")++ assert ccr_calls == [CCRToolCall(tool_call_id="tool_1", hash_key=HASH)]+ assert other_calls == [+ {"type": "tool_use", "id": "tool_2", "name": "read_file", "input": {"path": "a.py"}}+ ]+++def test_tool_call_id_for_provider_models_matching_result_ids() -> None:+ assert (+ tool_call_id_for_provider({"functionCall": {"name": CCR_TOOL_NAME}}, "google")+ == CCR_TOOL_NAME+ )+ assert (+ tool_call_id_for_provider({"id": "item_1", "call_id": "call_1"}, "openai_responses")+ == "call_1"+ )+ assert tool_call_id_for_provider({"id": "tool_1"}, "anthropic") == "tool_1"