ruvector-router 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,72 @@
1
+ """Embedding based routing over native RuVector HNSW, without network calls."""
2
+ from dataclasses import dataclass
3
+ import math
4
+ import numpy as np
5
+ from ruvector import HnswIndex
6
+
7
+ __all__ = ['SemanticRouter', 'RouteMatch']
8
+
9
+ @dataclass(frozen=True)
10
+ class RouteMatch:
11
+ name: str
12
+ score: float
13
+
14
+ class SemanticRouter:
15
+ """One representative embedding per route; cosine similarity threshold.
16
+
17
+ This is a Python routing policy over native core HNSW, not a binding to
18
+ the separate neural router crate. Embeddings must be supplied by callers.
19
+ """
20
+ def __init__(self, dimensions: int, *, threshold: float = 0.7):
21
+ if isinstance(dimensions, bool) or not isinstance(dimensions, int) or not 1 <= dimensions <= 65536:
22
+ raise ValueError('dimensions must be an integer in [1, 65536]')
23
+ if isinstance(threshold, bool) or not isinstance(threshold, (int, float)) or not math.isfinite(threshold) or not -1 <= threshold <= 1:
24
+ raise ValueError('threshold must be finite in [-1, 1]')
25
+ self.dimensions, self.threshold = dimensions, float(threshold)
26
+ self._vectors = {}
27
+ self._index = HnswIndex.create(dimensions)
28
+
29
+ def _vector(self, vector):
30
+ data = np.ascontiguousarray(vector, dtype=np.float32)
31
+ if data.ndim != 1 or len(data) != self.dimensions or not np.isfinite(data).all():
32
+ raise ValueError('embedding must be a finite vector matching dimensions')
33
+ # Reject zero norm; normalize in float64 to avoid float32 overflow.
34
+ norm = np.linalg.norm(data.astype(np.float64))
35
+ if not norm > 0:
36
+ raise ValueError('cosine routing requires nonzero embeddings')
37
+ return np.ascontiguousarray(data.astype(np.float64) / norm, dtype=np.float32)
38
+
39
+ def _replace(self, vectors):
40
+ # Build first, then commit. Replacement/deletion cannot retain stale HNSW
41
+ # graph nodes and invalid inserts leave the prior router intact.
42
+ index = HnswIndex.create(self.dimensions)
43
+ for name, vector in sorted(vectors.items()):
44
+ index.insert(name, vector)
45
+ self._index, self._vectors = index, vectors
46
+
47
+ def add(self, name: str, embedding):
48
+ if not isinstance(name, str) or not name.strip() or len(name) > 1024:
49
+ raise ValueError('name must be a nonempty string of at most 1024 characters')
50
+ vector = self._vector(embedding)
51
+ self._replace({**self._vectors, name: vector})
52
+
53
+ def remove(self, name: str) -> bool:
54
+ if name not in self._vectors:
55
+ return False
56
+ vectors = self._vectors.copy()
57
+ del vectors[name]
58
+ self._replace(vectors)
59
+ return True
60
+
61
+ def route(self, embedding, *, k: int = 1) -> list[RouteMatch]:
62
+ vector = self._vector(embedding)
63
+ if isinstance(k, bool) or not isinstance(k, int) or not 1 <= k <= 100000:
64
+ raise ValueError('k must be an integer in [1, 100000]')
65
+ if not self._vectors:
66
+ return []
67
+ results = self._index.search(vector, min(k, len(self._vectors)))
68
+ matches = [RouteMatch(name, max(-1., min(1., 1. - distance))) for name, distance, _ in results]
69
+ return sorted((m for m in matches if m.score >= self.threshold), key=lambda m: (-m.score, m.name))
70
+
71
+ def __len__(self):
72
+ return len(self._vectors)
File without changes
@@ -0,0 +1,53 @@
1
+ Metadata-Version: 2.4
2
+ Name: ruvector-router
3
+ Version: 0.2.0
4
+ Summary: Semantic embedding routing backed by native RuVector HNSW
5
+ Project-URL: Homepage, https://github.com/ruvnet/RuVector
6
+ Project-URL: Documentation, https://github.com/ruvnet/RuVector/tree/main/python/portfolio/ruvector-router
7
+ Project-URL: Repository, https://github.com/ruvnet/RuVector
8
+ Project-URL: Issues, https://github.com/ruvnet/RuVector/issues
9
+ Project-URL: Changelog, https://github.com/ruvnet/RuVector/blob/main/python/portfolio/CHANGELOG.md
10
+ Author: RuVector Team
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ Keywords: ai,embeddings,router,rust,ruvector
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Rust
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Requires-Python: >=3.10
19
+ Requires-Dist: numpy>=1.21
20
+ Requires-Dist: ruvector==0.1.3
21
+ Description-Content-Type: text/markdown
22
+
23
+ # ruvector-router
24
+
25
+ ![RuVector semantic routing](https://raw.githubusercontent.com/ruvnet/RuVector/main/docs/python-portfolio/router.svg)
26
+
27
+ Route embedding vectors to named intents with native RuVector HNSW search and an explicit cosine similarity threshold. Supply your own embeddings; the router makes no network requests.
28
+
29
+ ## Getting started
30
+
31
+ ```sh
32
+ python -m pip install ruvector-router==0.2.0
33
+ ```
34
+
35
+ ```python
36
+ from ruvector_router import SemanticRouter
37
+ router = SemanticRouter(2, threshold=0.8)
38
+ router.add('support', [1, 0])
39
+ router.add('sales', [0, 1])
40
+ assert router.route([1, 0])[0].name == 'support'
41
+ router.add('support', [-1, 0]) # Replace an existing route
42
+ assert router.route([1, 0]) == []
43
+ assert router.remove('support')
44
+ assert not router.remove('support')
45
+ ```
46
+
47
+ ## Architecture and scope
48
+
49
+ Caller embeddings → finite nonzero vector validation → normalization → native HNSW nearest routes → cosine threshold → typed `RouteMatch` values.
50
+
51
+ One representative embedding per route. HNSW is approximate; thresholds are inclusive and do not guarantee intent classification quality. This is a Python semantic policy over the native core index, not a binding to the separate neural router or an embedding model. Mutation rebuilds the index before committing, ensuring replacements and deletions cannot leave stale routes, at a cost proportional to the number of routes. Designed for small intent catalogs rather than high frequency writes to large indexes. Ties among retrieved results sort by name.
52
+
53
+ Python 3.10 or later; runtime `ruvector==0.1.3`. [Portfolio documentation](https://github.com/ruvnet/RuVector/tree/main/python/portfolio).
@@ -0,0 +1,6 @@
1
+ ruvector_router/__init__.py,sha256=sjCH9cdLpgZJ2EsnuudTRzUhHKj_lQQtNdYit4Mshsk,3318
2
+ ruvector_router/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ ruvector_router-0.2.0.dist-info/METADATA,sha256=JzgGYQkt5JY2xehOUHkzaiBXh5oi5nZpwdrdDVBNVfc,2599
4
+ ruvector_router-0.2.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
5
+ ruvector_router-0.2.0.dist-info/licenses/LICENSE,sha256=UP77k1YK9EITacmck8whTNg1sxgat_FjI_nm8t7YcOM,1060
6
+ ruvector_router-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 rUv
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.