💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows
Python agentsaiai-agentsembeddingsinformation-retrievallanguage-modellarge-language-modelsllmnlppythonragretrieval-augmented-generationsearchsearch-enginesemantic-searchsentence-embeddingstransformerstxtaivector-databasevector-search
Add milvus-lite as a dense ANN backend
morgan-coded99086302cec8
diff --git a/docs/embeddings/configuration/ann.md b/docs/embeddings/configuration/ann.mdindex 5a787d4d..a577af5b 100644--- a/docs/embeddings/configuration/ann.md+++ b/docs/embeddings/configuration/ann.md@@ -4,7 +4,7 @@ Approximate Nearest Neighbor (ANN) index configuration for storing vector embedd## backend```yaml-backend: faiss|hnsw|annoy|ggml|numpy|torch|turbovec|zvec|pgvector|sqlite|custom+backend: faiss|hnsw|annoy|ggml|milvuslite|numpy|torch|turbovec|zvec|pgvector|sqlite|custom```Sets the ANN backend. Defaults to `faiss`. Additional backends are available via the [ann](../../../install/#ann) extras package. Set custom backends via setting this parameter to the fully resolvable class string.diff --git a/setup.py b/setup.pyindex 8b0fd1a8..9eb4c50a 100644--- a/setup.py+++ b/setup.py@@ -59,6 +59,7 @@ extras["ann"] = ["bitsandbytes>=0.42.0","ggml-python>=0.0.41","hnswlib>=0.5.0",+ "milvus-lite>=3.1","pgvector>=0.4.1","scikit-learn>=0.23.1","scipy>=1.4.1",diff --git a/src/python/txtai/ann/dense/__init__.py b/src/python/txtai/ann/dense/__init__.pyindex 2f9fc25b..7fe44ef5 100644--- a/src/python/txtai/ann/dense/__init__.py+++ b/src/python/txtai/ann/dense/__init__.py@@ -6,6 +6,7 @@ from .annoy import Annoyfrom .factory import ANNFactoryfrom .faiss import Faissfrom .hnsw import HNSW+from .milvuslite import MilvusLitefrom .numpy import NumPyfrom .pgvector import PGVectorfrom .torch import Torchdiff --git a/src/python/txtai/ann/dense/factory.py b/src/python/txtai/ann/dense/factory.pyindex d58141e4..0e2c6cde 100644--- a/src/python/txtai/ann/dense/factory.py+++ b/src/python/txtai/ann/dense/factory.py@@ -8,6 +8,7 @@ from .annoy import Annoyfrom .faiss import Faiss, FAISSfrom .ggml import GGMLfrom .hnsw import HNSW+from .milvuslite import MilvusLitefrom .numpy import NumPyfrom .pgvector import PGVectorfrom .sqlite import SQLite@@ -44,6 +45,8 @@ class ANNFactory:ann = Faiss(config)elif backend == "hnsw":ann = HNSW(config)+ elif backend == "milvuslite":+ ann = MilvusLite(config)elif backend == "ggml":ann = GGML(config)elif backend == "numpy":diff --git a/src/python/txtai/ann/dense/milvuslite.py b/src/python/txtai/ann/dense/milvuslite.pynew file mode 100644index 00000000..06625e49--- /dev/null+++ b/src/python/txtai/ann/dense/milvuslite.py@@ -0,0 +1,138 @@+"""+milvus-lite module+"""++import os+import shutil+import tempfile++# Conditional import+try:+ import milvus_lite++ MILVUSLITE = True+except ImportError:+ MILVUSLITE = False++from ...archive import ArchiveFactory+from ..base import ANN+++class MilvusLite(ANN):+ """+ Builds an ANN index using the milvus-lite library.+ """++ def __init__(self, config):+ super().__init__(config)++ if not MILVUSLITE:+ raise ImportError('milvus-lite is not available - install "ann" extra to enable')++ self.collection = None+ self.directory = None+ self.path = None++ def load(self, path):+ self.close()+ self.directory = tempfile.mkdtemp()+ self.path = os.path.join(self.directory, "index")++ try:+ archive = ArchiveFactory.create(self.directory)+ archive.load(path, "tar")+ self.open()+ except Exception:+ self.close()+ raise++ def index(self, embeddings):+ self.close()++ # Lookup index settings+ m = self.setting("m", 50)++ # Create collection+ self.directory = tempfile.mkdtemp()+ self.path = os.path.join(self.directory, "index")++ # Use milvus-lite's native embedded API directly and keep this integration thin+ self.backend = milvus_lite.MilvusLite(self.path)+ schema = milvus_lite.CollectionSchema(+ fields=[+ milvus_lite.FieldSchema("id", milvus_lite.DataType.INT64, is_primary=True),+ milvus_lite.FieldSchema("embedding", milvus_lite.DataType.FLOAT_VECTOR, dim=self.config["dimensions"]),+ ]+ )+ self.collection = self.backend.create_collection("txtai", schema)+ self.collection.create_index("embedding", {"index_type": "HNSW", "metric_type": "IP", "params": {"M": m}})+ self.collection.load()++ # Add items - position in embeddings is used as the id+ self.insert(embeddings, 0)++ # Add id offset and index build metadata+ self.config["offset"] = embeddings.shape[0]+ self.metadata({"m": m, "milvuslite": milvus_lite.__version__})++ def append(self, embeddings):+ self.insert(embeddings, self.config["offset"])++ # Update id offset and index metadata+ self.config["offset"] += embeddings.shape[0]+ self.metadata()++ def delete(self, ids):+ if ids:+ self.collection.delete(ids)++ def search(self, queries, limit):+ matches = self.collection.search(queries.tolist(), top_k=limit, metric_type="IP", anns_field="embedding")+ return [[(int(match["id"]), float(match["distance"])) for match in results] for results in matches]++ def count(self):+ return self.collection.num_entities++ def save(self, path):+ self.collection.flush()+ self.backend.close()+ self.collection = None+ self.backend = None+ archive = ArchiveFactory.create(self.directory)+ archive.save(path, "tar")+ self.open()++ def close(self):+ # Release milvus-lite collection handles and the directory lock+ if self.backend:+ self.backend.close()+ self.collection = None+ super().close()++ if self.directory and os.path.exists(self.directory):+ shutil.rmtree(self.directory)++ self.directory = None+ self.path = None++ def insert(self, embeddings, offset):+ """+ Inserts embeddings starting at offset.++ Args:+ embeddings: embeddings array+ offset: starting id+ """++ if embeddings.shape[0]:+ for start in range(0, embeddings.shape[0], 1024):+ batch = embeddings[start : start + 1024]+ self.collection.insert(+ [{"id": offset + start + uid, "embedding": embedding.tolist()} for uid, embedding in enumerate(batch)]+ )++ def open(self):+ """Opens the milvus-lite database and collection."""++ self.backend = milvus_lite.MilvusLite(self.path)+ self.collection = self.backend.get_collection("txtai")diff --git a/test/python/testann/testdense.py b/test/python/testann/testdense.pyindex 2280c879..eaed64fd 100644--- a/test/python/testann/testdense.py+++ b/test/python/testann/testdense.py@@ -393,6 +393,25 @@ class TestDense(unittest.TestCase):self.runTests("turbovec")+ def testMilvusLite(self):+ """+ Test milvus-lite backend+ """++ self.runTests("milvuslite")++ def testMilvusLiteCustom(self):+ """+ Test milvus-lite backend with custom settings+ """++ self.runTests("milvuslite", {"milvuslite": {"m": 16}})++ # Test invalid file path handled+ with self.assertRaises(FileNotFoundError):+ ann = ANNFactory.create({"backend": "milvuslite"})+ ann.load("non-exist-path")+def testZvec(self):"""Test zvec backend