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.

chore(imports): lazy-load dynamic detector ML imports (#597)

Zbl1007e0a9fdb62c16
diff --git a/headroom/cache/dynamic_detector.py b/headroom/cache/dynamic_detector.py
index 039da0515..206c2adaa 100644
--- a/headroom/cache/dynamic_detector.py
+++ b/headroom/cache/dynamic_detector.py
@@ -36,29 +36,17 @@ import math
import re
from dataclasses import dataclass, field
from enum import Enum
+from importlib.util import find_spec
from typing import Any, Literal
from headroom.models.config import ML_MODEL_DEFAULTS
-# Optional imports - graceful degradation
-_SPACY_AVAILABLE = False
-_SENTENCE_TRANSFORMERS_AVAILABLE = False
-
-try:
- import spacy
-
- _SPACY_AVAILABLE = True
-except ImportError:
- spacy = None # type: ignore
-
-try:
- import numpy as np
- from sentence_transformers import SentenceTransformer
-
- _SENTENCE_TRANSFORMERS_AVAILABLE = True
-except ImportError:
- SentenceTransformer = None # type: ignore
- np = None # type: ignore
+# Optional ML dependencies are checked without importing them so this module
+# stays cheap to import during proxy startup.
+_SPACY_AVAILABLE = find_spec("spacy") is not None
+_SENTENCE_TRANSFORMERS_AVAILABLE = (
+ find_spec("numpy") is not None and find_spec("sentence_transformers") is not None
+)
class DynamicCategory(str, Enum):
@@ -601,6 +589,11 @@ class NERDetector:
from headroom.models.ml_models import MLModelRegistry
self._nlp = MLModelRegistry.get_spacy(config.spacy_model)
+ except ImportError:
+ self._load_error = (
+ "spaCy not installed. Install with: "
+ "pip install spacy && python -m spacy download en_core_web_sm"
+ )
except OSError:
self._load_error = (
f"spaCy model '{config.spacy_model}' not found. "
@@ -731,6 +724,11 @@ class SemanticDetector:
self.DYNAMIC_EXEMPLARS,
convert_to_numpy=True,
)
+ except ImportError:
+ self._load_error = (
+ "sentence-transformers not installed. "
+ "Install with: pip install sentence-transformers"
+ )
except Exception as e:
self._load_error = f"Failed to load embedding model: {e}"
@@ -773,6 +771,11 @@ class SemanticDetector:
if not sentences:
return [], None
+ try:
+ import numpy as np
+ except ImportError:
+ return [], "numpy not installed. Install with: pip install numpy"
+
sentence_texts = [s[0] for s in sentences]
sentence_embeddings = self._model.encode( # type: ignore[union-attr]
sentence_texts,
@@ -780,7 +783,7 @@ class SemanticDetector:
)
# Compute similarities
- similarities = np.dot(sentence_embeddings, self._exemplar_embeddings.T) # type: ignore[union-attr]
+ similarities = np.dot(sentence_embeddings, self._exemplar_embeddings.T)
for i, (text, start, end) in enumerate(sentences):
# Get max similarity to any exemplar
diff --git a/tests/test_package_init_lazy.py b/tests/test_package_init_lazy.py
index be56fee46..07af22fe2 100644
--- a/tests/test_package_init_lazy.py
+++ b/tests/test_package_init_lazy.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import json
+import os
import subprocess
import sys
import textwrap
@@ -126,3 +127,47 @@ def test_proxy_server_import_skips_litellm_backend() -> None:
assert data["litellm_backend_loaded"] is False
assert data["anyllm_backend_loaded"] is False
assert data["litellm_loaded"] is False
+
+
+def test_dynamic_detector_import_skips_optional_ml_dependencies(tmp_path: Path) -> None:
+ (tmp_path / "spacy.py").write_text("", encoding="utf-8")
+ (tmp_path / "numpy.py").write_text("", encoding="utf-8")
+ (tmp_path / "torch.py").write_text("", encoding="utf-8")
+ sentence_transformers_dir = tmp_path / "sentence_transformers"
+ sentence_transformers_dir.mkdir()
+ (sentence_transformers_dir / "__init__.py").write_text(
+ "import torch\n\nclass SentenceTransformer:\n pass\n",
+ encoding="utf-8",
+ )
+
+ script = textwrap.dedent(
+ """
+ import json
+ import sys
+
+ import headroom.cache.dynamic_detector
+
+ print(json.dumps({
+ "spacy_loaded": "spacy" in sys.modules,
+ "sentence_transformers_loaded": "sentence_transformers" in sys.modules,
+ "torch_loaded": "torch" in sys.modules,
+ }))
+ """
+ )
+
+ env = os.environ.copy()
+ env["PYTHONPATH"] = str(tmp_path)
+
+ result = subprocess.run(
+ [sys.executable, "-c", script],
+ capture_output=True,
+ text=True,
+ check=True,
+ cwd=Path(__file__).resolve().parents[1],
+ env=env,
+ )
+
+ data = json.loads(result.stdout.strip())
+ assert data["spacy_loaded"] is False
+ assert data["sentence_transformers_loaded"] is False
+ assert data["torch_loaded"] is False