Skip to content

armgit / txtai

Public Imported from GitHub
0

💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows

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.py
index 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 Annoy
from .faiss import Faiss
from .hnsw import HNSW
@@ -31,12 +33,32 @@ class ANNFactory:
# Create ANN instance
if 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 back
config["backend"] = backend
return 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 e
diff --git a/src/python/txtai/api/factory.py b/src/python/txtai/api/factory.py
index 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)
@staticmethod
def create(config, api):
diff --git a/src/python/txtai/database/encoder/factory.py b/src/python/txtai/database/encoder/factory.py
index 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 package
encoder = ".".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)
@staticmethod
def create(encoder):
diff --git a/src/python/txtai/database/factory.py b/src/python/txtai/database/factory.py
index 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 instance
if content == "sqlite":
database = SQLite(config)
+ elif content:
+ database = DatabaseFactory.resolve(content, config)
# Store config back
config["content"] = content
return 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 e
diff --git a/src/python/txtai/graph/factory.py b/src/python/txtai/graph/factory.py
index 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 back
config["backend"] = backend
return 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 e
diff --git a/src/python/txtai/pipeline/factory.py b/src/python/txtai/pipeline/factory.py
index d6f3b990..180e81af 100644
--- a/src/python/txtai/pipeline/factory.py
+++ b/src/python/txtai/pipeline/factory.py
@@ -6,6 +6,8 @@ import inspect
import sys
import 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)
@staticmethod
def create(config, pipeline):
diff --git a/src/python/txtai/util/__init__.py b/src/python/txtai/util/__init__.py
new file mode 100644
index 00000000..7912e008
--- /dev/null
+++ b/src/python/txtai/util/__init__.py
@@ -0,0 +1,5 @@
+"""
+Utility imports
+"""
+
+from .resolver import Resolver
diff --git a/src/python/txtai/util/resolver.py b/src/python/txtai/util/resolver.py
new file mode 100644
index 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 m
diff --git a/src/python/txtai/workflow/task/factory.py b/src/python/txtai/workflow/task/factory.py
index 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 module
import 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)
@staticmethod
def create(config, task):
diff --git a/test/python/testann.py b/test/python/testann.py
index a43b4a30..d0ca9337 100644
--- a/test/python/testann.py
+++ b/test/python/testann.py
@@ -31,6 +31,21 @@ class TestANN(unittest.TestCase):
# Test with custom settings
self.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 backend
diff --git a/test/python/testdatabase/testcustom.py b/test/python/testdatabase/testcustom.py
new file mode 100644
index 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.py
index 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