💡 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
Allow custom ann, database and graph instances, closes #344
davidmezzettif1906bd8915f
diff --git a/src/python/txtai/ann/factory.py b/src/python/txtai/ann/factory.pyindex 01d0aa5f..6bcb5ce5 100644--- a/src/python/txtai/ann/factory.py+++ b/src/python/txtai/ann/factory.py@@ -2,6 +2,8 @@Factory module"""+from ..util import Resolver+from .annoy import Annoyfrom .faiss import Faissfrom .hnsw import HNSW@@ -31,12 +33,32 @@ class ANNFactory:# Create ANN instanceif backend == "annoy":ann = Annoy(config)+ elif backend == "faiss":+ ann = Faiss(config)elif backend == "hnsw":ann = HNSW(config)else:- ann = Faiss(config)+ ann = ANNFactory.resolve(backend, config)# Store config backconfig["backend"] = backendreturn ann++ @staticmethod+ def resolve(backend, config):+ """+ Attempt to resolve a custom backend.++ Args:+ backend: backend class+ config: index configuration parameters++ Returns:+ ANN+ """++ try:+ return Resolver()(backend)(config)+ except Exception as e:+ raise ImportError(f"Unable to resolve ann backend: '{backend}'") from ediff --git a/src/python/txtai/api/factory.py b/src/python/txtai/api/factory.pyindex 478555ab..b3379346 100644--- a/src/python/txtai/api/factory.py+++ b/src/python/txtai/api/factory.py@@ -2,6 +2,8 @@API factory module"""+from ..util import Resolver+class Factory:"""@@ -20,13 +22,7 @@ class Factory:API"""- parts = api.split(".")- module = ".".join(parts[:-1])- m = __import__(module)- for comp in parts[1:]:- m = getattr(m, comp)-- return m+ return Resolver()(api)@staticmethoddef create(config, api):diff --git a/src/python/txtai/database/encoder/factory.py b/src/python/txtai/database/encoder/factory.pyindex ded7bf65..dbeb8222 100644--- a/src/python/txtai/database/encoder/factory.py+++ b/src/python/txtai/database/encoder/factory.py@@ -2,6 +2,8 @@Encoder factory module"""+from ...util import Resolver+from .base import Encoder@@ -27,13 +29,7 @@ class EncoderFactory:# Get parent packageencoder = ".".join(__name__.split(".")[:-1]) + "." + encoder.capitalize() + "Encoder"- parts = encoder.split(".")- module = ".".join(parts[:-1])- m = __import__(module)- for comp in parts[1:]:- m = getattr(m, comp)-- return m+ return Resolver()(encoder)@staticmethoddef create(encoder):diff --git a/src/python/txtai/database/factory.py b/src/python/txtai/database/factory.pyindex a04fafef..ee4db61a 100644--- a/src/python/txtai/database/factory.py+++ b/src/python/txtai/database/factory.py@@ -2,6 +2,8 @@Factory module"""+from ..util import Resolver+from .sqlite import SQLite@@ -35,8 +37,28 @@ class DatabaseFactory:# Create document database instanceif content == "sqlite":database = SQLite(config)+ elif content:+ database = DatabaseFactory.resolve(content, config)# Store config backconfig["content"] = contentreturn database++ @staticmethod+ def resolve(backend, config):+ """+ Attempt to resolve a custom backend.++ Args:+ backend: backend class+ config: index configuration parameters++ Returns:+ Database+ """++ try:+ return Resolver()(backend)(config)+ except Exception as e:+ raise ImportError(f"Unable to resolve database backend: '{backend}'") from ediff --git a/src/python/txtai/graph/factory.py b/src/python/txtai/graph/factory.pyindex 3c4ced69..30ad46cc 100644--- a/src/python/txtai/graph/factory.py+++ b/src/python/txtai/graph/factory.py@@ -2,6 +2,8 @@Factory module"""+from ..util import Resolver+from .networkx import NetworkX@@ -27,9 +29,30 @@ class GraphFactory:backend = config.get("backend", "networkx")# Create graph instance- graph = NetworkX(config)+ if backend == "networkx":+ graph = NetworkX(config)+ else:+ graph = GraphFactory.resolve(backend, config)# Store config backconfig["backend"] = backendreturn graph++ @staticmethod+ def resolve(backend, config):+ """+ Attempt to resolve a custom backend.++ Args:+ backend: backend class+ config: index configuration parameters++ Returns:+ Graph+ """++ try:+ return Resolver()(backend)(config)+ except Exception as e:+ raise ImportError(f"Unable to resolve graph backend: '{backend}'") from ediff --git a/src/python/txtai/pipeline/factory.py b/src/python/txtai/pipeline/factory.pyindex d6f3b990..180e81af 100644--- a/src/python/txtai/pipeline/factory.py+++ b/src/python/txtai/pipeline/factory.py@@ -6,6 +6,8 @@ import inspectimport sysimport types+from ..util import Resolver+from .base import Pipeline@@ -31,13 +33,7 @@ class PipelineFactory:return PipelineFactory.list()[pipeline]# Attempt to load custom pipeline- parts = pipeline.split(".")- module = ".".join(parts[:-1])- m = __import__(module)- for comp in parts[1:]:- m = getattr(m, comp)-- return m+ return Resolver()(pipeline)@staticmethoddef create(config, pipeline):diff --git a/src/python/txtai/util/__init__.py b/src/python/txtai/util/__init__.pynew file mode 100644index 00000000..7912e008--- /dev/null+++ b/src/python/txtai/util/__init__.py@@ -0,0 +1,5 @@+"""+Utility imports+"""++from .resolver import Resolverdiff --git a/src/python/txtai/util/resolver.py b/src/python/txtai/util/resolver.pynew file mode 100644index 00000000..b6768b35--- /dev/null+++ b/src/python/txtai/util/resolver.py@@ -0,0 +1,32 @@+"""+Resolver module+"""+++class Resolver:+ """+ Resolves a Python class path+ """++ def __call__(self, path):+ """+ Class instance to resolve.++ Args:+ path: path to class++ Returns:+ class instance+ """++ # Split into path components+ parts = path.split(".")++ # Resolve each path component+ module = ".".join(parts[:-1])+ m = __import__(module)+ for comp in parts[1:]:+ m = getattr(m, comp)++ # Return class instance+ return mdiff --git a/src/python/txtai/workflow/task/factory.py b/src/python/txtai/workflow/task/factory.pyindex 8ef45481..2c395da0 100644--- a/src/python/txtai/workflow/task/factory.py+++ b/src/python/txtai/workflow/task/factory.py@@ -4,6 +4,8 @@ Task factory moduleimport functools+from ...util import Resolver+class TaskFactory:"""@@ -28,13 +30,7 @@ class TaskFactory:task = ".".join(__name__.split(".")[:-1]) + "." + task.capitalize() + "Task"# Attempt to load custom task- parts = task.split(".")- module = ".".join(parts[:-1])- m = __import__(module)- for comp in parts[1:]:- m = getattr(m, comp)-- return m+ return Resolver()(task)@staticmethoddef create(config, task):diff --git a/test/python/testann.py b/test/python/testann.pyindex a43b4a30..d0ca9337 100644--- a/test/python/testann.py+++ b/test/python/testann.py@@ -31,6 +31,21 @@ class TestANN(unittest.TestCase):# Test with custom settingsself.runTests("annoy", {"annoy": {"ntrees": 2, "searchk": 1}}, False)+ def testCustomBackend(self):+ """+ Test resolving a custom backend+ """++ self.runTests("txtai.ann.Faiss")++ def testCustomBackendNotFound(self):+ """+ Test resolving an unresolvable backend+ """++ with self.assertRaises(ImportError):+ ANNFactory.create({"backend": "notfound.ann"})+def testFaiss(self):"""Test Faiss backenddiff --git a/test/python/testdatabase/testcustom.py b/test/python/testdatabase/testcustom.pynew file mode 100644index 00000000..755cb770--- /dev/null+++ b/test/python/testdatabase/testcustom.py@@ -0,0 +1,29 @@+"""+Custom database tests+"""++import unittest++from txtai.database import DatabaseFactory+++class TestCustom(unittest.TestCase):+ """+ Custom database backend tests.+ """++ def testCustomBackend(self):+ """+ Test resolving a custom backend+ """++ database = DatabaseFactory.create({"content": "txtai.database.SQLite"})+ self.assertIsNotNone(database)++ def testCustomBackendNotFound(self):+ """+ Test resolving an unresolvable backend+ """++ with self.assertRaises(ImportError):+ DatabaseFactory.create({"content": "notfound.database"})diff --git a/test/python/testgraph.py b/test/python/testgraph.pyindex 6d95f185..5c3aaef7 100644--- a/test/python/testgraph.py+++ b/test/python/testgraph.py@@ -87,6 +87,24 @@ class TestGraph(unittest.TestCase):graph.addtopics()self.assertEqual(sum((len(graph.topics[x]) for x in graph.topics)), 4)+ def testCustomBackend(self):+ """+ Test resolving a custom backend+ """++ graph = GraphFactory.create({"backend": "txtai.graph.NetworkX"})+ graph.initialize()+ self.assertIsNotNone(graph)++ def testCustomBackendNotFound(self):+ """+ Test resolving an unresolvable backend+ """++ with self.assertRaises(ImportError):+ graph = GraphFactory.create({"backend": "notfound.graph"})+ graph.initialize()+def testDelete(self):"""Test delete