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 mypy type checking errors in CCR batch modules
chopratejas80bfb1267b2f
diff --git a/headroom/ccr/batch_processor.py b/headroom/ccr/batch_processor.pyindex 584354805..ed8607991 100644--- a/headroom/ccr/batch_processor.py+++ b/headroom/ccr/batch_processor.py@@ -199,13 +199,14 @@ class BatchResultProcessor:def _get_custom_id(self, result: dict[str, Any], provider: str) -> str:"""Extract the custom ID from a result."""if provider == "anthropic":- return result.get("custom_id", "")+ return str(result.get("custom_id", ""))elif provider == "openai":- return result.get("custom_id", "")+ return str(result.get("custom_id", ""))elif provider == "google":# Google uses metadata.key- return result.get("metadata", {}).get("key", "")- return result.get("custom_id", result.get("id", ""))+ metadata = result.get("metadata", {})+ return str(metadata.get("key", "") if isinstance(metadata, dict) else "")+ return str(result.get("custom_id", result.get("id", "")))def _extract_response(self,@@ -213,16 +214,21 @@ class BatchResultProcessor:provider: str,) -> dict[str, Any] | None:"""Extract the actual response from a batch result."""+ response: Anyif provider == "anthropic":# Anthropic: result.result.message- return result.get("result", {}).get("message")+ inner = result.get("result", {})+ response = inner.get("message") if isinstance(inner, dict) else Noneelif provider == "openai":# OpenAI: response.body (the full chat completion)- return result.get("response", {}).get("body")+ inner = result.get("response", {})+ response = inner.get("body") if isinstance(inner, dict) else Noneelif provider == "google":# Google: response (the generateContent response)- return result.get("response")- return result.get("response")+ response = result.get("response")+ else:+ response = result.get("response")+ return response if isinstance(response, dict) else Noneasync def _process_single_result(self,@@ -345,7 +351,8 @@ class BatchResultProcessor:timeout=self.config.continuation_timeout,)response.raise_for_status()- return response.json()+ result: dict[str, Any] = response.json()+ return resultasync def _openai_continuation(self,@@ -377,7 +384,8 @@ class BatchResultProcessor:timeout=self.config.continuation_timeout,)response.raise_for_status()- return response.json()+ result: dict[str, Any] = response.json()+ return resultasync def _google_continuation(self,@@ -419,7 +427,8 @@ class BatchResultProcessor:timeout=self.config.continuation_timeout,)response.raise_for_status()- return response.json()+ result: dict[str, Any] = response.json()+ return resultdef _messages_to_google_contents(self,diff --git a/headroom/evals/batch_compression_eval.py b/headroom/evals/batch_compression_eval.pyindex 44082c690..a1df6ee52 100644--- a/headroom/evals/batch_compression_eval.py+++ b/headroom/evals/batch_compression_eval.py@@ -937,9 +937,9 @@ class TokenCounter:def __init__(self, model: str = "claude-sonnet-4-20250514"):self.model = model- self._tokenizer = None+ self._tokenizer: Any = None- def _get_tokenizer(self):+ def _get_tokenizer(self) -> Any:"""Lazy load tokenizer."""if self._tokenizer is None:try:@@ -956,7 +956,7 @@ class TokenCounter:tokenizer = self._get_tokenizer()if tokenizer:try:- return tokenizer.count_text(text)+ return int(tokenizer.count_text(text))except Exception:pass# Fallback: estimate ~4 chars per token@@ -1446,7 +1446,7 @@ def run_quick_batch_eval(# =============================================================================-def main():+def main() -> None:"""CLI entry point."""import argparse@@ -1487,26 +1487,26 @@ def main():args = parser.parse_args()if args.token_counting:- results = evaluate_token_counting_accuracy()- print(results.summary())+ token_results = evaluate_token_counting_accuracy()+ print(token_results.summary())if args.output:import jsonwith open(args.output, "w") as f:json.dump({- "model": results.model,- "test_cases": results.test_cases,- "exact_matches": results.exact_matches,- "avg_error_percent": results.avg_error_percent,- "max_error_percent": results.max_error_percent,- "results": results.results,+ "model": token_results.model,+ "test_cases": token_results.test_cases,+ "exact_matches": token_results.exact_matches,+ "avg_error_percent": token_results.avg_error_percent,+ "max_error_percent": token_results.max_error_percent,+ "results": token_results.results,},f,indent=2,)else:- results = run_batch_compression_eval(+ eval_results = run_batch_compression_eval(provider=args.provider,n_samples=args.samples,categories=args.categories,@@ -1517,7 +1517,7 @@ def main():import jsonwith open(args.output, "w") as f:- json.dump(results.to_dict(), f, indent=2)+ json.dump(eval_results.to_dict(), f, indent=2)print(f"\nResults saved to {args.output}")diff --git a/headroom/proxy/server.py b/headroom/proxy/server.pyindex 4e689a320..1f2756742 100644--- a/headroom/proxy/server.py+++ b/headroom/proxy/server.py@@ -1844,7 +1844,7 @@ class HeadroomProxy:body = await request.body()- response = await self.http_client.request(+ response = await self.http_client.request( # type: ignore[union-attr]method=request.method,url=url,headers=headers,@@ -1937,7 +1937,7 @@ class HeadroomProxy:headers = dict(request.headers.items())headers.pop("host", None)- response = await self.http_client.get(url, headers=headers)+ response = await self.http_client.get(url, headers=headers) # type: ignore[union-attr]if response.status_code != 200:# Error - pass through@@ -1987,7 +1987,7 @@ class HeadroomProxy:)# Process results with CCR handler- processor = BatchResultProcessor(self.http_client)+ processor = BatchResultProcessor(self.http_client) # type: ignore[arg-type]processed = await processor.process_results(batch_id, results, "anthropic")# Convert back to JSONL format@@ -2305,7 +2305,7 @@ class HeadroomProxy:else:body_content = json.dumps(body).encode()- response = await self.http_client.post(+ response = await self.http_client.post( # type: ignore[union-attr]url,headers=headers,content=body_content,@@ -2365,7 +2365,7 @@ class HeadroomProxy:body = await request.body()- response = await self.http_client.request(+ response = await self.http_client.request( # type: ignore[union-attr]method=request.method,url=url,headers=headers,@@ -2478,7 +2478,7 @@ class HeadroomProxy:else:url = f"{url}?key={api_key}"- response = await self.http_client.get(url, headers=headers)+ response = await self.http_client.get(url, headers=headers) # type: ignore[union-attr]if response.status_code != 200:# Error - pass through@@ -2551,7 +2551,7 @@ class HeadroomProxy:)# Process results with CCR handler- processor = BatchResultProcessor(self.http_client)+ processor = BatchResultProcessor(self.http_client) # type: ignore[arg-type]processed = await processor.process_results(batch_name, results, "google")# Update response with processed results@@ -3171,7 +3171,8 @@ class HeadroomProxy:)if response.status_code == 200:result = response.json()- return result.get("id")+ file_id: str | None = result.get("id")+ return file_idlogger.error(f"Failed to upload file: {response.status_code} - {response.text}")return Noneexcept Exception as e:@@ -3756,7 +3757,7 @@ class HeadroomProxy:self,request: Request,model: str,- ) -> StreamingResponse:+ ) -> StreamingResponse | JSONResponse:"""Handle Gemini streaming endpoint /v1beta/models/{model}:streamGenerateContent."""start_time = time.time()request_id = await self._next_request_id()