💡 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 embeddings cluster closes #87
davidmezzettia0bd420890de
diff --git a/setup.py b/setup.pyindex d72e0dfd..fcda7a74 100644--- a/setup.py+++ b/setup.py@@ -6,7 +6,7 @@ with open("README.md", "r", encoding="utf-8") as f:setup(name="txtai",- version="3.0.0",+ version="3.1.0",author="NeuML",description="AI-powered search engine",long_description=DESCRIPTION,@@ -23,6 +23,7 @@ setup(keywords="search embedding machine-learning nlp",python_requires=">=3.6",install_requires=[+ "aiohttp>=3.7.4","annoy>=1.16.3","apache-libcloud>=3.3.1","faiss-cpu>=1.7.0; os_name != 'nt'",diff --git a/src/python/txtai/api/__init__.py b/src/python/txtai/api/__init__.pyindex 4778f974..b8195ff3 100644--- a/src/python/txtai/api/__init__.py+++ b/src/python/txtai/api/__init__.py@@ -4,5 +4,6 @@ API importsfrom .application import app, startfrom .base import API+from .cluster import Clusterfrom .extension import Extensionfrom .factory import Factorydiff --git a/src/python/txtai/api/application.py b/src/python/txtai/api/application.pyindex f2bbb974..c7eab1fb 100644--- a/src/python/txtai/api/application.py+++ b/src/python/txtai/api/application.py@@ -71,6 +71,10 @@ def start():if name in config:app.include_router(router)+ # Special case for embeddings clusters+ if "cluster" in config and "embeddings" not in config:+ app.include_router(embeddings.router)+# Special case to add similarity instance for embeddingsif "embeddings" in config and "similarity" not in config:app.include_router(similarity.router)diff --git a/src/python/txtai/api/base.py b/src/python/txtai/api/base.pyindex e416158c..e7499d71 100644--- a/src/python/txtai/api/base.py+++ b/src/python/txtai/api/base.py@@ -2,6 +2,8 @@API module"""+from .cluster import Cluster+from ..embeddings import Documents, Embeddingsfrom ..pipeline import PipelineFactoryfrom ..workflow import WorkflowFactory@@ -21,8 +23,9 @@ class API:"""# Initialize member variables- self.config, self.documents, self.embeddings = config, None, None+ self.config, self.documents, self.embeddings, self.cluster = config, None, None, None+ # Local embeddings indexif self.config.get("path") and Embeddings().exists(self.config["path"]):# Load existing index if availableself.embeddings = Embeddings()@@ -31,6 +34,10 @@ class API:# Initialize empty embeddingsself.embeddings = Embeddings(self.config["embeddings"])+ # Embeddings cluster+ if self.config.get("cluster"):+ self.cluster = Cluster(self.config["cluster"])+# Create pipelinesself.pipes()@@ -113,8 +120,11 @@ class API:list of {id: value, score: value}"""+ limit = self.limit(request.query_params.get("limit") if request else None)++ if self.cluster:+ return self.cluster.search(query, limit)if self.embeddings:- limit = self.limit(request.query_params.get("limit"))return [{"id": uid, "score": float(score)} for uid, score in self.embeddings.search(query, limit)]return None@@ -133,6 +143,8 @@ class API:list of {id: value, score: value} per query"""+ if self.cluster:+ return self.cluster.batchsearch(queries, self.limit(limit))if self.embeddings:results = self.embeddings.batchsearch(queries, self.limit(limit))return [[{"id": uid, "score": float(score)} for uid, score in result] for result in results]@@ -149,8 +161,10 @@ class API:documents: list of {id: value, text: value}"""- # Only add batch if index is marked writable- if self.embeddings and self.config.get("writable"):+ if self.cluster:+ self.cluster.add(documents)+ elif self.embeddings and self.config.get("writable"):+ # Only add batch if index is marked writable# Create documents file if not already openif not self.documents:self.documents = Documents()@@ -163,7 +177,9 @@ class API:Builds an embeddings index for previously batched documents."""- if self.embeddings and self.config.get("writable") and self.documents:+ if self.cluster:+ self.cluster.index()+ elif self.embeddings and self.config.get("writable") and self.documents:# Build scoring index if scoring method providedif self.config.get("scoring"):self.embeddings.score(self.documents)@@ -184,7 +200,9 @@ class API:Runs an embeddings upsert operation for previously batched documents."""- if self.embeddings and self.config.get("writable") and self.documents:+ if self.cluster:+ self.cluster.upsert()+ elif self.embeddings and self.config.get("writable") and self.documents:# Run upsertself.embeddings.upsert(self.documents)@@ -207,6 +225,8 @@ class API:ids deleted"""+ if self.cluster:+ return self.cluster.delete(ids)if self.embeddings and self.config.get("writable"):return self.embeddings.delete(ids)@@ -220,6 +240,8 @@ class API:number of elements in embeddings index"""+ if self.cluster:+ return self.cluster.count()if self.embeddings:return self.embeddings.count()diff --git a/src/python/txtai/api/cluster.py b/src/python/txtai/api/cluster.pynew file mode 100644index 00000000..745c59e0--- /dev/null+++ b/src/python/txtai/api/cluster.py@@ -0,0 +1,248 @@+"""+Cluster module+"""++import asyncio+import zlib++import aiohttp+++class Cluster:+ """+ Aggregates multiple embeddings shards into a single logical embeddings instance.+ """++ # pylint: disable = W0231+ def __init__(self, config=None):+ """+ Creates a new Cluster.++ Args:+ config: cluster configuration+ """++ # Configuration+ self.config = config++ # Embeddings shard urls+ self.shards = None+ if "shards" in self.config:+ self.shards = self.config["shards"]++ def search(self, query, limit=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.++ Args:+ query: query text+ limit: maximum results++ Returns:+ list of {id: value, score: value}+ """++ # Build URL+ action = "search?query=%s" % query+ if limit:+ action += "&limit=%d" % limit++ # Run query and flatten results into single results list+ results = []+ for result in self.execute("get", action):+ results.extend(result)++ # Sort and limit results+ return sorted(results, key=lambda x: x["score"], reverse=True)[: (limit if limit else 10)]++ def batchsearch(self, queries, limit=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.++ Args:+ queries: queries text+ limit: maximum results++ Returns:+ list of {id: value, score: value} per query+ """++ # POST parameters+ params = {"queries": queries}+ if limit:+ params["limit"] = limit++ # Run query+ batch = self.execute("post", "batchsearch", [params] * len(self.shards))++ # Combine results per query+ results = []+ for x in range(len(queries)):+ result = []+ for section in batch:+ result.extend(section[x])++ # Sort and limit results+ results.append(sorted(result, key=lambda x: x["score"], reverse=True)[: (limit if limit else 10)])++ return results++ def add(self, documents):+ """+ Adds a batch of documents for indexing.++ Args:+ documents: list of {id: value, text: value}+ """++ self.execute("post", "add", self.shard(documents))++ def index(self):+ """+ Builds an embeddings index for previously batched documents.+ """++ self.execute("get", "index")++ def upsert(self):+ """+ Runs an embeddings upsert operation for previously batched documents.+ """++ self.execute("get", "upsert")++ def delete(self, ids):+ """+ Deletes from an embeddings cluster. Returns list of ids deleted.++ Args:+ ids: list of ids to delete++ Returns:+ ids deleted+ """++ return [uid for ids in self.execute("post", "delete", self.shard(ids)) for uid in ids]++ def count(self):+ """+ Total number of elements in this embeddings cluster.++ Returns:+ number of elements in embeddings cluster+ """++ return sum(self.execute("get", "count"))++ def shard(self, documents):+ """+ Splits documents into equal sized shards.++ Args:+ documents: input documents++ Returns:+ list of evenly sized shards with the last shard having the remaining elements+ """++ shards = [[] for _ in range(len(self.shards))]+ for document in documents:+ uid = document["id"] if isinstance(document, dict) else document+ if isinstance(uid, str):+ # Quick int hash of string to help derive shard id+ uid = zlib.adler32(uid.encode("utf-8"))++ shards[uid % len(self.shards)].append(document)++ return shards++ def execute(self, method, action, data=None):+ """+ Executes a HTTP action asynchronously.++ Args:+ method: get or post+ action: url action to perform+ data: post parameters++ Returns:+ json results if any+ """++ # Get urls+ urls = ["%s/%s" % (shard, action) for shard in self.shards]+ close = False++ # Use existing loop if available, otherwise create one+ try:+ loop = asyncio.get_event_loop()+ except RuntimeError:+ loop = asyncio.new_event_loop()+ close = True++ try:+ return loop.run_until_complete(self.run(urls, method, data))+ finally:+ # Close loop if it was created in this method+ if close:+ loop.close()++ async def run(self, urls, method, data):+ """+ Runs an async action.++ Args:+ urls: run against this list of urls+ method: get or post+ data: list of data for each url or None++ Returns:+ json results if any+ """++ async with aiohttp.ClientSession() as session:+ tasks = []++ for x, url in enumerate(urls):+ if method == "post":+ if not data or data[x]:+ tasks.append(asyncio.ensure_future(self.post(session, url, data[x] if data else None)))+ else:+ tasks.append(asyncio.ensure_future(self.get(session, url)))++ return await asyncio.gather(*tasks)++ async def get(self, session, url):+ """+ Runs an async HTTP GET request.++ Args:+ session: ClientSession+ url: url++ Returns:+ json results if any+ """++ async with session.get(url) as resp:+ return await resp.json()++ async def post(self, session, url, data):+ """+ Runs an async HTTP POST request.++ Args:+ session: ClientSession+ url: url+ data: data to POST++ Returns:+ json results if any+ """++ async with session.post(url, json=data) as resp:+ return await resp.json()diff --git a/src/python/txtai/api/routers/embeddings.py b/src/python/txtai/api/routers/embeddings.pyindex 75df7ba0..c08eefe8 100644--- a/src/python/txtai/api/routers/embeddings.py+++ b/src/python/txtai/api/routers/embeddings.py@@ -89,7 +89,7 @@ def delete(ids: List = Body(...)):ids deleted"""- application.get().delete(ids)+ return application.get().delete(ids)@router.get("/count")diff --git a/test/python/testapi/testcluster.py b/test/python/testapi/testcluster.pynew file mode 100644index 00000000..d376a766--- /dev/null+++ b/test/python/testapi/testcluster.py@@ -0,0 +1,182 @@+"""+Cluster API module tests+"""++import json+import os+import tempfile+import unittest++from http.server import HTTPServer, BaseHTTPRequestHandler+from threading import Thread+from unittest.mock import patch++from fastapi.testclient import TestClient++from txtai.api import app, start++# Configuration for an embeddings cluster+CLUSTER = """+cluster:+ shards:+ - http://127.0.0.1:8002+ - http://127.0.0.1:8003+"""+++class RequestHandler(BaseHTTPRequestHandler):+ """+ Test HTTP handler+ """++ def do_GET(self):+ """+ GET request handler.+ """++ if self.path == "/count":+ response = 5+ elif self.path.startswith("/search"):+ response = [{"id": 4, "score": 0.40}]+ else:+ response = {"result": "ok"}++ # Convert response to string+ response = json.dumps(response).encode("utf-8")++ self.send_response(200)+ self.send_header("content-type", "application/json")+ self.send_header("content-length", len(response))+ self.end_headers()++ self.wfile.write(response)++ def do_POST(self):+ """+ POST request handler.+ """++ if self.path.startswith("/batchsearch"):+ response = [[{"id": 4, "score": 0.40}], [{"id": 1, "score": 0.40}]]+ elif self.path.startswith("/delete"):+ response = [0]+ else:+ response = {"result": "ok"}++ response = json.dumps(response).encode("utf-8")++ self.send_response(200)+ self.send_header("content-type", "application/json")+ self.send_header("content-length", len(response))+ self.end_headers()++ self.wfile.write(response)+++class TestCluster(unittest.TestCase):+ """+ API tests for embeddings clusters+ """++ @staticmethod+ @patch.dict(os.environ, {"CONFIG": os.path.join(tempfile.gettempdir(), "testapi.yml"), "API_CLASS": "txtai.api.API"})+ def start():+ """+ Starts a mock FastAPI client.+ """++ config = os.path.join(tempfile.gettempdir(), "testapi.yml")++ with open(config, "w") as output:+ output.write(CLUSTER)++ client = TestClient(app)+ start()++ return client++ @classmethod+ def setUpClass(cls):+ """+ Create API client on creation of class.+ """++ cls.client = TestCluster.start()++ cls.httpd1 = HTTPServer(("127.0.0.1", 8002), RequestHandler)++ server1 = Thread(target=cls.httpd1.serve_forever)+ server1.setDaemon(True)+ server1.start()++ cls.httpd2 = HTTPServer(("127.0.0.1", 8003), RequestHandler)++ server2 = Thread(target=cls.httpd2.serve_forever)+ server2.setDaemon(True)+ server2.start()++ # Index data+ cls.client.post("add", json=[{"id": 0, "text": "test"}])+ cls.client.get("index")++ @classmethod+ def tearDownClass(cls):+ """+ Shutdown mock http server.+ """++ cls.httpd1.shutdown()+ cls.httpd2.shutdown()++ def testCount(self):+ """+ Test cluster count+ """++ self.assertEqual(self.client.get("count").json(), 10)++ def testDelete(self):+ """+ Test cluster delete+ """++ self.assertEqual(self.client.post("delete", json=[0]).json(), [0])++ def testDeleteString(self):+ """+ Test string id+ """++ self.assertEqual(self.client.post("delete", json=["0"]).json(), [0])++ def testSearch(self):+ """+ Test cluster search+ """++ uid = self.client.get("search?query=feel%20good%20story&limit=1").json()[0]["id"]+ self.assertEqual(uid, 4)++ def testSearchBatch(self):+ """+ Test cluster batch search+ """++ results = self.client.post("batchsearch", json={"queries": ["feel good story", "climate change"], "limit": 1}).json()++ uids = [result[0]["id"] for result in results]+ self.assertEqual(uids, [4, 1])++ def testUpsert(self):+ """+ Test cluster upsert+ """++ # Update data+ self.client.post("add", json=[{"id": 4, "text": "Feel good story: baby panda born"}])+ self.client.get("upsert")++ # Search for best match+ uid = self.client.get("search?query=feel%20good%20story&limit=1").json()[0]["id"]++ self.assertEqual(uid, 4)diff --git a/test/python/testapi/testembeddings.py b/test/python/testapi/testembeddings.pyindex f791c504..4f4e7c3b 100644--- a/test/python/testapi/testembeddings.py+++ b/test/python/testapi/testembeddings.py@@ -87,13 +87,21 @@ class TestEmbeddings(unittest.TestCase):cls.client.post("add", json=[{"id": x, "text": row} for x, row in enumerate(cls.data)])cls.client.get("index")+ def testCount(self):+ """+ Test count via API+ """++ self.assertEqual(self.client.get("count").json(), 6)+def testDelete(self):"""Test delete via API"""# Delete best match- self.client.post("delete", json=[4])+ ids = self.client.post("delete", json=[4]).json()+ self.assertEqual(ids, [4])# Search for best matchuid = self.client.get("search?query=feel%20good%20story&limit=1").json()[0]["id"]@@ -114,6 +122,8 @@ class TestEmbeddings(unittest.TestCase):self.assertIsNone(api.search("test", None))self.assertIsNone(api.batchsearch(["test"], None))+ self.assertIsNone(api.delete(["test"]))+ self.assertIsNone(api.count())self.assertIsNone(api.similarity("test", ["test"]))self.assertIsNone(api.batchsimilarity(["test"], ["test"]))self.assertIsNone(api.transform("test"))