💡 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 support for custom SQL functions in embeddings queries, closes #241
davidmezzetti7a4f6775d539
diff --git a/src/python/txtai/app/base.py b/src/python/txtai/app/base.pyindex f04ae38c..13551b16 100644--- a/src/python/txtai/app/base.py+++ b/src/python/txtai/app/base.py@@ -63,21 +63,15 @@ class Application:# ThreadPool - runs scheduled workflowsself.pool = None- # Local embeddings index- if loaddata and self.config.get("path") and Embeddings().exists(self.config["path"], self.config.get("cloud")):- # Load existing index if available- self.embeddings = Embeddings()- self.embeddings.load(self.config["path"], self.config.get("cloud"))- elif self.config.get("embeddings"):- # Initialize empty embeddings- self.embeddings = Embeddings(self.config["embeddings"])-# Create pipelinesself.pipes()# Create workflowsself.flows()+ # Create embeddings index+ self.indexes(loaddata)+def __del__(self):"""Close threadpool when this object is garbage collected.@@ -147,6 +141,36 @@ class Application:self.pool.apply_async(self.workflows[workflow].schedule, kwds=schedule)+ def indexes(self, loaddata):+ """+ Initialize an embeddings index.++ Args:+ loaddata: If True (default), load existing index data, if available. Otherwise, only load models.+ """++ # Resolve functions in embeddings config+ config = self.config.get("embeddings") if self.config else None+ if config:+ # Create copy of config+ config = config.copy()++ if "functions" in config:+ # Resolve callable functions+ config["functions"] = [self.function(fn) for fn in config["functions"]]+ if "transform" in config:+ # Resolve transform function+ config["transform"] = self.function(config["transform"])++ # Local embeddings index+ if loaddata and self.config.get("path") and Embeddings().exists(self.config["path"], self.config.get("cloud")):+ # Load existing index if available+ self.embeddings = Embeddings()+ self.embeddings.load(self.config["path"], self.config.get("cloud"))+ elif config:+ # Initialize empty embeddings+ self.embeddings = Embeddings(config)+def resolve(self, task):"""Resolves callable functions for a task.@@ -475,9 +499,14 @@ class Application:"""if self.embeddings and "extractor" in self.pipelines:+ # Set similarity function+ extractor = self.pipelines["extractor"]+ if not extractor.similarity:+ extractor.similarity = self.embeddings+# Convert queue to tuplesqueue = [(x["name"], x["query"], x.get("question"), x.get("snippet")) for x in queue]- return [{"name": name, "answer": answer} for name, answer in self.pipelines["extractor"](queue, texts)]+ return [{"name": name, "answer": answer} for name, answer in extractor(queue, texts)]return Nonediff --git a/src/python/txtai/database/base.py b/src/python/txtai/database/base.pyindex 64a784e7..ed23966f 100644--- a/src/python/txtai/database/base.py+++ b/src/python/txtai/database/base.py@@ -3,6 +3,9 @@ Database module"""import logging+import types++from inspect import signaturefrom .encoder import EncoderFactoryfrom .sql import SQL, SQLError, Token@@ -22,7 +25,7 @@ class Database:Creates a new Database.Args:- config: database configuration parameters+ config: database configuration"""# Database configuration@@ -35,6 +38,9 @@ class Database:encoder = self.config.get("objects")self.encoder = EncoderFactory.create(encoder) if encoder else None+ # Load custom functions+ self.functions = self.register(self.config)+def load(self, path):"""Loads a database path.@@ -208,6 +214,35 @@ class Database:raise NotImplementedError+ def register(self, config):+ """+ Register custom functions. This method stores the function details for underlying+ database implementations to handle.++ Args:+ config: database configuration+ """++ inputs = config.get("functions") if config else None+ if inputs:+ functions = []+ for fn in inputs:+ # Determine if this is a callable object or a function+ if not isinstance(fn, types.FunctionType) and hasattr(fn, "__call__"):+ name = fn.__class__.__name__.lower()+ argcount = len(signature(fn.__call__).parameters)+ fn = fn.__call__+ else:+ name = fn.__name__.lower()+ argcount = len(signature(fn).parameters)++ # Store function details+ functions.append((name, argcount, fn))++ return functions++ return None+def execute(self, function, *args):"""Executes a user query. This method has common error handling logic.diff --git a/src/python/txtai/database/sqlite.py b/src/python/txtai/database/sqlite.pyindex 8edb7848..7d829621 100644--- a/src/python/txtai/database/sqlite.py+++ b/src/python/txtai/database/sqlite.py@@ -119,6 +119,9 @@ class SQLite(Database):self.cursor = self.connection.cursor()self.path = path+ # Register custom functions+ self.addfunctions()+def insert(self, documents, index=0):# Initialize connection if not openself.initialize()@@ -203,6 +206,9 @@ class SQLite(Database):self.cursor = self.connection.cursor()self.path = path+ # Register custom functions+ self.addfunctions()+# Paths are equal, commit changeselif self.path == path:self.connection.commit()@@ -319,6 +325,15 @@ class SQLite(Database):return results+ def addfunctions(self):+ """+ Adds custom functions in current connection.+ """++ if self.connection and self.functions:+ for name, argcount, fn in self.functions:+ self.connection.create_function(name, argcount, fn)+def initialize(self):"""Creates connection and initial database schema if no connection exists.@@ -331,6 +346,9 @@ class SQLite(Database):self.connection = sqlite3.connect("", check_same_thread=False)self.cursor = self.connection.cursor()+ # Register custom functions+ self.addfunctions()+# Create initial schema and indicesself.cursor.execute(SQLite.CREATE_DOCUMENTS)self.cursor.execute(SQLite.CREATE_OBJECTS)diff --git a/src/python/txtai/embeddings/base.py b/src/python/txtai/embeddings/base.pyindex 16123d97..996888ff 100644--- a/src/python/txtai/embeddings/base.py+++ b/src/python/txtai/embeddings/base.py@@ -7,7 +7,6 @@ import pickleimport osimport shutilimport tempfile-import typesimport numpy as np@@ -471,13 +470,8 @@ class Embeddings:# Remove ids array if presentconfig.pop("ids", None)- # Format functions- for key in config:- if isinstance(config[key], types.FunctionType):- config[key] = "<function>"-# Print configuration- print(json.dumps(config, sort_keys=True, indent=2))+ print(json.dumps(config, sort_keys=True, default=str, indent=2))def configure(self, config):"""diff --git a/test/python/testapi/testembeddings.py b/test/python/testapi/testembeddings.pyindex 3578b71d..81c421f0 100644--- a/test/python/testapi/testembeddings.py+++ b/test/python/testapi/testembeddings.py@@ -39,6 +39,22 @@ path: %swritable: False"""+# Configuration for an index with custom functions+FUNCTIONS = """+pathignore: %s++writable: True++# Embeddings settings+embeddings:+ path: sentence-transformers/nli-mpnet-base-v2+ content: True+ functions:+ - testapi.testembeddings.Elements+ - testapi.testembeddings.length+ transform: testapi.testembeddings.transform+"""+class TestEmbeddings(unittest.TestCase):"""@@ -47,19 +63,19 @@ class TestEmbeddings(unittest.TestCase):@staticmethod@patch.dict(os.environ, {"CONFIG": os.path.join(tempfile.gettempdir(), "testapi.yml"), "API_CLASS": "txtai.api.API"})- def start(full):+ def start(yaml):"""Starts a mock FastAPI client.Args:- full: true if full api configuration should be loaded, otherwise a read-only configuration is used+ yaml: input configuration"""config = os.path.join(tempfile.gettempdir(), "testapi.yml")index = os.path.join(tempfile.gettempdir(), "testapi")with open(config, "w", encoding="utf-8") as output:- output.write((INDEX if full else READONLY) % (index))+ output.write(yaml % index)client = TestClient(app)start()@@ -72,7 +88,7 @@ class TestEmbeddings(unittest.TestCase):Create API client on creation of class."""- cls.client = TestEmbeddings.start(True)+ cls.client = TestEmbeddings.start(INDEX)cls.data = ["US tops 5 million confirmed virus cases",@@ -250,7 +266,7 @@ class TestEmbeddings(unittest.TestCase):"""# Re-create read-only model- self.client = TestEmbeddings.start(False)+ self.client = TestEmbeddings.start(READONLY)# Test searchquery = urllib.parse.quote("feel good story")@@ -266,3 +282,46 @@ class TestEmbeddings(unittest.TestCase):self.assertEqual(self.client.get("index").status_code, 403)self.assertEqual(self.client.get("upsert").status_code, 403)self.assertEqual(self.client.post("delete", json=[0]).status_code, 403)++ def testXFunctions(self):+ """+ Test API instance with custom functions+ """++ # Re-create model with custom functions+ self.client = TestEmbeddings.start(FUNCTIONS)++ # Index data+ self.client.post("add", json=[{"id": x, "text": row} for x, row in enumerate(self.data)])+ self.client.get("index")++ query = urllib.parse.quote("select elements('text') length from txtai limit 1")+ self.assertEqual(self.client.get(f"search?query={query}").json()[0]["length"], 4)++ query = urllib.parse.quote("select length('text') length from txtai limit 1")+ self.assertEqual(self.client.get(f"search?query={query}").json()[0]["length"], 4)+++class Elements:+ """+ Custom SQL function as callable object.+ """++ def __call__(self, text):+ return length(text)+++def transform(document):+ """+ Custom transform function.+ """++ return document+++def length(text):+ """+ Custom SQL function.+ """++ return len(text)