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(transforms): remove unused convenience wrappers and helpers (#4097)
Tejas Chopra5c72d824f4d1
diff --git a/headroom/image/trained_router.py b/headroom/image/trained_router.pyindex dfa16ef70..6645d63fa 100644--- a/headroom/image/trained_router.py+++ b/headroom/image/trained_router.py@@ -359,13 +359,3 @@ class TrainedRouter:query_prediction=technique.value,query_confidence=query_confidence,)---def get_trained_router(model_path: str | None = None) -> TrainedRouter:- """Get a trained router instance.-- Args:- model_path: Optional path to model (local or HF hub).- If None, uses local model if available, else HF hub.- """- return TrainedRouter(model_path=model_path)diff --git a/headroom/transforms/base.py b/headroom/transforms/base.pyindex c50fb0f5e..cffad025a 100644--- a/headroom/transforms/base.py+++ b/headroom/transforms/base.py@@ -9,24 +9,6 @@ from ..config import TransformResultfrom ..tokenizer import Tokenizer-def split_frozen(- messages: list[dict[str, Any]],- frozen_message_count: int,-) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:- """Split messages into frozen (cached prefix) and mutable portions.-- Args:- messages: All messages.- frozen_message_count: Number of leading messages to freeze.-- Returns:- (frozen, mutable) — frozen messages must not be modified.- """- if frozen_message_count <= 0 or frozen_message_count >= len(messages):- return [], messages- return messages[:frozen_message_count], messages[frozen_message_count:]--class Transform(ABC):"""Abstract base class for message transforms."""diff --git a/headroom/transforms/code_compressor.py b/headroom/transforms/code_compressor.pyindex 60a1cd13c..008dc1d00 100644--- a/headroom/transforms/code_compressor.py+++ b/headroom/transforms/code_compressor.py@@ -2686,33 +2686,3 @@ def _has_syntax_issues(node: Any) -> bool:if _has_syntax_issues(child):return Truereturn False---def compress_code(- code: str,- language: str | None = None,- target_rate: float = 0.2,- context: str = "",-) -> str:- """Convenience function for one-off code compression.-- Args:- code: Source code to compress.- language: Language hint (auto-detected if None).- target_rate: Target compression rate (0.2 = keep 20%).- context: Optional context for relevance.-- Returns:- Compressed code string.-- Example:- >>> compressed = compress_code(large_python_file)- >>> print(compressed) # Valid Python code- """- config = CodeCompressorConfig(- target_compression_rate=target_rate,- language_hint=language,- )- compressor = CodeAwareCompressor(config)- result = compressor.compress(code, language=language, context=context)- return result.compresseddiff --git a/headroom/transforms/content_detector.py b/headroom/transforms/content_detector.pyindex a92f104b0..180971923 100644--- a/headroom/transforms/content_detector.py+++ b/headroom/transforms/content_detector.py@@ -1009,20 +1009,3 @@ def _try_detect_code(content: str) -> DetectionResult | None:confidence,{"language": best_lang, "pattern_matches": best_score},)---def is_json_array_of_dicts(content: str) -> bool:- """Quick check if content is a JSON array of dictionaries.-- This is the format SmartCrusher can handle natively.-- Args:- content: The content to check.-- Returns:- True if content is a JSON array where all items are dicts.- """- result = detect_content_type(content)- return result.content_type == ContentType.JSON_ARRAY and result.metadata.get(- "is_dict_array", False- )diff --git a/headroom/transforms/content_router.py b/headroom/transforms/content_router.pyindex 2ab53e5aa..f73d269ea 100644--- a/headroom/transforms/content_router.py+++ b/headroom/transforms/content_router.py@@ -2489,7 +2489,6 @@ class ContentRouter(Transform):# skip — i.e. revert it to original text and bust the provider prefix# cache. Counting pins isolates the freeze's attributable payoff.self._freeze_pin_hits = 0- self._freeze_pin_chars = 0# ── #3486: per-request runtime state accessors ──────────────────────#@@ -2624,7 +2623,6 @@ class ContentRouter(Transform):preserved = max(0, int(len(content) * (1.0 - cached_ratio)))with self._frozen_lock:self._freeze_pin_hits += 1- self._freeze_pin_chars += preservedhits = self._freeze_pin_hitslogger.info(f"FREEZE-PIN: pins={hits} cached_ratio={cached_ratio:.3f} "@@ -7885,24 +7883,3 @@ class ContentRouter(Transform):Always returns True - the router handles all content types."""return True---def route_and_compress(- content: str,- context: str = "",-) -> str:- """Convenience function for one-off routing and compression.-- Args:- content: Content to compress.- context: Optional context for relevance-aware compression.-- Returns:- Compressed content.-- Example:- >>> compressed = route_and_compress(mixed_content)- """- router = ContentRouter()- result = router.compress(content, context=context)- return result.compresseddiff --git a/headroom/transforms/kompress_compressor.py b/headroom/transforms/kompress_compressor.pyindex e5d48c60a..5897dfded 100644--- a/headroom/transforms/kompress_compressor.py+++ b/headroom/transforms/kompress_compressor.py@@ -549,25 +549,6 @@ def _execution_semaphore(backend: str, device_type: str) -> threading.BoundedSemreturn semaphore-def _acquire_bounded(- semaphore: threading.BoundedSemaphore,- acquire_timeout: float | None,- remaining_budget: float | None,-) -> bool:- """Acquire ``semaphore``, waiting at most the tighter of the two bounds.-- Returns False on timeout. An unbounded wait here is how one stuck- inference (e.g. degraded ONNX on Windows) used to wedge every other- compression in the process: abandoned executor threads queued forever- on the semaphore. With both bounds disabled (<=0) this degrades to the- legacy blocking acquire.- """- bounds = [b for b in (acquire_timeout, remaining_budget) if b is not None]- if not bounds:- return semaphore.acquire()- return semaphore.acquire(timeout=max(0.0, min(bounds)))--def _batch_size() -> int:return _env_int(KOMPRESS_BATCH_SIZE_ENV) or 32diff --git a/headroom/transforms/pipeline.py b/headroom/transforms/pipeline.pyindex 09b4b45bd..648362d83 100644--- a/headroom/transforms/pipeline.py+++ b/headroom/transforms/pipeline.py@@ -12,7 +12,6 @@ from contextlib import nullcontextfrom typing import TYPE_CHECKING, Any, TypeVarfrom ..config import (- CacheAlignerConfig,DiffArtifact,HeadroomConfig,TransformDiff,@@ -597,23 +596,3 @@ class TransformPipeline:"""# apply() already works on a copy, so this is safereturn self.apply(messages, model, record_metrics=False, **kwargs)---def create_pipeline(- cache_aligner_config: CacheAlignerConfig | None = None,-) -> TransformPipeline:- """- Create a pipeline with specific configurations.-- Args:- cache_aligner_config: Cache aligner configuration.-- Returns:- Configured TransformPipeline.- """- config = HeadroomConfig()-- if cache_aligner_config is not None:- config.cache_aligner = cache_aligner_config-- return TransformPipeline(config)diff --git a/tests/test_kompress_failsafe.py b/tests/test_kompress_failsafe.pyindex 3d23c0ade..26e4c7d1b 100644--- a/tests/test_kompress_failsafe.py+++ b/tests/test_kompress_failsafe.py@@ -369,21 +369,6 @@ def test_carried_deadline_reaches_sequential_fallback(monkeypatch):assert model.calls == 1-def test_acquire_bounded_unbounded_when_both_disabled():- semaphore = kc._execution_semaphore("onnx", "onnx")- assert kc._acquire_bounded(semaphore, None, None) is True- semaphore.release()---def test_acquire_bounded_negative_remaining_does_not_raise():- semaphore = kc._execution_semaphore("onnx", "onnx")- assert semaphore.acquire(timeout=0)- try:- assert kc._acquire_bounded(semaphore, 5.0, -1.0) is False- finally:- semaphore.release()--# ── Wall-clock budget: give up before the proxy's stage timeout ───────diff --git a/tests/test_transforms_content_detection.py b/tests/test_transforms_content_detection.pyindex acf00a09f..77f45575d 100644--- a/tests/test_transforms_content_detection.py+++ b/tests/test_transforms_content_detection.py@@ -13,7 +13,6 @@ from headroom.transforms.content_detector import (_try_detect_log,_try_detect_search,detect_content_type,- is_json_array_of_dicts,normalize_concatenated_json,)from headroom.transforms.error_detection import (@@ -65,8 +64,6 @@ def test_json_detection_distinguishes_dict_arrays_and_other_lists() -> None:assert object_result.metadata == {"is_dict_array": False, "is_object": True}assert _try_detect_json("[not valid json") is None- assert is_json_array_of_dicts('[{"id": 1}]') is True- assert is_json_array_of_dicts('["value"]') is Falsedef test_space_separated_json_objects_detected_as_array() -> None:@@ -81,8 +78,9 @@ def test_space_separated_json_objects_detected_as_array() -> None:assert result.metadata == {"item_count": 3, "is_dict_array": True, "concatenated": True}# Reaches the same verdict through the top-level detector (not PLAIN_TEXT).- assert detect_content_type(content).content_type is ContentType.JSON_ARRAY- assert is_json_array_of_dicts(content) is True+ top_level = detect_content_type(content)+ assert top_level.content_type is ContentType.JSON_ARRAY+ assert top_level.metadata.get("is_dict_array") is True# Newline separation is just as common and must also be recognized.newline_sep = "\n".join(json.dumps({"id": i, "snippet": "x"}) for i in range(2))