💡 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
Change default embeddings config to json, closes #652, Store index ids outside of config when content is disabled, closes #653.
davidmezzetti168f7e4efdfd
diff --git a/docs/embeddings/configuration/general.md b/docs/embeddings/configuration/general.mdindex 803e4009..3c66e2fc 100644--- a/docs/embeddings/configuration/general.md+++ b/docs/embeddings/configuration/general.md@@ -41,7 +41,7 @@ Sets the `text` and `object` column names. Defaults to `text` and `object` if no## format```yaml-format: pickle|json+format: json|pickle```-Sets the configuration storage format. Defaults to `pickle`.+Sets the configuration storage format. Defaults to `json`.diff --git a/src/python/txtai/embeddings/base.py b/src/python/txtai/embeddings/base.pyindex d99a4a12..6daa3a90 100644--- a/src/python/txtai/embeddings/base.py+++ b/src/python/txtai/embeddings/base.py@@ -19,7 +19,7 @@ from ..scoring import ScoringFactoryfrom ..vectors import VectorsFactoryfrom ..version import __pickle__-from .index import Action, Functions, Indexes, Reducer, Stream, Transform+from .index import Action, Functions, Indexes, IndexIds, Reducer, Stream, Transformfrom .search import Explain, Ids, Query, Search, Terms@@ -54,6 +54,9 @@ class Embeddings:# Approximate nearest neighbor indexself.ann = None+ # Index ids when content is disabled+ self.ids = None+# Document databaseself.database = None@@ -132,7 +135,7 @@ class Embeddings:# Save indexids-ids mapping for indexes with no database, except when this is a reindexif ids and not reindex and not self.database:- self.config["ids"] = ids+ self.ids = self.createids(ids)# Index scoring, if necessary# This must occur before graph index in order to be available to the graph@@ -179,7 +182,7 @@ class Embeddings:# Save indexids-ids mapping for indexes with no databaseif ids and not self.database:- self.config["ids"] = self.config["ids"] + ids+ self.ids = self.createids(self.ids + ids)# Scoring upsert, if necessary# This must occur before graph upsert in order to be available to the graph@@ -222,17 +225,14 @@ class Embeddings:# Delete ids from databaseself.database.delete(deletes)elif self.ann or self.scoring:- # Lookup indexids from config for indexes with no database- indexids = self.config["ids"]-# Find existing idsfor uid in ids:- indices.extend([index for index, value in enumerate(indexids) if uid == value])+ indices.extend([index for index, value in enumerate(self.ids) if uid == value])- # Clear config ids+ # Clear embeddings idsfor index in indices:- deletes.append(indexids[index])- indexids[index] = None+ deletes.append(self.ids[index])+ self.ids[index] = None# Delete indices for all indexes and data storesif indices:@@ -338,8 +338,8 @@ class Embeddings:return self.scoring.count()if self.database:return self.database.count()- if self.config.get("ids"):- return len([uid for uid in self.config["ids"] if uid is not None])+ if self.ids:+ return len([uid for uid in self.ids if uid is not None])# Default to 0 when no suitable method foundreturn 0@@ -554,6 +554,11 @@ class Embeddings:self.reducer = Reducer()self.reducer.load(f"{path}/lsa")+ # Index ids when content is disabled+ self.ids = self.createids()+ if self.ids:+ self.ids.load(f"{path}/ids")+# Document database - stores document contentself.database = self.createdatabase()if self.database:@@ -615,6 +620,10 @@ class Embeddings:if self.reducer:self.reducer.save(f"{path}/lsa")+ # Save index ids+ if self.ids:+ self.ids.save(f"{path}/ids")+# Save document databaseif self.database:self.database.save(f"{path}/documents")@@ -647,6 +656,7 @@ class Embeddings:self.ann, self.config, self.graph, self.archive = None, None, None, Noneself.reducer, self.query, self.model, self.models = None, None, None, None+ self.ids = None# Close database connection if openif self.database:@@ -743,6 +753,9 @@ class Embeddings:# Initialize default parameters, if necessaryself.defaults()+ # Initialize index ids, only created when content is disabled+ self.ids = None+# Create document database, if necessaryif not reindex:self.database = self.createdatabase()@@ -817,9 +830,12 @@ class Embeddings:name = "config.json" if jsonconfig else "config"# Load configuration- with open(f"{path}/{name}", "r" if jsonconfig else "rb") as handle:+ with open(f"{path}/{name}", "r" if jsonconfig else "rb", encoding="utf-8" if jsonconfig else None) as handle:config = json.load(handle) if jsonconfig else pickle.load(handle)+ # Add format parameter+ config["format"] = "json" if jsonconfig else "pickle"+# Build full path to embedding vectors fileif config.get("storevectors"):config["path"] = os.path.join(path, config["path"])@@ -828,7 +844,7 @@ class Embeddings:def saveconfig(self, path):"""- Saves index configuration. This method saves to JSON if possible, otherwise it falls back to pickle.+ Saves index configuration. This method defaults to JSON and falls back to pickle.Args:path: path to directory@@ -837,8 +853,8 @@ class Embeddings:dict"""- # Default to pickle config- jsonconfig = self.config.get("format", "pickle") == "json"+ # Default to JSON config+ jsonconfig = self.config.get("format", "json") == "json"# Set config file namename = "config.json" if jsonconfig else "config"@@ -978,6 +994,20 @@ class Embeddings:return None+ def createids(self, ids=None):+ """+ Creates indexids when content is disabled.++ Args:+ ids: optional ids to add++ Returns:+ new indexids, if content disabled+ """++ # Load index ids when content is disabled+ return IndexIds(self, ids) if not self.config.get("content") else None+def createindexes(self):"""Creates subindexes from config.diff --git a/src/python/txtai/embeddings/index/__init__.py b/src/python/txtai/embeddings/index/__init__.pyindex a68599e1..9778aa60 100644--- a/src/python/txtai/embeddings/index/__init__.py+++ b/src/python/txtai/embeddings/index/__init__.py@@ -8,6 +8,7 @@ from .autoid import AutoIdfrom .documents import Documentsfrom .functions import Functionsfrom .indexes import Indexes+from .indexids import IndexIdsfrom .reducer import Reducerfrom .stream import Streamfrom .transform import Transformdiff --git a/src/python/txtai/embeddings/index/indexids.py b/src/python/txtai/embeddings/index/indexids.pynew file mode 100644index 00000000..3a1e4785--- /dev/null+++ b/src/python/txtai/embeddings/index/indexids.py@@ -0,0 +1,64 @@+"""+IndexIds module+"""++import pickle++from ...version import __pickle__+++class IndexIds:+ """+ Stores index ids when content is disabled.+ """++ def __init__(self, embeddings, ids=None):+ """+ Creates an IndexIds instance.++ Args:+ embeddings: embeddings instance+ ids: ids to store+ """++ self.config = embeddings.config+ self.ids = ids++ def __iter__(self):+ yield from self.ids++ def __getitem__(self, index):+ return self.ids[index]++ def __setitem__(self, index, value):+ self.ids[index] = value++ def __add__(self, ids):+ return self.ids + ids++ def load(self, path):+ """+ Loads IndexIds from path.++ Args:+ path: path to load+ """++ if "ids" in self.config:+ # Legacy ids format+ self.ids = self.config.pop("ids")+ else:+ # Standard ids format+ with open(path, "rb") as handle:+ self.ids = pickle.load(handle)++ def save(self, path):+ """+ Saves IndexIds to path.++ Args:+ path: path to save+ """++ with open(path, "wb") as handle:+ pickle.dump(self.ids, handle, protocol=__pickle__)diff --git a/src/python/txtai/embeddings/search/base.py b/src/python/txtai/embeddings/search/base.pyindex 5d93d155..3b686d22 100644--- a/src/python/txtai/embeddings/search/base.py+++ b/src/python/txtai/embeddings/search/base.py@@ -31,8 +31,8 @@ class Search:# Alias embeddings attributesself.ann = embeddings.annself.batchtransform = embeddings.batchtransform- self.config = embeddings.configself.database = embeddings.database+ self.ids = embeddings.idsself.indexes = embeddings.indexesself.query = embeddings.queryself.scoring = embeddings.scoring if embeddings.issparse() else None@@ -203,10 +203,9 @@ class Search:results with resolved ids"""- # Map indexids to ids if "ids" available- if not self.indexids and "ids" in self.config:- lookup = self.config["ids"]- return [[(lookup[i], score) for i, score in r] for r in results]+ # Map indexids to ids if embeddings ids are available+ if not self.indexids and self.ids:+ return [[(self.ids[i], score) for i, score in r] for r in results]return resultsdiff --git a/src/python/txtai/embeddings/search/ids.py b/src/python/txtai/embeddings/search/ids.pyindex 4dc207fe..677dec80 100644--- a/src/python/txtai/embeddings/search/ids.py+++ b/src/python/txtai/embeddings/search/ids.py@@ -16,8 +16,8 @@ class Ids:embeddings: embeddings instance"""- self.config = embeddings.configself.database = embeddings.database+ self.ids = embeddings.idsdef __call__(self, ids):"""@@ -30,7 +30,7 @@ class Ids:internal ids"""- # Resolve ids using database if available, otherwise fallback to config+ # Resolve ids using database if available, otherwise fallback to embeddings idsresults = self.database.ids(ids) if self.database else self.scan(ids)# Create dict of id: [iids] given there is a one to many relationship@@ -44,7 +44,7 @@ class Ids:def scan(self, ids):"""- Scans config ids array for matches when content is disabled.+ Scans embeddings ids array for matches when content is disabled.Args:ids: search ids@@ -56,6 +56,6 @@ class Ids:# Find existing idsindices = []for uid in ids:- indices.extend([(index, value) for index, value in enumerate(self.config["ids"]) if uid == value])+ indices.extend([(index, value) for index, value in enumerate(self.ids) if uid == value])return indicesdiff --git a/test/python/testdatabase/testrdbms.py b/test/python/testdatabase/testrdbms.pyindex 04ac080f..92ea3771 100644--- a/test/python/testdatabase/testrdbms.py+++ b/test/python/testdatabase/testrdbms.py@@ -355,33 +355,6 @@ class Common:with self.assertRaises(ValueError):self.embeddings.index([(0, {"text": "This is a test", "flag": float("NaN")}, None)])- def testJSON(self):- """- Test JSON configuration- """-- embeddings = Embeddings(- {- "format": "json",- "path": "sentence-transformers/nli-mpnet-base-v2",- "content": self.backend,- }- )-- embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])-- # Generate temp file path- index = os.path.join(tempfile.gettempdir(), f"embeddings.{self.category()}.json")-- embeddings.save(index)-- # Check that config.json exists- self.assertTrue(os.path.exists(os.path.join(index, "config.json")))-- # Check that index can be reloaded- embeddings.load(index)- self.assertEqual(embeddings.count(), 6)-def testKeyword(self):"""Test keyword only (sparse) search@@ -521,6 +494,33 @@ class Common:obj = embeddings.search("select object from txtai where id = 0")[0]["object"]self.assertEqual(str(obj.getvalue(), "utf-8"), "binary data")+ def testPickle(self):+ """+ Test pickle configuration+ """++ embeddings = Embeddings(+ {+ "format": "pickle",+ "path": "sentence-transformers/nli-mpnet-base-v2",+ "content": self.backend,+ }+ )++ embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])++ # Generate temp file path+ index = os.path.join(tempfile.gettempdir(), f"embeddings.{self.category()}.pickle")++ embeddings.save(index)++ # Check that config exists+ self.assertTrue(os.path.exists(os.path.join(index, "config")))++ # Check that index can be reloaded+ embeddings.load(index)+ self.assertEqual(embeddings.count(), 6)+def testQuantize(self):"""Test scalar quantizationdiff --git a/test/python/testembeddings.py b/test/python/testembeddings.pyindex 01e340d9..fb7dd20e 100644--- a/test/python/testembeddings.py+++ b/test/python/testembeddings.py@@ -2,6 +2,7 @@Embeddings module tests"""+import jsonimport osimport tempfileimport unittest@@ -217,6 +218,38 @@ class TestEmbeddings(unittest.TestCase):uid = embeddings.search("feel good story", 1)[0][0]self.assertEqual(uid, 0)+ def testIds(self):+ """+ Test legacy config ids loading+ """++ # Create an index for the list of text+ self.embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])++ # Generate temp file path+ index = os.path.join(tempfile.gettempdir(), "embeddings.ids")++ # Save index+ self.embeddings.save(index)++ # Set ids on config to simulate legacy ids format+ with open(f"{index}/config.json", "r", encoding="utf-8") as handle:+ config = json.load(handle)+ config["ids"] = list(range(len(self.data)))++ with open(f"{index}/config.json", "w", encoding="utf-8") as handle:+ json.dump(config, handle, default=str, indent=2)++ # Reload index+ self.embeddings.load(index)++ # Run search+ uid = self.embeddings.search("feel good story", 1)[0][0]+ self.assertEqual(uid, 4)++ # Check that ids is not in config+ self.assertTrue("ids" not in self.embeddings.config)+def testIndex(self):"""Test index@@ -396,7 +429,7 @@ class TestEmbeddings(unittest.TestCase):# Reset embeddings for testself.embeddings.ann = None- del self.embeddings.config["ids"]+ self.embeddings.ids = None# Create an index for the list of textself.embeddings.upsert(data)diff --git a/test/python/testvectors/testwordvectors.py b/test/python/testvectors/testwordvectors.pyindex 75a6ce5f..ee8f99ee 100644--- a/test/python/testvectors/testwordvectors.py+++ b/test/python/testvectors/testwordvectors.py@@ -42,7 +42,6 @@ class TestWordVectors(unittest.TestCase):self.assertFalse(model.initialized)- config["ids"] = ["0", "1"]config["dimensions"] = 10model = VectorsFactory.create(config, None)