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 application reindex method, closes #547. Add weights and index parameters, closes #561

davidmezzetti46ee7a34e12d
diff --git a/src/python/txtai/api/base.py b/src/python/txtai/api/base.py
index 404dae47..dd083df6 100644
--- a/src/python/txtai/api/base.py
+++ b/src/python/txtai/api/base.py
@@ -23,21 +23,23 @@ class API(Application):
self.cluster = Cluster(self.config["cluster"])
# pylint: disable=W0221
- def search(self, query, limit=None, request=None):
+ def search(self, query, limit=None, weights=None, index=None, request=None):
# When search is invoked via the API, limit is set from the request
# When search is invoked directly, limit is set using the method parameter
limit = self.limit(request.query_params.get("limit") if request and hasattr(request, "query_params") else limit)
+ weights = self.weights(request.query_params.get("weights") if request and hasattr(request, "query_params") else weights)
+ index = request.query_params.get("index") if request and hasattr(request, "query_params") else index
if self.cluster:
- return self.cluster.search(query, limit)
+ return self.cluster.search(query, limit, weights, index)
- return super().search(query, limit)
+ return super().search(query, limit, weights, index)
- def batchsearch(self, queries, limit=None):
+ def batchsearch(self, queries, limit=None, weights=None, index=None):
if self.cluster:
- return self.cluster.batchsearch(queries, self.limit(limit))
+ return self.cluster.batchsearch(queries, self.limit(limit), weights, index)
- return super().batchsearch(queries, limit)
+ return super().batchsearch(queries, limit, weights, index)
def add(self, documents):
"""
@@ -95,6 +97,20 @@ class API(Application):
return super().delete(ids)
+ def reindex(self, config, function=None):
+ """
+ Recreates this embeddings index using config. This method only works if document content storage is enabled.
+
+ Args:
+ config: new config
+ function: optional function to prepare content for indexing
+ """
+
+ if self.cluster:
+ self.cluster.reindex(config, function)
+ else:
+ super().reindex(config, function)
+
def count(self):
"""
Total number of elements in this embeddings index.
@@ -121,3 +137,16 @@ class API(Application):
# Return between 1 and 250 results, defaults to 10
return max(1, min(250, int(limit) if limit else 10))
+
+ def weights(self, weights):
+ """
+ Parses the weights parameter from the request.
+
+ Args:
+ weights: weights parameter
+
+ Returns:
+ weights
+ """
+
+ return float(weights) if weights else weights
diff --git a/src/python/txtai/api/cluster.py b/src/python/txtai/api/cluster.py
index e3f3c14a..0df158aa 100644
--- a/src/python/txtai/api/cluster.py
+++ b/src/python/txtai/api/cluster.py
@@ -3,6 +3,7 @@ Cluster module
"""
import asyncio
+import random
import urllib.parse
import zlib
@@ -36,24 +37,29 @@ class Cluster:
# Query aggregator
self.aggregate = Aggregate()
- def search(self, query, limit=None):
+ def search(self, query, limit=None, weights=None, index=None):
"""
- Finds documents in the embeddings cluster most similar to the input query. Returns
- a list of {id: value, score: value} sorted by highest score, where id is the
- document id in the embeddings model.
+ Finds documents most similar to the input query. This method will run either an index search
+ or an index + database search depending on if a database is available.
Args:
- query: query text
+ query: input query
limit: maximum results
+ weights: hybrid score weights, if applicable
+ index: index name, if applicable
Returns:
- list of {id: value, score: value}
+ list of {id: value, score: value} for index search, list of dict for an index + database search
"""
# Build URL
action = f"search?query={urllib.parse.quote_plus(query)}"
if limit:
action += f"&limit={limit}"
+ if weights:
+ action += f"&weights={weights}"
+ if index:
+ action += f"&index={index}"
# Run query and flatten results into single results list
results = []
@@ -66,24 +72,29 @@ class Cluster:
# Limit results
return results[: (limit if limit else 10)]
- def batchsearch(self, queries, limit=None):
+ def batchsearch(self, queries, limit=None, weights=None, index=None):
"""
- Finds documents in the embeddings cluster most similar to the input queries. Returns
- a list of {id: value, score: value} sorted by highest score per query, where id is
- the document id in the embeddings model.
+ Finds documents most similar to the input queries. This method will run either an index search
+ or an index + database search depending on if a database is available.
Args:
- queries: queries text
+ queries: input queries
limit: maximum results
+ weights: hybrid score weights, if applicable
+ index: index name, if applicable
Returns:
- list of {id: value, score: value} per query
+ list of {id: value, score: value} per query for index search, list of dict per query for an index + database search
"""
# POST parameters
params = {"queries": queries}
if limit:
params["limit"] = limit
+ if weights:
+ params["weights"] = weights
+ if index:
+ params["index"] = index
# Run query
batch = self.execute("post", "batchsearch", [params] * len(self.shards))
@@ -135,7 +146,18 @@ class Cluster:
ids deleted
"""
- return [uid for ids in self.execute("post", "delete", self.shard(ids)) for uid in ids]
+ return [uid for ids in self.execute("post", "delete", [ids] * len(self.shards)) for uid in ids]
+
+ def reindex(self, config, function=None):
+ """
+ Recreates this embeddings index using config. This method only works if document content storage is enabled.
+
+ Args:
+ config: new config
+ function: optional function to prepare content for indexing
+ """
+
+ self.execute("post", "reindex", [{"config": config, "function": function}] * len(self.shards))
def count(self):
"""
@@ -160,10 +182,13 @@ class Cluster:
shards = [[] for _ in range(len(self.shards))]
for document in documents:
- uid = document["id"] if isinstance(document, dict) else document
- if isinstance(uid, str):
+ uid = document.get("id") if isinstance(document, dict) else document
+ if uid and isinstance(uid, str):
# Quick int hash of string to help derive shard id
uid = zlib.adler32(uid.encode("utf-8"))
+ elif uid is None:
+ # Get random shard id when uid isn't set
+ uid = random.randint(0, len(shards) - 1)
shards[uid % len(self.shards)].append(document)
diff --git a/src/python/txtai/api/routers/embeddings.py b/src/python/txtai/api/routers/embeddings.py
index c40608e6..bc5c1874 100644
--- a/src/python/txtai/api/routers/embeddings.py
+++ b/src/python/txtai/api/routers/embeddings.py
@@ -15,37 +15,40 @@ router = APIRouter()
@router.get("/search")
def search(query: str, request: Request):
"""
- Finds documents in the embeddings model most similar to the input query. Returns
- a list of {id: value, score: value} sorted by highest score, where id is the
- document id in the embeddings model.
+ Finds documents most similar to the input query. This method will run either an index search
+ or an index + database search depending on if a database is available.
Args:
- query: query text
+ query: input query
request: FastAPI request
Returns:
- list of {id: value, score: value}
+ list of {id: value, score: value} for index search, list of dict for an index + database search
"""
return application.get().search(query, request=request)
+# pylint: disable=W0621
@router.post("/batchsearch")
-def batchsearch(queries: List[str] = Body(...), limit: int = Body(...)):
+def batchsearch(
+ queries: List[str] = Body(...), limit: int = Body(default=None), weights: float = Body(default=None), index: str = Body(default=None)
+):
"""
- Finds documents in the embeddings model most similar to the input queries. Returns
- a list of {id: value, score: value} sorted by highest score per query, where id is
- the document id in the embeddings model.
+ Finds documents most similar to the input queries. This method will run either an index search
+ or an index + database search depending on if a database is available.
Args:
- queries: queries text
+ queries: input queries
limit: maximum results
+ weights: hybrid score weights, if applicable
+ index: index name, if applicable
Returns:
- list of {id: value, score: value} per query
+ list of {id: value, score: value} per query for index search, list of dict per query for an index + database search
"""
- return application.get().batchsearch(queries, limit)
+ return application.get().batchsearch(queries, limit, weights, index)
@router.post("/add")
@@ -105,6 +108,22 @@ def delete(ids: List = Body(...)):
raise HTTPException(status_code=403, detail=e.args[0]) from e
[email protected]("/reindex")
+def reindex(config: dict = Body(...), function: str = Body(default=None)):
+ """
+ Recreates this embeddings index using config. This method only works if document content storage is enabled.
+
+ Args:
+ config: new config
+ function: optional function to prepare content for indexing
+ """
+
+ try:
+ application.get().reindex(config, function)
+ except ReadOnlyError as e:
+ raise HTTPException(status_code=403, detail=e.args[0]) from e
+
+
@router.get("/count")
def count():
"""
diff --git a/src/python/txtai/app/base.py b/src/python/txtai/app/base.py
index 61d8a659..e9500e3b 100644
--- a/src/python/txtai/app/base.py
+++ b/src/python/txtai/app/base.py
@@ -289,46 +289,48 @@ class Application:
# Attempt to resolve action as a callable function
return PipelineFactory.create({}, function)
- def search(self, query, limit=10):
+ def search(self, query, limit=10, weights=None, index=None):
"""
- Finds documents in the embeddings model most similar to the input query. Returns
- a list of {id: value, score: value} sorted by highest score, where id is the
- document id in the embeddings model.
+ Finds documents most similar to the input query. This method will run either an index search
+ or an index + database search depending on if a database is available.
Args:
- query: query text
- limit: maximum results, used if request is None
+ query: input query
+ limit: maximum results
+ weights: hybrid score weights, if applicable
+ index: index name, if applicable
Returns:
- list of {id: value, score: value}
+ list of {id: value, score: value} for index search, list of dict for an index + database search
"""
if self.embeddings:
with self.lock:
- results = self.embeddings.search(query, limit)
+ results = self.embeddings.search(query, limit, weights, index)
# Unpack (id, score) tuple, if necessary. Otherwise, results are dictionaries.
return [{"id": r[0], "score": float(r[1])} if isinstance(r, tuple) else r for r in results]
return None
- def batchsearch(self, queries, limit=10):
+ def batchsearch(self, queries, limit=10, weights=None, index=None):
"""
- Finds documents in the embeddings model most similar to the input queries. Returns
- a list of {id: value, score: value} sorted by highest score per query, where id is
- the document id in the embeddings model.
+ Finds documents most similar to the input queries. This method will run either an index search
+ or an index + database search depending on if a database is available.
Args:
- queries: queries text
+ queries: input queries
limit: maximum results
+ weights: hybrid score weights, if applicable
+ index: index name, if applicable
Returns:
- list of {id: value, score: value} per query
+ list of {id: value, score: value} per query for index search, list of dict per query for an index + database search
"""
if self.embeddings:
with self.lock:
- search = self.embeddings.batchsearch(queries, limit)
+ search = self.embeddings.batchsearch(queries, limit, weights, index)
results = []
for result in search:
@@ -434,6 +436,27 @@ class Application:
return None
+ def reindex(self, config, function=None):
+ """
+ Recreates embeddings index using config. This method only works if document content storage is enabled.
+
+ Args:
+ config: new config
+ function: optional function to prepare content for indexing
+ """
+
+ # Raise error if index is not writable
+ if not self.config.get("writable"):
+ raise ReadOnlyError("Attempting to reindex a read-only index (writable != True)")
+
+ if self.embeddings:
+ with self.lock:
+ # Resolve function, if necessary
+ function = self.function(function) if function and isinstance(function, str) else function
+
+ # Reindex
+ self.embeddings.reindex(config, function)
+
def count(self):
"""
Total number of elements in this embeddings index.
diff --git a/src/python/txtai/embeddings/base.py b/src/python/txtai/embeddings/base.py
index 01cf9d0d..92b02968 100644
--- a/src/python/txtai/embeddings/base.py
+++ b/src/python/txtai/embeddings/base.py
@@ -262,8 +262,7 @@ class Embeddings:
def reindex(self, config=None, function=None, **kwargs):
"""
- Recreates the approximate nearest neighbor (ann) index using config. This method only works if document
- content storage is enabled.
+ Recreates embeddings index using config. This method only works if document content storage is enabled.
Args:
config: new config
@@ -356,7 +355,7 @@ class Embeddings:
def search(self, query, limit=None, weights=None, index=None):
"""
- Finds documents most similar to the input queries. This method will run either an index search
+ Finds documents most similar to the input query. This method will run either an index search
or an index + database search depending on if a database is available.
Args:
@@ -366,7 +365,7 @@ class Embeddings:
index: index name, if applicable
Returns:
- list of (id, score) for index search, list of dict for an index+database search
+ list of (id, score) for index search, list of dict for an index + database search
"""
results = self.batchsearch([query], limit, weights, index)
@@ -384,7 +383,7 @@ class Embeddings:
index: index name, if applicable
Returns:
- list of (id, score) per query for index search, list of dict per query for an index+database search
+ list of (id, score) per query for index search, list of dict per query for an index + database search
"""
return Search(self)(queries, limit, weights, index)
diff --git a/test/python/testapi/testcluster.py b/test/python/testapi/testcluster.py
index 538b1dab..c89ad3f4 100644
--- a/test/python/testapi/testcluster.py
+++ b/test/python/testapi/testcluster.py
@@ -73,7 +73,10 @@ class RequestHandler(BaseHTTPRequestHandler):
if self.path.startswith("/batchsearch"):
response = [[{"id": 4, "score": 0.40}], [{"id": 1, "score": 0.40}]]
elif self.path.startswith("/delete"):
- response = [0]
+ if self.server.server_port == 8002:
+ response = [0]
+ else:
+ response = []
else:
response = {"result": "ok"}
@@ -160,18 +163,38 @@ class TestCluster(unittest.TestCase):
def testDeleteString(self):
"""
- Test string id
+ Test cluster delete with string id
"""
self.assertEqual(self.client.post("delete", json=["0"]).json(), [0])
+ def testIds(self):
+ """
+ Test id configurations
+ """
+
+ # String ids
+ self.client.post("add", json=[{"id": "0", "text": "test"}])
+ self.assertEqual(self.client.get("index").status_code, 200)
+
+ # Auto ids
+ self.client.post("add", json=[{"text": "test"}])
+ self.assertEqual(self.client.get("index").status_code, 200)
+
+ def testReindex(self):
+ """
+ Test cluster reindex
+ """
+
+ self.assertEqual(self.client.post("reindex", json={"config": {"path": "sentence-transformers/nli-mpnet-base-v2"}}).status_code, 200)
+
def testSearch(self):
"""
Test cluster search
"""
query = urllib.parse.quote("feel good story")
- uid = self.client.get(f"search?query={query}&limit=1").json()[0]["id"]
+ uid = self.client.get(f"search?query={query}&limit=1&weights=0.5&index=default").json()[0]["id"]
self.assertEqual(uid, 4)
def testSearchBatch(self):
@@ -179,7 +202,9 @@ class TestCluster(unittest.TestCase):
Test cluster batch search
"""
- results = self.client.post("batchsearch", json={"queries": ["feel good story", "climate change"], "limit": 1}).json()
+ results = self.client.post(
+ "batchsearch", json={"queries": ["feel good story", "climate change"], "limit": 1, "weights": 0.5, "index": "default"}
+ ).json()
uids = [result[0]["id"] for result in results]
self.assertEqual(uids, [4, 1])
diff --git a/test/python/testapi/testembeddings.py b/test/python/testapi/testembeddings.py
index 90e31491..e07df500 100644
--- a/test/python/testapi/testembeddings.py
+++ b/test/python/testapi/testembeddings.py
@@ -197,6 +197,24 @@ class TestEmbeddings(unittest.TestCase):
).json()
self.assertEqual("Flyers", answers[0]["answer"])
+ def testReindex(self):
+ """
+ Test reindex via API
+ """
+
+ # Reindex data
+ self.client.post("reindex", json={"config": {"path": "sentence-transformers/nli-mpnet-base-v2"}})
+
+ # Search for best match
+ query = urllib.parse.quote("feel good story")
+ uid = self.client.get(f"search?query={query}&limit=1").json()[0]["id"]
+
+ self.assertEqual(uid, 4)
+
+ # Reset data
+ self.client.post("add", json=[{"id": x, "text": row} for x, row in enumerate(self.data)])
+ self.client.get("index")
+
def testSearch(self):
"""
Test search via API
@@ -293,6 +311,7 @@ class TestEmbeddings(unittest.TestCase):
self.assertEqual(self.client.get("index").status_code, 403)
self.assertEqual(self.client.get("upsert").status_code, 403)
self.assertEqual(self.client.post("delete", json=[0]).status_code, 403)
+ self.assertEqual(self.client.post("reindex", json={"config": {"path": "sentence-transformers/nli-mpnet-base-v2"}}).status_code, 403)
def testXFunctions(self):
"""