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 indexing of embeddings graph relationships, closes #525

davidmezzettiea64551f34ed
diff --git a/src/python/txtai/embeddings/base.py b/src/python/txtai/embeddings/base.py
index 3bbf9fe2..779b4164 100644
--- a/src/python/txtai/embeddings/base.py
+++ b/src/python/txtai/embeddings/base.py
@@ -20,7 +20,7 @@ from ..vectors import VectorsFactory
from ..version import __pickle__
from .index import Action, Functions, Indexes, Reducer, Stream, Transform
-from .search import Explain, Query, Search, Terms
+from .search import Explain, Ids, Query, Search, Terms
# pylint: disable=C0302,R0904
@@ -145,7 +145,7 @@ class Embeddings:
# Index graph, if necessary
if self.graph:
- self.graph.index(Search(self, True), self.batchsimilarity)
+ self.graph.index(Search(self, True), Ids(self), self.batchsimilarity)
def upsert(self, documents):
"""
@@ -192,7 +192,7 @@ class Embeddings:
# Graph upsert, if necessary
if self.graph:
- self.graph.upsert(Search(self, True), self.batchsimilarity)
+ self.graph.upsert(Search(self, True), Ids(self), self.batchsimilarity)
def delete(self, ids):
"""
diff --git a/src/python/txtai/embeddings/search/__init__.py b/src/python/txtai/embeddings/search/__init__.py
index d7a15ef0..e2aa7043 100644
--- a/src/python/txtai/embeddings/search/__init__.py
+++ b/src/python/txtai/embeddings/search/__init__.py
@@ -5,6 +5,7 @@ Search imports
from .base import Search
from .errors import *
from .explain import Explain
+from .ids import Ids
from .query import Query
from .scan import Scan
from .terms import Terms
diff --git a/src/python/txtai/embeddings/search/ids.py b/src/python/txtai/embeddings/search/ids.py
new file mode 100644
index 00000000..4dc207fe
--- /dev/null
+++ b/src/python/txtai/embeddings/search/ids.py
@@ -0,0 +1,61 @@
+"""
+Ids module
+"""
+
+
+class Ids:
+ """
+ Resolves internal ids for lists of ids.
+ """
+
+ def __init__(self, embeddings):
+ """
+ Create a new ids action.
+
+ Args:
+ embeddings: embeddings instance
+ """
+
+ self.config = embeddings.config
+ self.database = embeddings.database
+
+ def __call__(self, ids):
+ """
+ Resolve internal ids.
+
+ Args:
+ ids: ids
+
+ Returns:
+ internal ids
+ """
+
+ # Resolve ids using database if available, otherwise fallback to config
+ results = self.database.ids(ids) if self.database else self.scan(ids)
+
+ # Create dict of id: [iids] given there is a one to many relationship
+ ids = {}
+ for iid, uid in results:
+ if uid not in ids:
+ ids[uid] = []
+ ids[uid].append(iid)
+
+ return ids
+
+ def scan(self, ids):
+ """
+ Scans config ids array for matches when content is disabled.
+
+ Args:
+ ids: search ids
+
+ Returns:
+ internal ids
+ """
+
+ # Find existing ids
+ indices = []
+ for uid in ids:
+ indices.extend([(index, value) for index, value in enumerate(self.config["ids"]) if uid == value])
+
+ return indices
diff --git a/src/python/txtai/graph/base.py b/src/python/txtai/graph/base.py
index 769c77ab..af24f2a6 100644
--- a/src/python/txtai/graph/base.py
+++ b/src/python/txtai/graph/base.py
@@ -44,6 +44,10 @@ class Graph:
self.text = columns.get("text", "text")
self.object = columns.get("object", "object")
+ # Relationships are manually-provided edges
+ self.relationships = columns.get("relationships", "relationships")
+ self.relations = {}
+
def create(self):
"""
Creates the graph network.
@@ -355,7 +359,14 @@ class Graph:
self.initialize()
for _, document, _ in documents:
+ # Relationships are manually-provided edges
+ relations = None
+
+ # Extract data from dictionary
if isinstance(document, dict):
+ # Extract relationships
+ relations = document.get(self.relationships)
+
# Require text or object field
document = document.get(self.text, document.get(self.object))
@@ -366,6 +377,10 @@ class Graph:
# Create node
self.addnode(index, data=document)
+
+ # Add relationships
+ self.addrelations(index, relations)
+
index += 1
def delete(self, ids):
@@ -392,15 +407,19 @@ class Graph:
# Delete node
self.removenode(uid)
- def index(self, search, similarity):
+ def index(self, search, ids, similarity):
"""
Build relationships between graph nodes using a score-based search function.
Args:
search: batch search function - takes a list of queries and returns lists of (id, scores) to use as edge weights
+ ids: ids function - internal id resolver
similarity: batch similarity function - takes a list of text and labels and returns best matches
"""
+ # Add relationship edges
+ self.resolverelations(ids)
+
# Add node edges
self.addedges(self.scan(), search)
@@ -408,18 +427,22 @@ class Graph:
if "topics" in self.config:
self.addtopics(similarity)
- def upsert(self, search, similarity=None):
+ def upsert(self, search, ids, similarity=None):
"""
Adds relationships for new graph nodes using a score-based search function.
Args:
search: batch search function - takes a list of queries and returns lists of (id, scores) to use as edge weights
+ ids: ids function - internal id resolver
similarity: batch similarity function - takes a list of text and labels and returns best matches
"""
# Detect if topics processing is enabled
hastopics = "topics" in self.config
+ # Add relationship edges
+ self.resolverelations(ids)
+
# Add node edges using new/updated nodes, set updated flag for topic processing, if necessary
self.addedges(self.scan(attribute="data"), search, {"updated": True} if hastopics else None)
@@ -431,6 +454,59 @@ class Graph:
else:
self.addtopics(similarity)
+ def addrelations(self, uid, relations):
+ """
+ Add manually-provided relationships.
+
+ Args:
+ uid: node id
+ relations: list of relationships to add
+ """
+
+ # Add relationships, if any
+ if relations:
+ if uid not in self.relations:
+ self.relations[uid] = []
+
+ # Add each relationship
+ for relation in relations:
+ # Support both dict and string ids
+ relation = {"id": relation} if not isinstance(relation, dict) else relation
+ self.relations[uid].append(relation)
+
+ def resolverelations(self, ids):
+ """
+ Resolves ids and creates edges for manually-provided relationships.
+
+ Args:
+ ids: internal id resolver
+ """
+
+ # Resolve ids and create edges for relationships
+ for uid, relations in self.relations.items():
+ # Resolve internal ids
+ iids = ids(y["id"] for y in relations)
+
+ # Add each edge
+ for relation in relations:
+ # Make copy of relation
+ relation = relation.copy()
+
+ # Lookup targets for relationship
+ targets = iids.get(str(relation.pop("id")))
+
+ # Create edge for each instance of id - internal id pair
+ if targets:
+ for target in targets:
+ # Add weight, if not provided
+ relation["weight"] = relation.get("weight", 1.0)
+
+ # Add edge and all other attributes
+ self.addedge(uid, target, **relation)
+
+ # Clear temporary relationship storage
+ self.relations = {}
+
def addedges(self, nodes, search, attributes=None):
"""
Adds edges for a list of nodes using a score-based search function.
diff --git a/src/python/txtai/graph/networkx.py b/src/python/txtai/graph/networkx.py
index c77a26da..cd7c45a6 100644
--- a/src/python/txtai/graph/networkx.py
+++ b/src/python/txtai/graph/networkx.py
@@ -75,7 +75,7 @@ class NetworkX(Graph):
def edges(self, uid):
edges = self.backend.adj.get(uid)
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)).keys()
return None
diff --git a/test/python/testgraph.py b/test/python/testgraph.py
index 7dbc7033..dee72d5b 100644
--- a/test/python/testgraph.py
+++ b/test/python/testgraph.py
@@ -201,6 +201,41 @@ class TestGraph(unittest.TestCase):
self.assertRaises(NotImplementedError, graph.loadgraph, None)
self.assertRaises(NotImplementedError, graph.savegraph, None)
+ def testRelationships(self):
+ """
+ Test manually-provided relationships
+ """
+
+ # Create relationships for id 0
+ relationships = [{"id": f"ID{x}"} for x in range(1, len(self.data))]
+
+ # Test with content enabled
+ self.embeddings.index({"id": f"ID{i}", "text": x, "relationships": relationships if i == 0 else None} for i, x in enumerate(self.data))
+ self.assertEqual(len(self.embeddings.graph.edges(0)), len(self.data) - 1)
+
+ # Test with content disabled
+ config = self.config.copy()
+ config["content"] = False
+
+ embeddings = Embeddings(config)
+ embeddings.index({"id": f"ID{i}", "text": x, "relationships": relationships if i == 0 else None} for i, x in enumerate(self.data))
+ self.assertEqual(len(embeddings.graph.edges(0)), len(self.data) - 1)
+
+ def testRelationshipsInvalid(self):
+ """
+ Test manually-provided relationships with no matching id
+ """
+
+ # Create relationships for id 0
+ relationships = [{"id": "INVALID"}]
+
+ # Index with invalid relationship
+ self.embeddings.index({"text": x, "relationships": relationships if i == 0 else None} for i, x in enumerate(self.data))
+
+ # Validate only relationship is semantically-derived
+ edges = list(self.embeddings.graph.edges(0))
+ self.assertTrue(len(edges) == 1 and edges[0] != "INVALID")
+
def testResetTopics(self):
"""
Test resetting of topics