Skip to content

armgit / txtai

Public Imported from GitHub
0

💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows

Add support for configurable text/object fields, closes #512

davidmezzetti20d8df17b095
diff --git a/src/python/txtai/database/base.py b/src/python/txtai/database/base.py
index dc8a0400..576e12ee 100644
--- a/src/python/txtai/database/base.py
+++ b/src/python/txtai/database/base.py
@@ -37,6 +37,11 @@ class Database:
encoder = self.config.get("objects")
self.encoder = EncoderFactory.create(encoder) if encoder else None
+ # Transform columns
+ columns = config.get("columns", {})
+ self.text = columns.get("text", "text")
+ self.object = columns.get("object", "object")
+
# Custom functions and expressions
self.functions, self.expressions = None, None
diff --git a/src/python/txtai/database/filedb.py b/src/python/txtai/database/filedb.py
index 2aacd000..dcc45d5b 100644
--- a/src/python/txtai/database/filedb.py
+++ b/src/python/txtai/database/filedb.py
@@ -371,18 +371,18 @@ class FileDB(Database):
document = document.copy()
# Get and remove object field from document
- obj = document.pop("object") if "object" in document else None
+ obj = document.pop(self.object) if self.object in document else None
# Insert document as JSON
if document:
self.cursor.execute(FileDB.INSERT_DOCUMENT, [uid, json.dumps(document, allow_nan=False), tags, entry])
# If text and object are both available, insert object as it won't otherwise be used
- if "text" in document and obj:
+ if self.text in document and obj:
self.insertobject(uid, obj, tags, entry)
# Return value to use for section - use text if available otherwise use object
- return document["text"] if "text" in document else obj
+ return document[self.text] if self.text in document else obj
def insertobject(self, uid, obj, tags, entry):
"""
diff --git a/src/python/txtai/embeddings/base.py b/src/python/txtai/embeddings/base.py
index 19770bb8..afbe6ff5 100644
--- a/src/python/txtai/embeddings/base.py
+++ b/src/python/txtai/embeddings/base.py
@@ -138,14 +138,15 @@ class Embeddings:
if ids and not reindex and not self.database:
self.config["ids"] = ids
- # Index graph, if necessary
- if self.graph:
- self.graph.index(Search(self, True), self.batchsimilarity)
-
# Index scoring, if necessary
+ # This must occur before graph index in order to be available to the graph
if self.issparse():
self.scoring.index()
+ # Index graph, if necessary
+ if self.graph:
+ self.graph.index(Search(self, True), self.batchsimilarity)
+
def upsert(self, documents):
"""
Runs an embeddings upsert operation. If the index exists, new data is
@@ -183,14 +184,15 @@ class Embeddings:
if ids and not self.database:
self.config["ids"] = self.config["ids"] + ids
- # Graph upsert, if necessary
- if self.graph:
- self.graph.upsert(Search(self, True), self.batchsimilarity)
-
# Scoring upsert, if necessary
+ # This must occur before graph upsert in order to be available to the graph
if self.issparse():
self.scoring.upsert()
+ # Graph upsert, if necessary
+ if self.graph:
+ self.graph.upsert(Search(self, True), self.batchsimilarity)
+
def delete(self, ids):
"""
Deletes from an embeddings index. Returns list of ids deleted.
@@ -231,20 +233,20 @@ class Embeddings:
deletes.append(indexids[index])
indexids[index] = None
- # Delete indices from ann embeddings
+ # Delete indices for all indexes and data stores
if indices:
+ # Delete ids from ann
if self.isdense():
- # Delete ids from ANN
self.ann.delete(indices)
- # Delete ids from graph
- if self.graph:
- self.graph.delete(indices)
-
# Delete ids from scoring
if self.issparse():
self.scoring.delete(indices)
+ # Delete ids from graph
+ if self.graph:
+ self.graph.delete(indices)
+
return deletes
def reindex(self, config, columns=None, function=None):
@@ -886,7 +888,12 @@ class Embeddings:
new graph, if enabled in config
"""
- return GraphFactory.create(self.config["graph"]) if "graph" in self.config else None
+ if "graph" in self.config:
+ # Create configuration with custom columns, if necessary
+ config = self.columns(self.config["graph"])
+ return GraphFactory.create(config)
+
+ return None
def createscoring(self):
"""
@@ -900,7 +907,37 @@ class Embeddings:
if self.scoring:
self.scoring.close()
- return ScoringFactory.create(self.config["scoring"]) if "scoring" in self.config else None
+ if "scoring" in self.config:
+ # Expand scoring to a dictionary, if necessary
+ config = self.config["scoring"]
+ config = config if isinstance(config, dict) else {"method": config}
+
+ # Create configuration with custom columns, if necessary
+ config = self.columns(config)
+ return ScoringFactory.create(config)
+
+ return None
+
+ def columns(self, config):
+ """
+ Adds custom text/object column information if it's provided.
+
+ Args:
+ config: input configuration
+
+ Returns:
+ config with column information added
+ """
+
+ # Add text/object columns if custom
+ if "columns" in self.config:
+ # Work on copy of configuration
+ config = config.copy()
+
+ # Copy columns to config
+ config["columns"] = self.config["columns"]
+
+ return config
def normalize(self, embeddings):
"""
diff --git a/src/python/txtai/embeddings/transform.py b/src/python/txtai/embeddings/transform.py
index f8c7bd0b..26babe8c 100644
--- a/src/python/txtai/embeddings/transform.py
+++ b/src/python/txtai/embeddings/transform.py
@@ -38,6 +38,11 @@ class Transform:
self.offset = embeddings.config.get("offset", 0) if action == Action.UPSERT else 0
self.batch = embeddings.config.get("batch", 1024)
+ # Transform columns
+ columns = embeddings.config.get("columns", {})
+ self.text = columns.get("text", "text")
+ self.object = columns.get("object", "object")
+
# List of deleted ids with this action
self.deletes = set()
@@ -122,7 +127,7 @@ class Transform:
2. Batch and load original documents into enabled data stores (database, graph, scoring)
Documents are yielded for vectorization if one of the following is True:
- - dict with the field "text" or "object"
+ - dict with a text or object field
- not a dict
Otherwise, documents are only batched and inserted into data stores
@@ -137,11 +142,11 @@ class Transform:
# Iterate and process documents stream
for document in documents:
if isinstance(document[1], dict):
- if "text" in document[1]:
- yield (document[0], document[1]["text"], document[2])
+ if self.text in document[1]:
+ yield (document[0], document[1][self.text], document[2])
offset += 1
- elif "object" in document[1]:
- yield (document[0], document[1]["object"], document[2])
+ elif self.object in document[1]:
+ yield (document[0], document[1][self.object], document[2])
offset += 1
else:
yield document
diff --git a/src/python/txtai/graph/base.py b/src/python/txtai/graph/base.py
index d99b39c9..fdd863e7 100644
--- a/src/python/txtai/graph/base.py
+++ b/src/python/txtai/graph/base.py
@@ -40,6 +40,11 @@ class Graph:
self.categories = None
self.topics = None
+ # Transform columns
+ columns = config.get("columns", {})
+ self.text = columns.get("text", "text")
+ self.object = columns.get("object", "object")
+
def create(self):
"""
Creates the graph network.
@@ -353,7 +358,7 @@ class Graph:
for _, document, _ in documents:
if isinstance(document, dict):
# Require text or object field
- document = document.get("text", document.get("object"))
+ document = document.get(self.text, document.get(self.object))
if document is not None:
if isinstance(document, list):
diff --git a/src/python/txtai/scoring/base.py b/src/python/txtai/scoring/base.py
index d6659aa9..1e3443da 100644
--- a/src/python/txtai/scoring/base.py
+++ b/src/python/txtai/scoring/base.py
@@ -54,6 +54,11 @@ class Scoring:
# Tokenizer, lazily loaded as needed
self.tokenizer = None
+ # Transform columns
+ columns = config.get("columns", {})
+ self.text = columns.get("text", "text")
+ self.object = columns.get("object", "object")
+
# Term index
self.terms = Terms(self.config["terms"], self.score, self.idf) if self.config.get("terms") else None
@@ -77,7 +82,7 @@ class Scoring:
for uid, document, tags in documents:
# Extract text, if necessary
if isinstance(document, dict):
- document = document.get("text", document.get("object"))
+ document = document.get(self.text, document.get(self.object))
if document is not None:
# If index is passed, use indexid, otherwise use id
diff --git a/test/python/testdatabase/testsqlite.py b/test/python/testdatabase/testsqlite.py
index a3af60b4..0abe1211 100644
--- a/test/python/testdatabase/testsqlite.py
+++ b/test/python/testdatabase/testsqlite.py
@@ -78,18 +78,31 @@ class TestSQLite(unittest.TestCase):
"""
# Default sequence id
- embeddings = Embeddings()
+ embeddings = Embeddings(path="sentence-transformers/nli-mpnet-base-v2", content=True)
embeddings.index(self.data)
- uid = embeddings.search(self.data[4], 1)[0][0]
- self.assertEqual(uid, 4)
+ result = embeddings.search("feel good story", 1)[0]
+ self.assertEqual(result["text"], self.data[4])
# UUID
- embeddings = Embeddings(autoid="uuid4")
+ embeddings = Embeddings(autoid="uuid4", path="sentence-transformers/nli-mpnet-base-v2", content=True)
embeddings.index(self.data)
- uid = embeddings.search(self.data[4], 1)[0][0]
- self.assertEqual(len(uid), 36)
+ result = embeddings.search(self.data[4], 1)[0]
+ self.assertEqual(len(result["id"]), 36)
+
+ def testColumns(self):
+ """
+ Test custom text/object columns
+ """
+
+ embeddings = Embeddings({"keyword": True, "content": self.backend, "columns": {"text": "value"}})
+ data = [{"value": x} for x in self.data]
+ embeddings.index([(uid, text, None) for uid, text in enumerate(data)])
+
+ # Run search
+ result = embeddings.search("lottery", 1)[0]
+ self.assertEqual(result["text"], self.data[4])
def testClose(self):
"""
diff --git a/test/python/testembeddings.py b/test/python/testembeddings.py
index e1763546..497f3967 100644
--- a/test/python/testembeddings.py
+++ b/test/python/testembeddings.py
@@ -65,6 +65,19 @@ class TestEmbeddings(unittest.TestCase):
uid = embeddings.search(self.data[4], 1)[0][0]
self.assertEqual(len(uid), 36)
+ def testColumns(self):
+ """
+ Test custom text/object columns
+ """
+
+ embeddings = Embeddings({"keyword": True, "columns": {"text": "value"}})
+ data = [{"value": x} for x in self.data]
+ embeddings.index([(uid, text, None) for uid, text in enumerate(data)])
+
+ # Run search
+ uid = embeddings.search("lottery", 1)[0][0]
+ self.assertEqual(uid, 4)
+
def testDefaults(self):
"""
Test default configuration