💡 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 feature to return embeddings search results as graph, closes #644
davidmezzettib35290ddab1f
diff --git a/src/python/txtai/database/base.py b/src/python/txtai/database/base.pyindex 9e10c3bd..fa0c8375 100644--- a/src/python/txtai/database/base.py+++ b/src/python/txtai/database/base.py@@ -113,7 +113,7 @@ class Database:raise NotImplementedError- def search(self, query, similarity=None, limit=None, parameters=None):+ def search(self, query, similarity=None, limit=None, parameters=None, indexids=False):"""Runs a search against the database. Supports the following methods:@@ -137,6 +137,7 @@ class Database:Returns:query results as a list of dicts+ list of ([indexid, score]) if indexids is True"""# Parse query if necessary@@ -160,7 +161,7 @@ class Database:query["where"] = where# Run query- return self.query(query, limit, parameters)+ return self.query(query, limit, parameters, indexids)def parse(self, query):"""@@ -201,7 +202,7 @@ class Database:raise NotImplementedError- def query(self, query, limit, parameters):+ def query(self, query, limit, parameters, indexids):"""Executes query against database.@@ -209,6 +210,7 @@ class Database:query: input querylimit: maximum number of results to returnparameters: dict of named parameters to bind to placeholders+ indexids: results are returned as [(indexid, score)] regardless of select clause parameters if TrueReturns:query resultsdiff --git a/src/python/txtai/database/rdbms.py b/src/python/txtai/database/rdbms.pyindex 44a55e60..d10a4976 100644--- a/src/python/txtai/database/rdbms.py+++ b/src/python/txtai/database/rdbms.py@@ -178,7 +178,7 @@ class RDBMS(Database):return Statement.IDS_CLAUSE % batch# pylint: disable=R0912- def query(self, query, limit, parameters):+ def query(self, query, limit, parameters, indexids):# Extract query componentsselect = query.get("select", self.defaults())where = query.get("where")@@ -186,6 +186,10 @@ class RDBMS(Database):orderby, qlimit, offset = query.get("orderby"), query.get("limit"), query.get("offset")similarity = query.get("similar")+ # Select "indexid, score" when indexids is True+ if indexids:+ select = f"{self.resolve('indexid')}, {self.resolve('score')}"+# Build query textquery = Statement.TABLE_CLAUSE % selectif where is not None:@@ -236,7 +240,8 @@ class RDBMS(Database):results.append(result)- return results+ # Transform results, if necessary+ return [(x["indexid"], x["score"]) for x in results] if indexids else resultsdef initialize(self):"""diff --git a/src/python/txtai/embeddings/base.py b/src/python/txtai/embeddings/base.pyindex 779b4164..d99a4a12 100644--- a/src/python/txtai/embeddings/base.py+++ b/src/python/txtai/embeddings/base.py@@ -344,7 +344,7 @@ class Embeddings:# Default to 0 when no suitable method foundreturn 0- def search(self, query, limit=None, weights=None, index=None, parameters=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.@@ -355,15 +355,18 @@ class Embeddings:weights: hybrid score weights, if applicableindex: index name, if applicableparameters: dict of named parameters to bind to placeholders+ graph: return graph results if TrueReturns:- 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+ graph when graph is set to True"""- results = self.batchsearch([query], limit, weights, index, [parameters])+ results = self.batchsearch([query], limit, weights, index, [parameters], graph)return results[0] if results else results- def batchsearch(self, queries, limit=None, weights=None, index=None, parameters=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.@@ -374,12 +377,22 @@ class Embeddings:weights: hybrid score weights, if applicableindex: index name, if applicableparameters: list of dicts of named parameters to bind to placeholders+ graph: return graph results if TrueReturns:- 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+ list of graph per query when graph is set to True"""- return Search(self)(queries, limit, weights, index, parameters)+ # Determine if graphs should be returned+ graph = graph if self.graph else False++ # Execute search+ results = Search(self, graph)(queries, limit, weights, index, parameters)++ # Create subgraphs using results, if necessary+ return [self.graph.filter(x) for x in results] if graph else resultsdef similarity(self, query, data):"""diff --git a/src/python/txtai/embeddings/search/base.py b/src/python/txtai/embeddings/search/base.pyindex 5a16f0fd..5d93d155 100644--- a/src/python/txtai/embeddings/search/base.py+++ b/src/python/txtai/embeddings/search/base.py@@ -66,7 +66,7 @@ class Search:index = self.indexes.default()# Database search- if not self.indexids and self.database:+ if self.database:return self.dbsearch(queries, limit, weights, index, parameters)# Default vector index query (sparse, dense or hybrid)@@ -238,7 +238,9 @@ class Search:results = []for x, query in enumerate(queries):# Run the database query, get matching bulk searches for current query- result = self.database.search(query, [r for y, r in scan if x == y], limit, parameters[x] if parameters and parameters[x] else None)+ result = self.database.search(+ query, [r for y, r in scan if x == y], limit, parameters[x] if parameters and parameters[x] else None, self.indexids+ )results.append(result)return resultsdiff --git a/src/python/txtai/graph/base.py b/src/python/txtai/graph/base.pyindex af24f2a6..e3f990b9 100644--- a/src/python/txtai/graph/base.py+++ b/src/python/txtai/graph/base.py@@ -79,12 +79,12 @@ class Graph:raise NotImplementedError- def node(self, uid):+ def node(self, node):"""- Get node with id uid. Returns None if not found.+ Get node by id. Returns None if not found.Args:- uid: node id+ node: node idReturns:graph node@@ -92,33 +92,33 @@ class Graph:raise NotImplementedError- def addnode(self, uid, **attrs):+ def addnode(self, node, **attrs):"""Adds a node to the graph.Args:- uid: node id+ node: node idattrs: node attributes"""raise NotImplementedError- def removenode(self, uid):+ def removenode(self, node):"""Removes a node and all it's edges from graph.Args:- uid: node id+ node: node id"""raise NotImplementedError- def hasnode(self, uid):+ def hasnode(self, node):"""Returns True if node found, False otherwise.Args:- uid: node id+ node: node idReturns:True if node found, False otherwise@@ -126,12 +126,12 @@ class Graph:raise NotImplementedError- def attribute(self, uid, field):+ def attribute(self, node, field):"""Gets a node attribute.Args:- uid: node id+ node: node idfield: attribute nameReturns:@@ -140,24 +140,24 @@ class Graph:raise NotImplementedError- def addattribute(self, uid, field, value):+ def addattribute(self, node, field, value):"""Adds an attribute to node.Args:- uid: node id+ node: node idfield: attribute namevalue: attribute value"""raise NotImplementedError- def removeattribute(self, uid, field):+ def removeattribute(self, node, field):"""Removes an attribute from node.Args:- uid: node id+ node: node idfield: attribute nameReturns:@@ -176,12 +176,12 @@ class Graph:raise NotImplementedError- def edges(self, uid):+ def edges(self, node):"""Gets edges of node by id.Args:- uid: node id+ node: node idReturns:list of edge node ids@@ -358,7 +358,7 @@ class Graph:# Initialize graph backendself.initialize()- for _, document, _ in documents:+ for uid, document, _ in documents:# Relationships are manually-provided edgesrelations = None@@ -376,7 +376,7 @@ class Graph:document = " ".join(document)# Create node- self.addnode(index, data=document)+ self.addnode(index, id=uid, data=document)# Add relationshipsself.addrelations(index, relations)@@ -391,21 +391,21 @@ class Graph:ids: node ids to delete"""- for uid in ids:+ for node in ids:# Remove existing node, if it exists- if self.hasnode(uid):+ if self.hasnode(node):# Delete from topics- topic = self.attribute(uid, "topic")+ topic = self.attribute(node, "topic")if topic and self.topics:# Delete id from topic- self.topics[topic].remove(uid)+ self.topics[topic].remove(node)# Also delete topic, if it's emptyif not self.topics[topic]:self.topics.pop(topic)# Delete node- self.removenode(uid)+ self.removenode(node)def index(self, search, ids, similarity):"""@@ -454,25 +454,72 @@ class Graph:else:self.addtopics(similarity)- def addrelations(self, uid, relations):+ def filter(self, nodes):+ """+ Creates a subgraph of this graph using the list of input nodes. This method create a new graph+ selecting only matching nodes, edges, topics and categories.++ Args:+ nodes: nodes to select as a list of (id, score) tuples++ Returns:+ graph+ """++ # Create a new empty graph of the same type+ graph = type(self)(self.config)++ # Initalize subgraph+ graph.initialize()++ nodeids = {node for node, _ in nodes}+ for node, score in nodes:+ # Add nodes+ graph.addnode(node, **self.node(node))+ graph.addattribute(node, "score", score)++ # Add edges+ edges = self.edges(node)+ if edges:+ for target, attributes in self.edges(node).items():+ if target in nodeids:+ 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}++ return graph++ def addrelations(self, node, relations):"""Add manually-provided relationships.Args:- uid: node id+ node: node idrelations: list of relationships to add"""# Add relationships, if anyif relations:- if uid not in self.relations:- self.relations[uid] = []+ if node not in self.relations:+ self.relations[node] = []# Add each relationshipfor relation in relations:# Support both dict and string idsrelation = {"id": relation} if not isinstance(relation, dict) else relation- self.relations[uid].append(relation)+ self.relations[node].append(relation)def resolverelations(self, ids):"""@@ -483,7 +530,7 @@ class Graph:"""# Resolve ids and create edges for relationships- for uid, relations in self.relations.items():+ for node, relations in self.relations.items():# Resolve internal idsiids = ids(y["id"] for y in relations)@@ -502,7 +549,7 @@ class Graph:relation["weight"] = relation.get("weight", 1.0)# Add edge and all other attributes- self.addedge(uid, target, **relation)+ self.addedge(node, target, **relation)# Clear temporary relationship storageself.relations = {}@@ -522,22 +569,22 @@ class Graph:approximate = self.config.get("approximate", True)batch = []- for uid in nodes:+ for node in nodes:# Get data attribute- data = self.removeattribute(uid, "data")+ data = self.removeattribute(node, "data")# Set text field when data is a stringif isinstance(data, str):- self.addattribute(uid, "text", data)+ self.addattribute(node, "text", data)# Add additional attributes, if specifiedif attributes:for field, value in attributes.items():- self.addattribute(uid, field, value)+ self.addattribute(node, field, value)# Skip nodes with existing edges when building an approximate network- if not self.hasedge(uid) or not approximate:- batch.append((uid, data))+ if not self.hasedge(node) or not approximate:+ batch.append((node, data))# Process batchif len(batch) == batchsize:@@ -563,7 +610,7 @@ class Graph:# Get input node idx, _ = batch[x]- # Add edges for each input uid and result uid pair that meets specified criteria+ # Add edges for each input node id and result node id pair that meets specified criteriafor y, score in result:if x != y and score > minscore and not self.hasedge(x, y):self.addedge(x, y, weight=score)@@ -593,12 +640,12 @@ class Graph:# Add topic-related node attributesfor x, topic in enumerate(self.topics):- for r, uid in enumerate(self.topics[topic]):- self.addattribute(uid, "topic", topic)- self.addattribute(uid, "topicrank", r)+ for r, node in enumerate(self.topics[topic]):+ self.addattribute(node, "topic", topic)+ self.addattribute(node, "topicrank", r)if self.categories:- self.addattribute(uid, "category", self.categories[x])+ self.addattribute(node, "category", self.categories[x])def cleartopics(self):"""@@ -607,12 +654,12 @@ class Graph:# Clear previous topics, if anyif self.topics:- for uid in self.scan():- self.removeattribute(uid, "topic")- self.removeattribute(uid, "topicrank")+ for node in self.scan():+ self.removeattribute(node, "topic")+ self.removeattribute(node, "topicrank")if self.categories:- self.removeattribute(uid, "category")+ self.removeattribute(node, "category")self.topics, self.categories = None, None@@ -623,23 +670,24 @@ class Graph:"""# Iterate over nodes missing topic attribute (only occurs for new nodes)- for uid in self.scan(attribute="updated"):+ for node in self.scan(attribute="updated"):# Remove updated attribute- self.removeattribute(uid, "updated")+ self.removeattribute(node, "updated")# Get list of neighboring nodes- ids = self.edges(uid)+ ids = self.edges(node)+ ids = ids.keys() if ids else None# Infer topictopic = Counter(self.attribute(x, "topic") for x in ids).most_common(1)[0][0] if ids else Noneif topic:# Add id to topic list and set topic attribute- self.topics[topic].append(uid)- self.addattribute(uid, "topic", topic)+ self.topics[topic].append(node)+ self.addattribute(node, "topic", topic)# Set topic rank- self.addattribute(uid, "topicrank", len(self.topics[topic]) - 1)+ self.addattribute(node, "topicrank", len(self.topics[topic]) - 1)# Infer categorycategory = Counter(self.attribute(x, "category") for x in ids).most_common(1)[0][0]- self.addattribute(uid, "category", category)+ self.addattribute(node, "category", category)diff --git a/src/python/txtai/graph/networkx.py b/src/python/txtai/graph/networkx.pyindex cd7c45a6..3e4ae496 100644--- a/src/python/txtai/graph/networkx.py+++ b/src/python/txtai/graph/networkx.py@@ -46,36 +46,36 @@ class NetworkX(Graph):# Return all nodesreturn self.backend- def node(self, uid):- return self.backend.nodes.get(uid)+ def node(self, node):+ return self.backend.nodes.get(node)- def hasnode(self, uid):- return self.backend.has_node(uid)+ def hasnode(self, node):+ return self.backend.has_node(node)- def addnode(self, uid, **attrs):- self.backend.add_node(uid, **attrs)+ def addnode(self, node, **attrs):+ self.backend.add_node(node, **attrs)- def removenode(self, uid):- if self.hasnode(uid):- self.backend.remove_node(uid)+ def removenode(self, node):+ if self.hasnode(node):+ self.backend.remove_node(node)- def attribute(self, uid, field):- return self.node(uid).get(field) if self.hasnode(uid) else None+ def attribute(self, node, field):+ return self.node(node).get(field) if self.hasnode(node) else None- def addattribute(self, uid, field, value):- if self.hasnode(uid):- self.node(uid)[field] = value+ def addattribute(self, node, field, value):+ if self.hasnode(node):+ self.node(node)[field] = value- def removeattribute(self, uid, field):- return self.node(uid).pop(field, None) if self.hasnode(uid) else None+ def removeattribute(self, node, field):+ return self.node(node).pop(field, None) if self.hasnode(node) else Nonedef edgecount(self):return self.backend.number_of_edges()- def edges(self, uid):- edges = self.backend.adj.get(uid)+ def edges(self, node):+ edges = self.backend.adj.get(node)if edges:- return dict(sorted(edges.items(), key=lambda x: x[1]["weight"], reverse=True)).keys()+ return dict(sorted(edges.items(), key=lambda x: x[1]["weight"], reverse=True))return Nonediff --git a/src/python/txtai/graph/topics.py b/src/python/txtai/graph/topics.pyindex dfe0cd11..8c0dfde0 100644--- a/src/python/txtai/graph/topics.py+++ b/src/python/txtai/graph/topics.py@@ -99,7 +99,7 @@ class Topics:Args:graph: Graph instance- node: node uid+ node: node idReturns:list of node tokensdiff --git a/test/python/testdatabase/testdatabase.py b/test/python/testdatabase/testdatabase.pyindex 44a2331c..92618825 100644--- a/test/python/testdatabase/testdatabase.py+++ b/test/python/testdatabase/testdatabase.py@@ -29,4 +29,4 @@ class TestDatabase(unittest.TestCase):self.assertRaises(NotImplementedError, database.count)self.assertRaises(NotImplementedError, database.resolve, None, None)self.assertRaises(NotImplementedError, database.embed, None, None)- self.assertRaises(NotImplementedError, database.query, None, None, None)+ self.assertRaises(NotImplementedError, database.query, None, None, None, None)diff --git a/test/python/testgraph.py b/test/python/testgraph.pyindex dee72d5b..a9b12ff5 100644--- a/test/python/testgraph.py+++ b/test/python/testgraph.py@@ -123,6 +123,19 @@ class TestGraph(unittest.TestCase):self.assertEqual(sum((len(graph.topics[x]) for x in graph.topics)), 5)self.assertEqual(len(graph.categories), 6)+ def testFilter(self):+ """+ Test creating filtered subgraphs+ """++ # 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.search("feel good story", graph=True)+ self.assertEqual(graph.count(), 3)+ self.assertEqual(graph.edgecount(), 2)+def testFunction(self):"""Test running graph functions with SQL