Skip to content

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.

Add question-aware compression and enable ContentRouter by default

chopratejas02e742f3578b
diff --git a/headroom/config.py b/headroom/config.py
index 399b19ac2..5c707d4ef 100644
--- a/headroom/config.py
+++ b/headroom/config.py
@@ -492,6 +492,11 @@ class HeadroomConfig:
cache_optimizer: CacheOptimizerConfig = field(default_factory=CacheOptimizerConfig)
ccr: CCRConfig = field(default_factory=CCRConfig) # Compress-Cache-Retrieve
+ # Content Router - intelligent content-type based compression
+ # Routes content to appropriate compressor (LLMLingua for text, SmartCrusher for JSON,
+ # CodeCompressor for code, LogCompressor for logs, etc.)
+ content_router_enabled: bool = True
+
# Intelligent context management (Phase 2.5)
# When enabled, replaces RollingWindow with semantic-aware context management
intelligent_context: IntelligentContextConfig = field(
diff --git a/headroom/transforms/content_router.py b/headroom/transforms/content_router.py
index dcb156b97..8817ed8cb 100644
--- a/headroom/transforms/content_router.py
+++ b/headroom/transforms/content_router.py
@@ -548,12 +548,15 @@ class ContentRouter(Transform):
self,
content: str,
context: str = "",
+ question: str | None = None,
) -> RouterCompressionResult:
"""Compress content using optimal strategy based on content detection.
Args:
content: Content to compress.
context: Optional context for relevance-aware compression.
+ question: Optional question for QA-aware compression. When provided,
+ tokens relevant to answering this question are preserved.
Returns:
RouterCompressionResult with compressed content and routing metadata.
@@ -570,9 +573,9 @@ class ContentRouter(Transform):
strategy = self._determine_strategy(content)
if strategy == CompressionStrategy.MIXED:
- return self._compress_mixed(content, context)
+ return self._compress_mixed(content, context, question)
else:
- return self._compress_pure(content, strategy, context)
+ return self._compress_pure(content, strategy, context, question)
def _determine_strategy(self, content: str) -> CompressionStrategy:
"""Determine the compression strategy from content analysis.
@@ -625,12 +628,14 @@ class ContentRouter(Transform):
self,
content: str,
context: str,
+ question: str | None = None,
) -> RouterCompressionResult:
"""Compress mixed content by splitting and routing sections.
Args:
content: Mixed content to compress.
context: User context for relevance.
+ question: Optional question for QA-aware compression.
Returns:
RouterCompressionResult with reassembled content.
@@ -654,7 +659,7 @@ class ContentRouter(Transform):
# Compress section
original_tokens = len(section.content.split())
compressed_content, compressed_tokens = self._apply_strategy_to_content(
- section.content, strategy, context, section.language
+ section.content, strategy, context, section.language, question
)
# Preserve code fence markers
@@ -685,6 +690,7 @@ class ContentRouter(Transform):
content: str,
strategy: CompressionStrategy,
context: str,
+ question: str | None = None,
) -> RouterCompressionResult:
"""Compress pure (non-mixed) content.
@@ -692,13 +698,16 @@ class ContentRouter(Transform):
content: Content to compress.
strategy: Selected strategy.
context: User context.
+ question: Optional question for QA-aware compression.
Returns:
RouterCompressionResult.
"""
original_tokens = len(content.split())
- compressed, compressed_tokens = self._apply_strategy_to_content(content, strategy, context)
+ compressed, compressed_tokens = self._apply_strategy_to_content(
+ content, strategy, context, question=question
+ )
return RouterCompressionResult(
compressed=compressed,
@@ -720,6 +729,7 @@ class ContentRouter(Transform):
strategy: CompressionStrategy,
context: str,
language: str | None = None,
+ question: str | None = None,
) -> tuple[str, int]:
"""Apply a compression strategy to content.
@@ -728,6 +738,7 @@ class ContentRouter(Transform):
strategy: Strategy to use.
context: User context.
language: Language hint for code.
+ question: Optional question for QA-aware compression.
Returns:
Tuple of (compressed_content, compressed_token_count).
@@ -746,7 +757,7 @@ class ContentRouter(Transform):
compressed, compressed_tokens = result.compressed, result.compressed_tokens
if compressed is None:
# Fallback to LLMLingua
- compressed, compressed_tokens = self._try_llmlingua(content, context)
+ compressed, compressed_tokens = self._try_llmlingua(content, context, question)
strategy = CompressionStrategy.LLMLINGUA # Update for TOIN
elif strategy == CompressionStrategy.SMART_CRUSHER:
@@ -796,12 +807,12 @@ class ContentRouter(Transform):
compressed_tokens = len(compressed.split()) if compressed else 0
elif strategy == CompressionStrategy.LLMLINGUA:
- compressed, compressed_tokens = self._try_llmlingua(content, context)
+ compressed, compressed_tokens = self._try_llmlingua(content, context, question)
elif strategy == CompressionStrategy.TEXT:
# Prefer LLMLingua for text if available (ML-based, better compression)
# Falls back to heuristic TextCompressor if LLMLingua unavailable
- compressed, compressed_tokens = self._try_llmlingua(content, context)
+ compressed, compressed_tokens = self._try_llmlingua(content, context, question)
except Exception as e:
logger.warning("Compression with %s failed: %s", strategy.value, e)
@@ -822,12 +833,15 @@ class ContentRouter(Transform):
# Fallback: return unchanged
return content, original_tokens
- def _try_llmlingua(self, content: str, context: str) -> tuple[str, int]:
+ def _try_llmlingua(
+ self, content: str, context: str, question: str | None = None
+ ) -> tuple[str, int]:
"""Try LLMLingua compression with fallback.
Args:
content: Content to compress.
context: User context.
+ question: Optional question for QA-aware compression.
Returns:
Tuple of (compressed, token_count).
@@ -836,7 +850,7 @@ class ContentRouter(Transform):
compressor = self._get_llmlingua()
if compressor:
try:
- result = compressor.compress(content, context=context)
+ result = compressor.compress(content, context=context, question=question)
return result.compressed, result.compressed_tokens
except Exception as e:
logger.debug("LLMLingua failed: %s", e)
diff --git a/headroom/transforms/llmlingua_compressor.py b/headroom/transforms/llmlingua_compressor.py
index 165f6ad53..c760399e8 100644
--- a/headroom/transforms/llmlingua_compressor.py
+++ b/headroom/transforms/llmlingua_compressor.py
@@ -299,6 +299,7 @@ class LLMLinguaCompressor(Transform):
content: str,
context: str = "",
content_type: str | None = None,
+ question: str | None = None,
) -> LLMLinguaResult:
"""Compress content using LLMLingua-2.
@@ -307,6 +308,9 @@ class LLMLinguaCompressor(Transform):
context: Optional context for relevance-aware compression.
content_type: Type of content ('code', 'json', 'text').
If None, auto-detected.
+ question: Optional question for QA-aware compression. When provided,
+ LLMLingua preserves tokens relevant to answering this question.
+ This significantly improves accuracy for QA tasks.
Returns:
LLMLinguaResult with compressed content and metadata.
@@ -357,12 +361,21 @@ class LLMLinguaCompressor(Transform):
# Perform compression
try:
- result = compressor.compress_prompt(
- context=[content], # LLMLingua expects a list of context strings
- rate=compression_rate,
- force_tokens=force_tokens if force_tokens else [],
- drop_consecutive=self.config.drop_consecutive,
- )
+ # Build compress_prompt kwargs
+ compress_kwargs: dict[str, Any] = {
+ "context": [content], # LLMLingua expects a list of context strings
+ "rate": compression_rate,
+ "force_tokens": force_tokens if force_tokens else [],
+ "drop_consecutive": self.config.drop_consecutive,
+ }
+
+ # Add question for QA-aware token selection (LLMLingua-2 feature)
+ # This enables relevance-aware compression where tokens relevant
+ # to answering the question are preserved with higher probability
+ if question:
+ compress_kwargs["question"] = question
+
+ result = compressor.compress_prompt(**compress_kwargs)
compressed = result.get("compressed_prompt", content)
original_tokens = result.get("origin_tokens", estimated_tokens)
diff --git a/headroom/transforms/pipeline.py b/headroom/transforms/pipeline.py
index ee9ba445a..1258f326b 100644
--- a/headroom/transforms/pipeline.py
+++ b/headroom/transforms/pipeline.py
@@ -19,6 +19,7 @@ from ..tokenizer import Tokenizer
from ..utils import deep_copy_messages
from .base import Transform
from .cache_aligner import CacheAligner
+from .content_router import ContentRouter
from .intelligent_context import IntelligentContextManager
from .rolling_window import RollingWindow
from .smart_crusher import SmartCrusher
@@ -36,8 +37,10 @@ class TransformPipeline:
Transform order:
1. Cache Aligner - normalize prefix for cache hits
- 2. Tool Crusher - compress tool outputs
- 3. Rolling Window - enforce token limits
+ 2. Content Router - intelligent content-aware compression (routes to appropriate
+ compressor: LLMLingua for text, SmartCrusher for JSON, CodeCompressor for code, etc.)
+ 3. SmartCrusher/ToolCrusher - fallback if ContentRouter disabled
+ 4. IntelligentContextManager/RollingWindow - enforce token limits
"""
def __init__(
@@ -72,10 +75,19 @@ class TransformPipeline:
if self.config.cache_aligner.enabled:
transforms.append(CacheAligner(self.config.cache_aligner))
- # 2. Tool Output Compression
- # SmartCrusher (statistical) takes precedence over ToolCrusher (fixed rules)
- if self.config.smart_crusher.enabled:
- # Use smart statistical crushing
+ # 2. Content-aware Compression
+ # ContentRouter handles ALL content types intelligently:
+ # - JSON arrays -> SmartCrusher
+ # - Plain text -> LLMLingua (ML-based) or TextCompressor
+ # - Code -> CodeCompressor (AST-aware)
+ # - Logs -> LogCompressor
+ # - Search results -> SearchCompressor
+ # - HTML -> HTMLExtractor
+ if self.config.content_router_enabled:
+ transforms.append(ContentRouter())
+ logger.info("Pipeline using ContentRouter for intelligent content-aware compression")
+ elif self.config.smart_crusher.enabled:
+ # Fallback: SmartCrusher only handles JSON arrays
from .smart_crusher import SmartCrusherConfig as SCConfig
smart_config = SCConfig(