💡 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 SQL expression columns, closes #338
davidmezzetti60d1c7c2d770
diff --git a/src/python/txtai/database/base.py b/src/python/txtai/database/base.pyindex 3d82a0f8..7147a274 100644--- a/src/python/txtai/database/base.py+++ b/src/python/txtai/database/base.py@@ -5,8 +5,6 @@ Database moduleimport loggingimport types-from inspect import signature-from .encoder import EncoderFactoryfrom .sql import SQL, SQLError, Token@@ -38,8 +36,14 @@ class Database:encoder = self.config.get("objects")self.encoder = EncoderFactory.create(encoder) if encoder else None+ # Custom functions and expressions+ self.functions, self.expressions = None, None+# Load custom functions- self.functions = self.register(self.config)+ self.registerfunctions(self.config)++ # Load custom expressions+ self.registerexpressions(self.config)def load(self, path):"""@@ -214,7 +218,7 @@ class Database:raise NotImplementedError- def register(self, config):+ def registerfunctions(self, config):"""Register custom functions. This method stores the function details for underlyingdatabase implementations to handle.@@ -227,27 +231,42 @@ class Database:if inputs:functions = []for fn in inputs:- name, argcount = None, None+ name, argcount = None, -1# Optional function configurationif isinstance(fn, dict):- name, argcount, fn = fn.get("name"), fn.get("argcount"), fn["function"]+ name, argcount, fn = fn.get("name"), fn.get("argcount", -1), fn["function"]# Determine if this is a callable object or a functionif not isinstance(fn, types.FunctionType) and hasattr(fn, "__call__"):name = name if name else fn.__class__.__name__.lower()- argcount = argcount if argcount else len(signature(fn.__call__).parameters)fn = fn.__call__else:name = name if name else fn.__name__.lower()- argcount = argcount if argcount else len(signature(fn).parameters)# Store function detailsfunctions.append((name, argcount, fn))- return functions+ self.functions = functions++ def registerexpressions(self, config):+ """+ Register custom expressions. This method parses and resolves expressions for later use in SQL queries.++ Args:+ config: database configuration+ """- return None+ inputs = config.get("expressions") if config else None+ if inputs:+ expressions = {}+ for entry in inputs:+ name = entry.get("name")+ expression = entry.get("expression")+ if name and expression:+ expressions[name] = self.sql.snippet(expression)++ self.expressions = expressionsdef execute(self, function, *args):"""diff --git a/src/python/txtai/database/sql/base.py b/src/python/txtai/database/sql/base.pyindex 7b399a28..6dabaa15 100644--- a/src/python/txtai/database/sql/base.py+++ b/src/python/txtai/database/sql/base.py@@ -95,11 +95,28 @@ class SQL:True if this is a valid SQL query, False otherwise"""- # Reduce query to a lower-cased single line stripped of leading/trailing whitespace- query = query.lower().strip(";").replace("\n", " ").replace("\t", " ").strip()+ if isinstance(query, str):+ # Reduce query to a lower-cased single line stripped of leading/trailing whitespace+ query = query.lower().strip(";").replace("\n", " ").replace("\t", " ").strip()- # Detect if this is a valid txtai SQL statement- return query.startswith("select ") and (" from txtai " in query or query.endswith(" from txtai"))+ # Detect if this is a valid txtai SQL statement+ return query.startswith("select ") and (" from txtai " in query or query.endswith(" from txtai"))++ return False++ def snippet(self, text):+ """+ Parses a partial SQL snippet.++ Args:+ text: SQL snippet++ Returns:+ parsed snippet+ """++ tokens, _ = self.tokenize(text)+ return self.expression(tokens)def tokenize(self, query):"""diff --git a/src/python/txtai/database/sqlite.py b/src/python/txtai/database/sqlite.pyindex d2e0fab3..4fd7e497 100644--- a/src/python/txtai/database/sqlite.py+++ b/src/python/txtai/database/sqlite.py@@ -245,6 +245,10 @@ class SQLite(Database):# Build alias clausereturn f'{name} as "{alias}"'+ # Resolve expression+ if self.expressions and name in self.expressions:+ return self.expressions[name]+# Name is already resolved, skipif name.startswith("json_extract(data") or any(f"s.{s}" == name for s in sections):return namediff --git a/src/python/txtai/embeddings/functions.py b/src/python/txtai/embeddings/functions.pynew file mode 100644index 00000000..c9d4c31d--- /dev/null+++ b/src/python/txtai/embeddings/functions.py@@ -0,0 +1,127 @@+"""+Functions module+"""++from types import FunctionType, MethodType+++class Functions:+ """+ Resolves function configuration to function references.+ """++ def __init__(self, embeddings):+ """+ Creates a new function resolver.++ Args:+ embeddings: embeddings instance+ """++ self.embeddings = embeddings++ def __call__(self, config):+ """+ Resolves a list of functions to function references.++ Args:+ config: configuration++ Returns:+ list of function references+ """++ # Resolve callable functions+ functions = []+ for fn in config["functions"]:+ if isinstance(fn, dict):+ fn = fn.copy()+ fn["function"] = self.function(fn["function"])+ else:+ fn = self.function(fn)+ functions.append(fn)++ return functions++ def function(self, function):+ """+ Resolves function configuration. If function is a string, it's split on '.' and each part+ is separately resolved to an object, attribute or function. Each part is resolved upon the+ first invocation of the function. Otherwise, the input is returned.++ Args:+ function: function configuration++ Returns:+ function reference+ """++ if isinstance(function, str):+ parts = function.split(".")++ if hasattr(self.embeddings, parts[0]):+ m = Reference(self.embeddings, parts[0])+ else:+ module = ".".join(parts[:-1])+ m = __import__(module)++ for comp in parts[1:]:+ m = Reference(m, comp)++ return m++ return function+++class Reference:+ """+ Stores a reference to an object attribute. This attribute is resolved by invoking the __call__ method.+ This allows for functions to be independent of the initialization order of an embeddings instance.+ """++ def __init__(self, obj, attribute):+ """+ Create a new reference.++ Args:+ obj: object handle+ attribute: attribute name+ """++ # Object handle and attribute+ self.obj = obj+ self.attribute = attribute++ # True if the object and attribute have been resolved+ self.resolved = False++ # True if the attribute is a function+ self.function = None++ def __call__(self, *args):+ """+ Resolves an object attribute reference. If the attribute is a function, the function is executed.+ Otherwise, the object attribute value is returned.++ Args:+ args: list of function arguments to the object attribute, when attribute is a function++ Returns:+ object attribute function result or object attribute value+ """++ # Resolve nested function arguments, if necessary+ if not self.resolved:+ self.obj = self.obj() if isinstance(self.obj, Reference) else self.obj+ self.attribute = self.attribute() if isinstance(self.attribute, Reference) else self.attribute+ self.resolved = True++ # Lookup attribute+ attribute = getattr(self.obj, self.attribute)++ # Determine if attribute is a function+ if self.function is None:+ self.function = isinstance(attribute, (FunctionType, MethodType)) or (hasattr(attribute, "__call__") and args)++ # If attribute is a function, execute and return, otherwise return attribute+ return attribute(*args) if self.function else attributediff --git a/test/python/testdatabase/testembeddings.py b/test/python/testdatabase/testembeddings.pyindex 8072ca79..2ee7cc6b 100644--- a/test/python/testdatabase/testembeddings.py+++ b/test/python/testdatabase/testembeddings.py@@ -212,6 +212,27 @@ class TestEmbeddings(unittest.TestCase):self.assertEqual(self.embeddings.explain("select * from txtai limit 1")[0]["id"], "0")+ def testFunction(self):+ """+ Test custom functions+ """++ embeddings = Embeddings(+ {+ "path": "sentence-transformers/nli-mpnet-base-v2",+ "content": True,+ "functions": [{"name": "length", "function": "testdatabase.testembeddings.length"}],+ }+ )++ # Create an index for the list of text+ embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])++ # Search for best match+ result = embeddings.search("select length(text) length from txtai where id = 0", 1)[0]++ self.assertEqual(result["length"], 39)+def testGenerator(self):"""Test index with a generator@@ -497,3 +518,11 @@ class TestEmbeddings(unittest.TestCase):self.assertEqual(result["text"], data[0][1])finally:del self.embeddings.config["batch"]+++def length(text):+ """+ Custom SQL function.+ """++ return len(text)diff --git a/test/python/testdatabase/testsql.py b/test/python/testdatabase/testsql.pyindex 342be47e..1e8aed1c 100644--- a/test/python/testdatabase/testsql.py+++ b/test/python/testdatabase/testsql.py@@ -110,6 +110,14 @@ class TestSQL(unittest.TestCase):self.assertSql("having", prefix + "group by text having count(*) > 1", "count(*) > 1")self.assertSql("having", prefix + "where flag = 1 group by text having count(*) > 1", "count(*) > 1")+ def testIsSQL(self):+ """+ Tests SQL detection method.+ """++ self.assertTrue(self.sql.issql("select text from txtai where id = 1"))+ self.assertFalse(self.sql.issql(1234))+def testLimit(self):"""Test limit clauses