💡 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
Update ANN package to make terminology more consistent, closes #334
davidmezzetti3f824ec27519
diff --git a/src/python/txtai/ann/annoy.py b/src/python/txtai/ann/annoy.pyindex f31f8b06..4ff0f0dd 100644--- a/src/python/txtai/ann/annoy.py+++ b/src/python/txtai/ann/annoy.py@@ -16,28 +16,34 @@ from .base import ANN# pylint: disable=W0223class Annoy(ANN):"""- Builds an ANN model using the Annoy library.+ Builds an ANN index using the Annoy library."""+ def __init__(self, config):+ super().__init__(config)++ if not ANNOY:+ raise ImportError('Annoy is not available - install "similarity" extra to enable')+def load(self, path):# Load index- self.model = AnnoyIndex(self.config["dimensions"], self.config["metric"])- self.model.load(path)+ self.backend = AnnoyIndex(self.config["dimensions"], self.config["metric"])+ self.backend.load(path)def index(self, embeddings):# Inner product is equal to cosine similarity on normalized vectorsself.config["metric"] = "dot"# Create index- self.model = AnnoyIndex(self.config["dimensions"], self.config["metric"])+ self.backend = AnnoyIndex(self.config["dimensions"], self.config["metric"])# Add items - position in embeddings is used as the idfor x in range(embeddings.shape[0]):- self.model.add_item(x, embeddings[x])+ self.backend.add_item(x, embeddings[x])# Build indexntrees = self.setting("ntrees", 10)- self.model.build(ntrees)+ self.backend.build(ntrees)# Add index build metadataself.metadata({"ntrees": ntrees})@@ -50,7 +56,7 @@ class Annoy(ANN):results = []for query in queries:# Run the query- ids, scores = self.model.get_nns_by_vector(query, n=limit, search_k=searchk, include_distances=True)+ ids, scores = self.backend.get_nns_by_vector(query, n=limit, search_k=searchk, include_distances=True)# Map results to [(id, score)]results.append(list(zip(ids, scores)))@@ -59,8 +65,8 @@ class Annoy(ANN):def count(self):# Number of items in index- return self.model.get_n_items()+ return self.backend.get_n_items()def save(self, path):# Write index- self.model.save(path)+ self.backend.save(path)diff --git a/src/python/txtai/ann/base.py b/src/python/txtai/ann/base.pyindex 8f5e49c0..18227865 100644--- a/src/python/txtai/ann/base.py+++ b/src/python/txtai/ann/base.py@@ -10,26 +10,26 @@ from .. import __version__class ANN:"""- Base class for ANN models.+ Base class for ANN instances."""def __init__(self, config):"""- Creates a new ANN model.+ Creates a new ANN.Args:config: index configuration parameters"""# ANN index- self.model = None+ self.backend = None- # Model configuration+ # ANN configurationself.config = configdef load(self, path):"""- Loads an ANN model at path.+ Loads an ANN at path.Args:path: path to load ann index@@ -39,7 +39,7 @@ class ANN:def index(self, embeddings):"""- Builds an ANN model.+ Builds an ANN index.Args:embeddings: embeddings array@@ -49,7 +49,7 @@ class ANN:def append(self, embeddings):"""- Append elements to an existing model.+ Append elements to an existing index.Args:embeddings: embeddings array@@ -59,7 +59,7 @@ class ANN:def delete(self, ids):"""- Deletes elements from existing model.+ Deletes elements from existing index.Args:ids: ids to delete@@ -69,7 +69,7 @@ class ANN:def search(self, queries, limit):"""- Searches ANN model for query. Returns topn results.+ Searches ANN index for query. Returns topn results.Args:queries: queries array@@ -83,7 +83,7 @@ class ANN:def count(self):"""- Number of elements in the ANN model.+ Number of elements in the ANN index.Returns:count@@ -93,7 +93,7 @@ class ANN:def save(self, path):"""- Saves an ANN model at path.+ Saves an ANN index at path.Args:path: path to save ann indexdiff --git a/src/python/txtai/ann/factory.py b/src/python/txtai/ann/factory.pyindex 6767b4d7..01d0aa5f 100644--- a/src/python/txtai/ann/factory.py+++ b/src/python/txtai/ann/factory.py@@ -2,20 +2,20 @@Factory module"""-from .annoy import Annoy, ANNOY+from .annoy import Annoyfrom .faiss import Faiss-from .hnsw import HNSW, HNSWLIB+from .hnsw import HNSWclass ANNFactory:"""- Methods to create ANN models.+ Methods to create ANN indexes."""@staticmethoddef create(config):"""- Create an ANN model.+ Create an ANN.Args:config: index configuration parameters@@ -24,25 +24,19 @@ class ANNFactory:ANN"""- # ANN model- model = None+ # ANN instance+ ann = Nonebackend = config.get("backend", "faiss")# Create ANN instanceif backend == "annoy":- if not ANNOY:- raise ImportError('annoy library is not available - install "similarity" extra to enable')-- model = Annoy(config)+ ann = Annoy(config)elif backend == "hnsw":- if not HNSWLIB:- raise ImportError('hnswlib library is not available - install "similarity" extra to enable')-- model = HNSW(config)+ ann = HNSW(config)else:- model = Faiss(config)+ ann = Faiss(config)# Store config backconfig["backend"] = backend- return model+ return anndiff --git a/src/python/txtai/ann/faiss.py b/src/python/txtai/ann/faiss.pyindex e64cbb5e..82571105 100644--- a/src/python/txtai/ann/faiss.py+++ b/src/python/txtai/ann/faiss.py@@ -13,23 +13,23 @@ from .base import ANNclass Faiss(ANN):"""- Builds an ANN model using the Faiss library.+ Builds an ANN index using the Faiss library."""def load(self, path):# Load index- self.model = read_index(path, IO_FLAG_MMAP if self.setting("mmap") is True else 0)+ self.backend = read_index(path, IO_FLAG_MMAP if self.setting("mmap") is True else 0)def index(self, embeddings):# Configure embeddings index. Inner product is equal to cosine similarity on normalized vectors.params = self.configure(embeddings.shape[0])- self.model = index_factory(embeddings.shape[1], params, METRIC_INNER_PRODUCT)+ self.backend = index_factory(embeddings.shape[1], params, METRIC_INNER_PRODUCT)# Train model- self.model.train(embeddings)+ self.backend.train(embeddings)# Add embeddings - position in embeddings is used as the id- self.model.add_with_ids(embeddings, np.arange(embeddings.shape[0], dtype=np.int64))+ self.backend.add_with_ids(embeddings, np.arange(embeddings.shape[0], dtype=np.int64))# Add id offset and index build metadataself.config["offset"] = embeddings.shape[0]@@ -39,7 +39,7 @@ class Faiss(ANN):new = embeddings.shape[0]# Append new ids - position in embeddings + existing offset is used as the id- self.model.add_with_ids(embeddings, np.arange(self.config["offset"], self.config["offset"] + new, dtype=np.int64))+ self.backend.add_with_ids(embeddings, np.arange(self.config["offset"], self.config["offset"] + new, dtype=np.int64))# Update id offset and index metadataself.config["offset"] += new@@ -47,12 +47,12 @@ class Faiss(ANN):def delete(self, ids):# Remove specified ids- self.model.remove_ids(np.array(ids, dtype=np.int64))+ self.backend.remove_ids(np.array(ids, dtype=np.int64))def search(self, queries, limit):# Run the query- self.model.nprobe = self.nprobe()- scores, ids = self.model.search(queries, limit)+ self.backend.nprobe = self.nprobe()+ scores, ids = self.backend.search(queries, limit)# Map results to [(id, score)]results = []@@ -62,11 +62,11 @@ class Faiss(ANN):return resultsdef count(self):- return self.model.ntotal+ return self.backend.ntotaldef save(self, path):# Write index- write_index(self.model, path)+ write_index(self.backend, path)def configure(self, count):"""diff --git a/src/python/txtai/ann/hnsw.py b/src/python/txtai/ann/hnsw.pyindex ac6d217c..3f029f44 100644--- a/src/python/txtai/ann/hnsw.py+++ b/src/python/txtai/ann/hnsw.py@@ -18,13 +18,19 @@ from .base import ANNclass HNSW(ANN):"""- Builds an ANN model using the hnswlib library.+ Builds an ANN index using the hnswlib library."""+ def __init__(self, config):+ super().__init__(config)++ if not HNSWLIB:+ raise ImportError('HNSW is not available - install "similarity" extra to enable')+def load(self, path):# Load index- self.model = Index(dim=self.config["dimensions"], space=self.config["metric"])- self.model.load_index(path)+ self.backend = Index(dim=self.config["dimensions"], space=self.config["metric"])+ self.backend.load_index(path)def index(self, embeddings):# Inner product is equal to cosine similarity on normalized vectors@@ -36,11 +42,11 @@ class HNSW(ANN):seed = self.setting("randomseed", 100)# Create index- self.model = Index(dim=self.config["dimensions"], space=self.config["metric"])- self.model.init_index(max_elements=embeddings.shape[0], ef_construction=efconstruction, M=m, random_seed=seed)+ self.backend = Index(dim=self.config["dimensions"], space=self.config["metric"])+ self.backend.init_index(max_elements=embeddings.shape[0], ef_construction=efconstruction, M=m, random_seed=seed)# Add items - position in embeddings is used as the id- self.model.add_items(embeddings, np.arange(embeddings.shape[0]))+ self.backend.add_items(embeddings, np.arange(embeddings.shape[0]))# Add id offset, delete counter and index build metadataself.config["offset"] = embeddings.shape[0]@@ -51,10 +57,10 @@ class HNSW(ANN):new = embeddings.shape[0]# Resize index- self.model.resize_index(self.config["offset"] + new)+ self.backend.resize_index(self.config["offset"] + new)# Append new ids - position in embeddings + existing offset is used as the id- self.model.add_items(embeddings, np.arange(self.config["offset"], self.config["offset"] + new))+ self.backend.add_items(embeddings, np.arange(self.config["offset"], self.config["offset"] + new))# Update id offset and index metadataself.config["offset"] += new@@ -64,7 +70,7 @@ class HNSW(ANN):# Mark elements as deleted to omit from search resultsfor uid in ids:try:- self.model.mark_deleted(uid)+ self.backend.mark_deleted(uid)self.config["deletes"] += 1except RuntimeError:# Ignore label not found error@@ -74,10 +80,10 @@ class HNSW(ANN):# Set ef query paramef = self.setting("efsearch")if ef:- self.model.set_ef(ef)+ self.backend.set_ef(ef)# Run the query- ids, distances = self.model.knn_query(queries, k=limit)+ ids, distances = self.backend.knn_query(queries, k=limit)# Map results to [(id, score)]results = []@@ -91,8 +97,8 @@ class HNSW(ANN):return resultsdef count(self):- return self.model.get_current_count() - self.config["deletes"]+ return self.backend.get_current_count() - self.config["deletes"]def save(self, path):# Write index- self.model.save_index(path)+ self.backend.save_index(path)