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(content-router,proxy): compress text blocks + close DeepSeek metrics gaps
Tejas Choprad955abb1d65a
diff --git a/headroom/models/registry.py b/headroom/models/registry.pyindex 425a762ba..15fcec469 100644--- a/headroom/models/registry.py+++ b/headroom/models/registry.py@@ -422,6 +422,30 @@ def _register_builtin_models() -> None:notes="DeepSeek Coder - Specialized for code",)+ _MODELS["deepseek-v4-flash"] = ModelInfo(+ name="deepseek-v4-flash",+ provider="deepseek",+ context_window=1_000_000,+ max_output_tokens=384_000,+ supports_tools=True,+ supports_vision=False,+ supports_streaming=True,+ tokenizer_backend="huggingface",+ notes="DeepSeek V4 Flash - 13B active params; non-thinking + thinking modes",+ )++ _MODELS["deepseek-v4-pro"] = ModelInfo(+ name="deepseek-v4-pro",+ provider="deepseek",+ context_window=1_000_000,+ max_output_tokens=384_000,+ supports_tools=True,+ supports_vision=False,+ supports_streaming=True,+ tokenizer_backend="huggingface",+ notes="DeepSeek V4 Pro - 49B active params",+ )+# ============================================================# Qwen Models# ============================================================diff --git a/headroom/providers/openai.py b/headroom/providers/openai.pyindex beaa43644..2851f4802 100644--- a/headroom/providers/openai.py+++ b/headroom/providers/openai.py@@ -93,6 +93,15 @@ _CONTEXT_LIMITS: dict[str, int] = {"o1-mini": 128000,"o3": 200000,"o3-mini": 200000,+ # DeepSeek (often accessed via OpenAI-compatible API). Values verified+ # against api-docs.deepseek.com (V4) and LiteLLM model_cost (deprecated+ # aliases). LiteLLM lookup is still attempted first in get_context_limit;+ # these are the manual fallback when LiteLLM doesn't know the model.+ "deepseek-v4-flash": 1_000_000,+ "deepseek-v4-pro": 1_000_000,+ "deepseek-chat": 131_072,+ "deepseek-reasoner": 131_072,+ "deepseek-coder": 16384,}# Fallback pricing - LiteLLM is preferred sourcediff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.pyindex f0036feaf..cb3e58a66 100644--- a/headroom/proxy/handlers/openai.py+++ b/headroom/proxy/handlers/openai.py@@ -766,6 +766,7 @@ class OpenAIHandlerMixin:tags,optimization_latency,pipeline_timing=pipeline_timing,+ waste_signals=waste_signals_dict,)else:# Non-streaming: use send_openai_message() → JSON@@ -823,8 +824,40 @@ class OpenAIHandlerMixin:cached=False,overhead_ms=optimization_latency,pipeline_timing=pipeline_timing,+ waste_signals=waste_signals_dict,)+ # Mirror the streaming path: log to RequestLogger so+ # /stats.recent_requests sees the OpenAI-via-backend+ # non-streaming path. Previously this path was silent.+ if getattr(self, "logger", None) is not None:+ from headroom.proxy.models import RequestLog++ self.logger.log(+ RequestLog(+ request_id=request_id,+ timestamp=datetime.now().isoformat(),+ provider=self.anthropic_backend.name,+ model=model,+ input_tokens_original=original_tokens,+ input_tokens_optimized=optimized_tokens,+ output_tokens=output_tokens,+ tokens_saved=tokens_saved,+ savings_percent=(tokens_saved / original_tokens * 100)+ if original_tokens > 0+ else 0,+ optimization_latency_ms=optimization_latency,+ total_latency_ms=total_latency,+ tags=tags or {},+ cache_hit=False,+ transforms_applied=transforms_applied,+ waste_signals=waste_signals_dict,+ request_messages=body.get("messages")+ if getattr(self.config, "log_full_messages", False)+ else None,+ )+ )+if tokens_saved > 0:logger.info(f"[{request_id}] {model}: {original_tokens:,} → {optimized_tokens:,} "diff --git a/headroom/proxy/handlers/streaming.py b/headroom/proxy/handlers/streaming.pyindex 9232d19f1..086d3f791 100644--- a/headroom/proxy/handlers/streaming.py+++ b/headroom/proxy/handlers/streaming.py@@ -1223,20 +1223,26 @@ class StreamingMixin:tags: dict[str, str],optimization_latency: float,pipeline_timing: dict[str, float] | None = None,+ waste_signals: dict[str, int] | None = None,) -> StreamingResponse:"""Stream OpenAI chat completion response from backend.Routes stream:true requests through the backend's stream_openai_message(),- yielding SSE events to the client.+ yielding SSE events to the client. Buffers chunks so the final+ `usage.completion_tokens` (set when stream_options.include_usage is+ on) can be parsed for metrics + RequestLog."""from fastapi.responses import StreamingResponseassert self.anthropic_backend is not Noneasync def generate():+ buffer: list[bytes] = []try:async for sse_chunk in self.anthropic_backend.stream_openai_message(body, headers):- yield sse_chunk.encode() if isinstance(sse_chunk, str) else sse_chunk+ chunk_bytes = sse_chunk.encode() if isinstance(sse_chunk, str) else sse_chunk+ buffer.append(chunk_bytes)+ yield chunk_bytesexcept Exception as e:logger.error(f"[{request_id}] Backend streaming error: {e}")error_data = {@@ -1249,18 +1255,74 @@ class StreamingMixin:yield f"data: {json.dumps(error_data)}\n\n".encode()yield b"data: [DONE]\n\n"finally:+ # Reverse-scan the buffered chunks for the final SSE frame+ # carrying `usage` (LiteLLM emits this only when the request+ # included stream_options.include_usage=true).+ output_tokens = 0+ for chunk_bytes in reversed(buffer):+ decoded = chunk_bytes.decode("utf-8", errors="replace")+ found = False+ for line in decoded.split("\n"):+ line = line.strip()+ if not line.startswith("data: ") or line == "data: [DONE]":+ continue+ try:+ data = json.loads(line[6:])+ except (json.JSONDecodeError, ValueError):+ continue+ chunk_usage = data.get("usage")+ if chunk_usage:+ output_tokens = int(chunk_usage.get("completion_tokens", 0) or 0)+ found = True+ break+ if found:+ break+total_latency = (time.time() - start_time) * 1000await self.metrics.record_request(provider=self.anthropic_backend.name,model=model,input_tokens=optimized_tokens,- output_tokens=0, # Unknown in streaming+ output_tokens=output_tokens,tokens_saved=tokens_saved,latency_ms=total_latency,cached=False,overhead_ms=optimization_latency,pipeline_timing=pipeline_timing,+ waste_signals=waste_signals,)++ # Mirror the Anthropic-stream path: log to RequestLogger so+ # /stats.recent_requests and /transformations/feed see this+ # request. Without it the OpenAI-via-backend path is invisible.+ if getattr(self, "logger", None) is not None:+ from headroom.proxy.models import RequestLog++ self.logger.log(+ RequestLog(+ request_id=request_id,+ timestamp=datetime.now().isoformat(),+ provider=self.anthropic_backend.name,+ model=model,+ input_tokens_original=original_tokens,+ input_tokens_optimized=optimized_tokens,+ output_tokens=output_tokens,+ tokens_saved=tokens_saved,+ savings_percent=(tokens_saved / original_tokens * 100)+ if original_tokens > 0+ else 0,+ optimization_latency_ms=optimization_latency,+ total_latency_ms=total_latency,+ tags=tags or {},+ cache_hit=False,+ transforms_applied=transforms_applied,+ waste_signals=waste_signals,+ request_messages=body.get("messages")+ if getattr(self.config, "log_full_messages", False)+ else None,+ )+ )+if tokens_saved > 0:logger.info(f"[{request_id}] {model}: {original_tokens:,} → {optimized_tokens:,} "diff --git a/headroom/transforms/content_router.py b/headroom/transforms/content_router.pyindex add7b9402..b75761e4f 100644--- a/headroom/transforms/content_router.py+++ b/headroom/transforms/content_router.py@@ -1645,6 +1645,9 @@ class ContentRouter(Transform):read_protection_window=read_protection_window,messages_from_end=messages_from_end,compressor_timing=compressor_timing,+ min_tokens=min_tokens,+ skip_user=skip_user,+ skip_system=skip_system,)result_slots[i] = transformed_messageroute_counts["content_blocks"] += 1@@ -1917,11 +1920,16 @@ class ContentRouter(Transform):read_protection_window: int = 8,messages_from_end: int = 0,compressor_timing: dict[str, float] | None = None,+ min_tokens: int = 50,+ skip_user: bool = True,+ skip_system: bool = True,) -> dict[str, Any]:- """Process content blocks (Anthropic format) for tool_result compression.+ """Process content blocks (Anthropic format) for compression.- Handles tool_result blocks by compressing their string content using- the appropriate strategy (typically SmartCrusher for JSON arrays).+ Handles tool_result blocks by compressing their string content. Also+ handles `text` blocks (e.g. from non-Anthropic clients whose SDK+ normalizes content into block-list form) but respects role-based+ protection so the user's actual prompt is never compressed.Args:message: The original message.@@ -1935,12 +1943,22 @@ class ContentRouter(Transform):min_ratio: Adaptive compression ratio threshold.read_protection_window: Messages from end within which excluded tools are protected.messages_from_end: How far this message is from the end of the conversation.+ min_tokens: Minimum token threshold for text-block compression.+ skip_user: If True, never compress text blocks in user-role messages.+ skip_system: If True, never compress text blocks in system-role messages.Returns:Transformed message with compressed content blocks."""new_blocks = []any_compressed = False+ role = message.get("role", "")+ # Text blocks in user/system messages carry the user's prompt or+ # the system instructions — compressing them silently corrupts the+ # request. tool_result blocks are unaffected by these guards (they+ # ride on user-role messages by Anthropic convention but represent+ # tool output, not user content).+ protect_text_blocks = (skip_user and role == "user") or (skip_system and role == "system")for block in content_blocks:if not isinstance(block, dict):@@ -2054,6 +2072,89 @@ class ContentRouter(Transform):if route_counts is not None:route_counts["small"] += 1+ # Handle text blocks — compress for non-Anthropic clients (e.g.+ # OpenAI/DeepSeek via Cline) whose SDK normalizes content to+ # block-list form. User and system roles are protected above.+ elif block_type == "text" and not protect_text_blocks:+ text_content = block.get("text", "")+ if isinstance(text_content, str) and len(text_content) > 500:+ # Pinning: skip already-compressed content+ if (+ "Retrieve more: hash=" in text_content+ or "Retrieve original: hash=" in text_content+ ):+ new_blocks.append(block)+ if route_counts is not None:+ route_counts.setdefault("already_compressed", 0)+ route_counts["already_compressed"] += 1+ continue++ content_key = hash(text_content)++ # Tier 1: skip set+ if self._cache.is_skipped(content_key):+ new_blocks.append(block)+ if route_counts is not None:+ route_counts["ratio_too_high"] += 1+ route_counts.setdefault("cache_hit", 0)+ route_counts["cache_hit"] += 1+ continue++ # Tier 2: result cache+ cached = self._cache.get(content_key)+ if cached is not None:+ cached_compressed, cached_ratio, cached_strategy = cached+ if cached_ratio < min_ratio:+ new_blocks.append({**block, "text": cached_compressed})+ transforms_applied.append(f"router:text_block:{cached_strategy}")+ if compressed_details is not None:+ compressed_details.append(+ f"text:{cached_strategy}:{cached_ratio:.2f}"+ )+ any_compressed = True+ else:+ self._cache.move_to_skip(content_key)+ new_blocks.append(block)+ if route_counts is not None:+ route_counts["ratio_too_high"] += 1+ if route_counts is not None:+ route_counts.setdefault("cache_hit", 0)+ route_counts["cache_hit"] += 1+ continue++ # Cache miss — full compression+ if route_counts is not None:+ route_counts.setdefault("cache_miss", 0)+ route_counts["cache_miss"] += 1+ t0 = time.perf_counter()+ result = self.compress(text_content, context=context, bias=1.0)+ compress_ms = (time.perf_counter() - t0) * 1000+ if compressor_timing is not None:+ key = f"compressor:{result.strategy_used.value}"+ compressor_timing[key] = compressor_timing.get(key, 0.0) + compress_ms+ if result.compression_ratio < min_ratio:+ self._cache.put(+ content_key,+ result.compressed,+ result.compression_ratio,+ result.strategy_used.value,+ )+ new_blocks.append({**block, "text": result.compressed})+ transforms_applied.append(f"router:text_block:{result.strategy_used.value}")+ if compressed_details is not None:+ compressed_details.append(+ f"text:{result.strategy_used.value}:{result.compression_ratio:.2f}"+ )+ any_compressed = True+ continue+ else:+ self._cache.mark_skip(content_key)+ if route_counts is not None:+ route_counts["ratio_too_high"] += 1+ else:+ if route_counts is not None:+ route_counts["small"] += 1+# Keep block unchangednew_blocks.append(block)