💡 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 graph search, closes #534, closes #540, closes #670
davidmezzettidc5d913ac65f
diff --git a/setup.py b/setup.pyindex 5104803e..e06bac63 100644--- a/setup.py+++ b/setup.py@@ -41,7 +41,7 @@ extras["console"] = ["rich>=12.0.1"]extras["database"] = ["duckdb>=0.7.1", "pillow>=7.1.2", "sqlalchemy>=2.0.20"]-extras["graph"] = ["networkx>=2.6.3", "python-louvain>=0.16"]+extras["graph"] = ["grand-cypher>=0.6.0", "networkx>=2.6.3", "python-louvain>=0.16"]extras["model"] = ["onnx>=1.11.0", "onnxruntime>=1.11.0"]diff --git a/src/python/txtai/api/base.py b/src/python/txtai/api/base.pyindex dd083df6..df2846ff 100644--- a/src/python/txtai/api/base.py+++ b/src/python/txtai/api/base.py@@ -2,6 +2,8 @@API module"""+import json+from .cluster import Clusterfrom ..app import Application@@ -23,23 +25,28 @@ class API(Application):self.cluster = Cluster(self.config["cluster"])# pylint: disable=W0221- def search(self, query, limit=None, weights=None, index=None, request=None):+ def search(self, query, limit=None, weights=None, index=None, parameters=None, graph=False, 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 parameterlimit = 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+ parameters = request.query_params.get("parameters") if request and hasattr(request, "query_params") else parameters+ graph = request.query_params.get("graph") if request and hasattr(request, "query_params") else graph++ # Decode parameters+ parameters = json.loads(parameters) if parameters and isinstance(parameters, str) else parametersif self.cluster:- return self.cluster.search(query, limit, weights, index)+ return self.cluster.search(query, limit, weights, index, parameters, graph)- return super().search(query, limit, weights, index)+ return super().search(query, limit, weights, index, parameters, graph)- def batchsearch(self, queries, limit=None, weights=None, index=None):+ def batchsearch(self, queries, limit=None, weights=None, index=None, parameters=None, graph=False):if self.cluster:- return self.cluster.batchsearch(queries, self.limit(limit), weights, index)+ return self.cluster.batchsearch(queries, self.limit(limit), weights, index, parameters, graph)- return super().batchsearch(queries, limit, weights, index)+ return super().batchsearch(queries, limit, weights, index, parameters, graph)def add(self, documents):"""diff --git a/src/python/txtai/api/cluster.py b/src/python/txtai/api/cluster.pyindex 0df158aa..db4039d0 100644--- a/src/python/txtai/api/cluster.py+++ b/src/python/txtai/api/cluster.py@@ -3,6 +3,7 @@ Cluster module"""import asyncio+import jsonimport randomimport urllib.parseimport zlib@@ -37,7 +38,7 @@ class Cluster:# Query aggregatorself.aggregate = Aggregate()- def search(self, query, limit=None, weights=None, index=None):+ def search(self, query, limit=None, weights=None, index=None, parameters=None, graph=False):"""Finds documents most similar to the input query. This method will run either an index searchor an index + database search depending on if a database is available.@@ -47,6 +48,8 @@ class Cluster:limit: maximum resultsweights: hybrid score weights, if applicableindex: index name, if applicable+ parameters: dict of named parameters to bind to placeholders+ graph: return graph results if TrueReturns:list of {id: value, score: value} for index search, list of dict for an index + database search@@ -60,6 +63,10 @@ class Cluster:action += f"&weights={weights}"if index:action += f"&index={index}"+ if parameters:+ action += f"¶meters={json.dumps(parameters) if isinstance(parameters, dict) else parameters}"+ if graph is not None:+ action += f"&graph={graph}"# Run query and flatten results into single results listresults = []@@ -72,7 +79,7 @@ class Cluster:# Limit resultsreturn results[: (limit if limit else 10)]- def batchsearch(self, queries, limit=None, weights=None, index=None):+ def batchsearch(self, queries, limit=None, weights=None, index=None, parameters=None, graph=False):"""Finds documents most similar to the input queries. This method will run either an index searchor an index + database search depending on if a database is available.@@ -82,6 +89,8 @@ class Cluster:limit: maximum resultsweights: hybrid score weights, if applicableindex: index name, if applicable+ parameters: list of dicts of named parameters to bind to placeholders+ graph: return graph results if TrueReturns:list of {id: value, score: value} per query for index search, list of dict per query for an index + database search@@ -95,6 +104,10 @@ class Cluster:params["weights"] = weightsif index:params["index"] = index+ if parameters:+ params["parameters"] = parameters+ if graph is not None:+ params["graph"] = graph# Run querybatch = self.execute("post", "batchsearch", [params] * len(self.shards))diff --git a/src/python/txtai/api/routers/embeddings.py b/src/python/txtai/api/routers/embeddings.pyindex 31ecf06b..ad2a1778 100644--- a/src/python/txtai/api/routers/embeddings.py+++ b/src/python/txtai/api/routers/embeddings.py@@ -15,6 +15,7 @@ from ..responses import ResponseFactoryfrom ..route import EncodingAPIRoutefrom ...app import ReadOnlyError+from ...graph import Graphrouter = APIRouter(route_class=EncodingAPIRoute)@@ -37,7 +38,9 @@ def search(query: str, request: Request):results = application.get().search(query, request=request)# Encode using standard FastAPI encoder but skip certain classes- results = jsonable_encoder(results, custom_encoder={bytes: lambda x: x, BytesIO: lambda x: x, PIL.Image.Image: lambda x: x})+ results = jsonable_encoder(+ results, custom_encoder={bytes: lambda x: x, BytesIO: lambda x: x, PIL.Image.Image: lambda x: x, Graph: lambda x: x.savedict()}+ )# Return raw response to prevent duplicate encodingresponse = ResponseFactory.create(request)@@ -52,6 +55,8 @@ def batchsearch(limit: int = Body(default=None),weights: float = Body(default=None),index: str = Body(default=None),+ parameters: List[dict] = Body(default=None),+ graph: bool = Body(default=False),):"""Finds documents most similar to the input queries. This method will run either an index search@@ -62,16 +67,20 @@ def batchsearch(limit: maximum resultsweights: hybrid score weights, if applicableindex: index name, if applicable+ parameters: list of dicts of named parameters to bind to placeholders+ graph: return graph results if TrueReturns:list of {id: value, score: value} per query for index search, list of dict per query for an index + database search"""# Execute search- results = application.get().batchsearch(queries, limit, weights, index)+ results = application.get().batchsearch(queries, limit, weights, index, parameters, graph)# Encode using standard FastAPI encoder but skip certain classes- results = jsonable_encoder(results, custom_encoder={bytes: lambda x: x, BytesIO: lambda x: x, PIL.Image.Image: lambda x: x})+ results = jsonable_encoder(+ results, custom_encoder={bytes: lambda x: x, BytesIO: lambda x: x, PIL.Image.Image: lambda x: x, Graph: lambda x: x.savedict()}+ )# Return raw response to prevent duplicate encodingresponse = ResponseFactory.create(request)diff --git a/src/python/txtai/app/base.py b/src/python/txtai/app/base.pyindex ff829480..58cf2a01 100644--- a/src/python/txtai/app/base.py+++ b/src/python/txtai/app/base.py@@ -309,7 +309,7 @@ class Application:# Attempt to resolve action as a callable functionreturn PipelineFactory.create({}, function)- def search(self, query, limit=10, weights=None, index=None):+ def search(self, query, limit=10, weights=None, index=None, parameters=None, graph=False):"""Finds documents most similar to the input query. This method will run either an index searchor an index + database search depending on if a database is available.@@ -319,6 +319,8 @@ class Application:limit: maximum resultsweights: hybrid score weights, if applicableindex: index name, if applicable+ parameters: dict of named parameters to bind to placeholders+ graph: return graph results if TrueReturns:list of {id: value, score: value} for index search, list of dict for an index + database search@@ -326,14 +328,14 @@ class Application:if self.embeddings:with self.lock:- results = self.embeddings.search(query, limit, weights, index)+ results = self.embeddings.search(query, limit, weights, index, parameters, graph)# 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 results if graph else [{"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, weights=None, index=None):+ def batchsearch(self, queries, limit=10, weights=None, index=None, parameters=None, graph=False):"""Finds documents most similar to the input queries. This method will run either an index searchor an index + database search depending on if a database is available.@@ -343,6 +345,8 @@ class Application:limit: maximum resultsweights: hybrid score weights, if applicableindex: index name, if applicable+ parameters: list of dicts of named parameters to bind to placeholders+ graph: return graph results if TrueReturns:list of {id: value, score: value} per query for index search, list of dict per query for an index + database search@@ -350,12 +354,12 @@ class Application:if self.embeddings:with self.lock:- search = self.embeddings.batchsearch(queries, limit, weights, index)+ search = self.embeddings.batchsearch(queries, limit, weights, index, parameters, graph)results = []for result in search:# Unpack (id, score) tuple, if necessary. Otherwise, results are dictionaries.- results.append([{"id": r[0], "score": float(r[1])} if isinstance(r, tuple) else r for r in result])+ results.append(result if graph else [{"id": r[0], "score": float(r[1])} if isinstance(r, tuple) else r for r in result])return resultsreturn Nonediff --git a/src/python/txtai/embeddings/base.py b/src/python/txtai/embeddings/base.pyindex d6370471..53443b24 100644--- a/src/python/txtai/embeddings/base.py+++ b/src/python/txtai/embeddings/base.py@@ -314,8 +314,11 @@ class Embeddings:# Initialize default parameters, if necessaryself.defaults()+ # Default vector model, if necessary+ model = self.model if self.model else next(iter(self.models.values()))+# Convert documents into sentence embeddings- embeddings = self.model.batchtransform(Stream(self)(documents), category)+ embeddings = model.batchtransform(Stream(self)(documents), category)# Reduce the dimensionality of the embeddings. Scale the embeddings using this# model to reduce the noise of common but less relevant terms.diff --git a/src/python/txtai/graph/base.py b/src/python/txtai/graph/base.pyindex e01eb777..8eade381 100644--- a/src/python/txtai/graph/base.py+++ b/src/python/txtai/graph/base.py@@ -249,6 +249,37 @@ class Graph:raise NotImplementedError+ def search(self, query, limit=None, graph=False):+ """+ Searches graph for nodes matching query.++ Args:+ query: graph query+ limit: maximum results+ graph: return graph results if True++ Returns:+ list of dict if graph is set to False+ filtered graph if graph is set to True+ """++ raise NotImplementedError++ def batchsearch(self, queries, limit=None, graph=False):+ """+ Searches graph for nodes matching query.++ Args:+ query: graph query+ limit: maximum results+ graph: return graph results if True++ Returns:+ list of dict+ """++ return [self.search(query, limit, graph) for query in queries]+def communities(self, config):"""Run community detection on the graph.@@ -282,6 +313,26 @@ class Graph:raise NotImplementedError+ def loaddict(self, data):+ """+ Loads data from input dictionary into this graph.++ Args:+ data: input dictionary+ """++ raise NotImplementedError++ def savedict(self):+ """+ Saves graph data to a dictionary.++ Returns:+ dict+ """++ raise NotImplementedError+def initialize(self):"""Initialize graph instance.@@ -460,7 +511,7 @@ class Graph:selecting only matching nodes, edges, topics and categories.Args:- nodes: nodes to select as a list of (id, score) tuples+ nodes: nodes to select as a list of ids or list of (id, score) tuplesReturns:graph@@ -472,11 +523,17 @@ class Graph:# Initalize subgraphgraph.initialize()- nodeids = {node for node, _ in nodes}- for node, score in nodes:+ nodeids = {node[0] if isinstance(node, tuple) else node for node in nodes}+ for node in nodes:+ # Unpack node and score, if available+ node, score = node if isinstance(node, tuple) else (node, None)+# Add nodesgraph.addnode(node, **self.node(node))- graph.addattribute(node, "score", score)++ # Add score if present+ if score is not None:+ graph.addattribute(node, "score", score)# Add edgesedges = self.edges(node)@@ -486,18 +543,19 @@ class Graph:graph.addedge(node, target, **attributes)# Filter categories and topics- topics = {}- for i, (topic, ids) in enumerate(self.topics.items()):- ids = [x for x in ids if x in nodeids]- if ids:- topics[topic] = (self.categories[i] if self.categories else None, ids)-- # Sort by number of nodes descending- topics = sorted(topics.items(), key=lambda x: len(x[1][1]), reverse=True)-- # Copy filtered categories and topics- graph.categories = [category for _, (category, _) in topics] if self.categories else None- graph.topics = {topic: ids for topic, (_, ids) in topics}+ if self.topics:+ topics = {}+ for i, (topic, ids) in enumerate(self.topics.items()):+ ids = [x for x in ids if x in nodeids]+ if ids:+ topics[topic] = (self.categories[i] if self.categories else None, ids)++ # Sort by number of nodes descending+ topics = sorted(topics.items(), key=lambda x: len(x[1][1]), reverse=True)++ # Copy filtered categories and topics+ graph.categories = [category for _, (category, _) in topics] if self.categories else None+ graph.topics = {topic: ids for topic, (_, ids) in topics}return graphdiff --git a/src/python/txtai/graph/networkx.py b/src/python/txtai/graph/networkx.pyindex 3e4ae496..82e5deaa 100644--- a/src/python/txtai/graph/networkx.py+++ b/src/python/txtai/graph/networkx.py@@ -9,7 +9,9 @@ try:import networkx as nxfrom community import community_louvain+ from grandcypher import GrandCypherfrom networkx.algorithms.community import asyn_lpa_communities, greedy_modularity_communities+ from networkx.readwrite import json_graphNETWORKX = Trueexcept ImportError:@@ -101,6 +103,33 @@ class NetworkX(Graph):# pylint: disable=E1121return nx.shortest_path(self.backend, source, target, self.distance)+ def search(self, query, limit=None, graph=False):+ # Run openCypher query+ results = GrandCypher(self.backend, limit if limit else 3).run(query)++ # Transform into filtered graph+ if graph:+ nodes = set()+ for column in results.values():+ for value in column:+ if isinstance(value, list):+ # Path group+ nodes.update([node for node in value if node and not isinstance(node, dict)])+ elif value is not None:+ # Single result+ nodes.add(value)++ return self.filter(list(nodes))++ # Transform columnar structure into rows+ keys = list(results.keys())+ rows, count = [], len(results[keys[0]])++ for x in range(count):+ rows.append({str(key): results[key][x] for key in keys})++ return rows+def communities(self, config):# Get community detection algorithmalgorithm = config.get("algorithm")@@ -124,6 +153,17 @@ class NetworkX(Graph):with open(path, "wb") as handle:pickle.dump(self.backend, handle, protocol=__pickle__)+ def loaddict(self, data):+ self.backend = json_graph.node_link_graph(data)+ self.categories, self.topics = data.get("categories"), data.get("topics")++ def savedict(self):+ data = json_graph.node_link_data(self.backend)+ data["categories"] = self.categories+ data["topics"] = self.topics++ return data+def louvain(self, config):"""Runs the Louvain community detection algorithm.diff --git a/test/python/testapi/testcluster.py b/test/python/testapi/testcluster.pyindex 77ff9878..2b5a488b 100644--- a/test/python/testapi/testcluster.py+++ b/test/python/testapi/testcluster.py@@ -195,8 +195,11 @@ class TestCluster(unittest.TestCase):Test cluster search"""+ # Encode parameters+ params = json.dumps({"x": 1})+query = urllib.parse.quote("feel good story")- uid = self.client.get(f"search?query={query}&limit=1&weights=0.5&index=default").json()[0]["id"]+ uid = self.client.get(f"search?query={query}&limit=1&weights=0.5&index=default¶meters={params}&graph=False").json()[0]["id"]self.assertEqual(uid, 4)def testSearchBatch(self):@@ -205,7 +208,15 @@ class TestCluster(unittest.TestCase):"""results = self.client.post(- "batchsearch", json={"queries": ["feel good story", "climate change"], "limit": 1, "weights": 0.5, "index": "default"}+ "batchsearch",+ json={+ "queries": ["feel good story", "climate change"],+ "limit": 1,+ "weights": 0.5,+ "index": "default",+ "parameters": [{"x": 1}, {"x": 2}],+ "graph": False,+ },).json()uids = [result[0]["id"] for result in results]diff --git a/test/python/testgraph.py b/test/python/testgraph.pyindex a9b12ff5..568ef4ce 100644--- a/test/python/testgraph.py+++ b/test/python/testgraph.py@@ -11,6 +11,7 @@ from txtai.embeddings import Embeddingsfrom txtai.graph import Graph, GraphFactory+# pylint: disable=R0904class TestGraph(unittest.TestCase):"""Graph tests.@@ -210,9 +211,12 @@ class TestGraph(unittest.TestCase):self.assertRaises(NotImplementedError, graph.centrality)self.assertRaises(NotImplementedError, graph.pagerank)self.assertRaises(NotImplementedError, graph.showpath, None, None)+ self.assertRaises(NotImplementedError, graph.search, None)self.assertRaises(NotImplementedError, graph.communities, None)self.assertRaises(NotImplementedError, graph.loadgraph, None)self.assertRaises(NotImplementedError, graph.savegraph, None)+ self.assertRaises(NotImplementedError, graph.loaddict, None)+ self.assertRaises(NotImplementedError, graph.savedict)def testRelationships(self):"""@@ -281,6 +285,91 @@ class TestGraph(unittest.TestCase):self.assertEqual(sum((len(graph.topics[x]) for x in graph.topics)), 6)self.assertEqual(len(graph.categories), 6)+ def testSaveDict(self):+ """+ Test loading and saving to dictionaries+ """++ # Create an index for the list of text+ self.embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])++ # Validate counts+ graph = self.embeddings.graph+ count, edgecount = graph.count(), graph.edgecount()++ # Save and reload graph as dict+ data = graph.savedict()+ graph.loaddict(data)++ # Validate counts+ self.assertEqual(graph.count(), count)+ self.assertEqual(graph.edgecount(), edgecount)++ def testSearch(self):+ """+ Test search+ """++ # Create an index for the list of text+ self.embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])++ # Run standard search+ results = self.embeddings.graph.search(+ """+ MATCH (A)-[]->(B)+ RETURN A, B+ """+ )+ self.assertEqual(len(results), 3)++ # Run path search+ results = self.embeddings.graph.search(+ """+ MATCH P=()-[]->()+ RETURN P+ """+ )+ self.assertEqual(len(results), 3)++ # Run graph search+ g = self.embeddings.graph.search(+ """+ MATCH (A)-[]->(B)+ RETURN A, B+ """,+ graph=True,+ )+ self.assertEqual(g.count(), 3)++ # Run path search+ results = self.embeddings.graph.search(+ """+ MATCH P=()-[]->()+ RETURN P+ """,+ graph=True,+ )+ self.assertEqual(g.count(), 3)++ def testSearchBatch(self):+ """+ Test batch search+ """++ # Create an index for the list of text+ self.embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])++ # Run standard search+ results = self.embeddings.graph.batchsearch(+ [+ """+ MATCH (A)-[]->(B)+ RETURN A, B+ """+ ]+ )+ self.assertEqual(len(results[0]), 3)+def testSimple(self):"""Test creating a simple graph