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.

Make hnswlib optional and skip tests when unavailable

chopratejasdf6a38b477c1
diff --git a/headroom/memory/adapters/__init__.py b/headroom/memory/adapters/__init__.py
index e715552c1..ff7b36a0f 100644
--- a/headroom/memory/adapters/__init__.py
+++ b/headroom/memory/adapters/__init__.py
@@ -18,6 +18,12 @@ from headroom.memory.adapters.cache import LRUMemoryCache
from headroom.memory.adapters.fts5 import FTS5TextIndex
from headroom.memory.adapters.sqlite import SQLiteMemoryStore
+# Check for optional dependencies availability
+try:
+ from headroom.memory.adapters.hnsw import HNSW_AVAILABLE
+except ImportError:
+ HNSW_AVAILABLE = False
+
# Lazy imports for optional adapters
_HNSWVectorIndex = None
_LocalEmbedder = None
@@ -70,4 +76,6 @@ __all__ = [
"LocalEmbedder",
"OllamaEmbedder",
"OpenAIEmbedder",
+ # Availability flags
+ "HNSW_AVAILABLE",
]
diff --git a/headroom/memory/adapters/hnsw.py b/headroom/memory/adapters/hnsw.py
index 7b2aee8a3..0355743a1 100644
--- a/headroom/memory/adapters/hnsw.py
+++ b/headroom/memory/adapters/hnsw.py
@@ -3,6 +3,12 @@
Provides fast approximate nearest neighbor search with cosine similarity
for semantic memory retrieval. Supports filtering by user_id, session_id,
agent_id, category, and entity references.
+
+Note: hnswlib is an optional dependency. Install with:
+ pip install hnswlib
+
+Or via headroom extras:
+ pip install "headroom-ai[memory]"
"""
from __future__ import annotations
@@ -14,9 +20,17 @@ from pathlib import Path
from threading import Lock
from typing import TYPE_CHECKING, Any
-import hnswlib
import numpy as np
+# hnswlib is optional - may not compile on all platforms
+try:
+ import hnswlib
+
+ HNSW_AVAILABLE = True
+except ImportError:
+ hnswlib = None # type: ignore[assignment]
+ HNSW_AVAILABLE = False
+
from ..models import Memory, MemoryCategory, ScopeLevel
from ..ports import VectorFilter, VectorSearchResult
@@ -176,7 +190,16 @@ class HNSWVectorIndex:
Raises:
ValueError: If auto_save is True but save_path is not provided.
+ ImportError: If hnswlib is not installed.
"""
+ if not HNSW_AVAILABLE:
+ raise ImportError(
+ "hnswlib is required for HNSWVectorIndex. "
+ "Install with: pip install hnswlib\n"
+ "Note: hnswlib requires C++ compilation and may not be "
+ "available on all platforms."
+ )
+
if auto_save and save_path is None:
raise ValueError("save_path must be provided when auto_save is True")
diff --git a/tests/test_hnsw_only.py b/tests/test_hnsw_only.py
new file mode 100644
index 000000000..c33d9e37b
--- /dev/null
+++ b/tests/test_hnsw_only.py
@@ -0,0 +1,78 @@
+"""Isolated HNSW tests - copy of relevant parts from test_hierarchical.py."""
+
+import os
+
+os.environ["TOKENIZERS_PARALLELISM"] = "false"
+
+import tempfile
+from pathlib import Path
+
+import numpy as np
+import pytest
+
+from headroom.memory.models import Memory
+from headroom.memory.ports import VectorFilter
+
+# Check if hnswlib is available
+try:
+ from headroom.memory.adapters.hnsw import HNSW_AVAILABLE
+except ImportError:
+ HNSW_AVAILABLE = False
+
+
+def temp_db_path():
+ """Create a temporary database path."""
+ with tempfile.NamedTemporaryFile(suffix=".db", delete=False) as f:
+ yield Path(f.name)
+
+
[email protected](not HNSW_AVAILABLE, reason="hnswlib not installed")
+class TestHNSWVectorIndex:
+ """Tests for HNSWVectorIndex."""
+
+ @pytest.fixture
+ def vector_index(self, temp_db_path):
+ """Create an HNSW vector index for testing."""
+ from headroom.memory.adapters.hnsw import HNSWVectorIndex
+
+ return HNSWVectorIndex(dimension=384, save_path=temp_db_path.with_suffix(".hnsw"))
+
+ @pytest.mark.asyncio
+ async def test_index_and_search(self, vector_index):
+ """Test indexing and searching vectors."""
+ print("\n[TEST] Starting test_index_and_search")
+
+ # Create memories with random embeddings
+ np.random.seed(42)
+ memories = []
+ for i in range(10):
+ embedding = np.random.randn(384).astype(np.float32)
+ memory = Memory(
+ content=f"Test content {i}",
+ user_id="alice",
+ embedding=embedding,
+ )
+ memories.append(memory)
+ print(f"[TEST] Created {len(memories)} memories")
+
+ # Index all memories
+ print("[TEST] Indexing...")
+ for memory in memories:
+ await vector_index.index(memory)
+ print("[TEST] All indexed!")
+
+ # Search with first memory's embedding
+ filter = VectorFilter(
+ query_vector=memories[0].embedding,
+ top_k=3,
+ user_id="alice",
+ )
+ print("[TEST] Searching...")
+ results = await vector_index.search(filter)
+ print(f"[TEST] Found {len(results)} results")
+
+ assert len(results) == 3
+ assert results[0].memory.id == memories[0].id
+ assert results[0].similarity > 0.99
+ print("[TEST] PASSED!")
diff --git a/tests/test_memory/test_hierarchical.py b/tests/test_memory/test_hierarchical.py
index c81623e50..6fd892c8a 100644
--- a/tests/test_memory/test_hierarchical.py
+++ b/tests/test_memory/test_hierarchical.py
@@ -615,7 +615,14 @@ class TestIntegration:
# HNSW Vector Index Tests
# =============================================================================
+# Check if hnswlib is available
+try:
+ from headroom.memory.adapters.hnsw import HNSW_AVAILABLE
+except ImportError:
+ HNSW_AVAILABLE = False
+
[email protected](not HNSW_AVAILABLE, reason="hnswlib not installed")
class TestHNSWVectorIndex:
"""Tests for HNSWVectorIndex."""