From 6ce753e40c4b78992d33706c51beeef75ced1400 Mon Sep 17 00:00:00 2001
From: James Briggs <35938317+jamescalam@users.noreply.github.com>
Date: Mon, 6 Jan 2025 08:31:25 +0400
Subject: [PATCH] fix: raise error if index not initialized at router level

---
 semantic_router/routers/base.py   | 4 ++++
 semantic_router/routers/hybrid.py | 2 ++
 tests/unit/test_router.py         | 3 ++-
 3 files changed, 8 insertions(+), 1 deletion(-)

diff --git a/semantic_router/routers/base.py b/semantic_router/routers/base.py
index 556d0f51..5bff5f5d 100644
--- a/semantic_router/routers/base.py
+++ b/semantic_router/routers/base.py
@@ -421,6 +421,8 @@ class BaseRouter(BaseModel):
         simulate_static: bool = False,
         route_filter: Optional[List[str]] = None,
     ) -> RouteChoice:
+        if self.index.index is None or self.routes is None:
+            raise ValueError("Index or routes are not populated.")
         # if no vector provided, encode text to get vector
         if vector is None:
             if text is None:
@@ -477,6 +479,8 @@ class BaseRouter(BaseModel):
         simulate_static: bool = False,
         route_filter: Optional[List[str]] = None,
     ) -> RouteChoice:
+        if self.index.index is None or self.routes is None:
+            raise ValueError("Index or routes are not populated.")
         # if no vector provided, encode text to get vector
         if vector is None:
             if text is None:
diff --git a/semantic_router/routers/hybrid.py b/semantic_router/routers/hybrid.py
index e2f0a23e..3d810576 100644
--- a/semantic_router/routers/hybrid.py
+++ b/semantic_router/routers/hybrid.py
@@ -218,6 +218,8 @@ class HybridRouter(BaseRouter):
         route_filter: Optional[List[str]] = None,
         sparse_vector: dict[int, float] | SparseEmbedding | None = None,
     ) -> RouteChoice:
+        if self.index.index is None or self.routes is None:
+            raise ValueError("Index or routes are not populated.")
         potential_sparse_vector: List[SparseEmbedding] | None = None
         # if no vector provided, encode text to get vector
         if vector is None:
diff --git a/tests/unit/test_router.py b/tests/unit/test_router.py
index cfb467dc..4d1378c5 100644
--- a/tests/unit/test_router.py
+++ b/tests/unit/test_router.py
@@ -815,7 +815,8 @@ class TestSemanticRouter:
         encoder = encoder_cls()
         route_layer = router_cls(encoder=encoder)
         # TODO: probably should avoid running this with multiple encoders or find a way to set dims
-        assert route_layer(text="Anything").name is None
+        with pytest.raises(ValueError):
+            assert route_layer(text="Anything").name is None
 
     def test_query_with_vector(self, routes, index_cls, encoder_cls, router_cls):
         encoder = encoder_cls()
-- 
GitLab