💡 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 new workflow functionality, closes #155
davidmezzetti361371903c0d
diff --git a/src/python/txtai/api/base.py b/src/python/txtai/api/base.pyindex 60dd0e04..2b89c1f9 100644--- a/src/python/txtai/api/base.py+++ b/src/python/txtai/api/base.py@@ -53,7 +53,7 @@ class API:self.pipelines = {}# Default pipelines- pipelines = ["extractor", "labels", "segmentation", "similarity", "summary", "tabular", "textractor", "transcription", "translation"]+ pipelines = ["extractor", "labels", "nop", "segmentation", "similarity", "summary", "tabular", "textractor", "transcription", "translation"]# Add custom pipelinesfor key in self.config:@@ -81,23 +81,70 @@ class API:# Workflow definitionsself.workflows = {}- # Post workflow actions- self.actions = {}-# Create workflowsif "workflow" in self.config:for workflow, config in self.config["workflow"].items():+ # Resolve callable functionsfor task in config["tasks"]:- # Resolve pipeline action- if "action" in task:- action = task["action"]- task["action"] = self.pipelines.get(action)-- if action in ["index", "upsert"]:- self.actions[workflow] = action+ self.resolve(task)self.workflows[workflow] = WorkflowFactory.create(config)+ def resolve(self, task):+ """+ Resolves callable functions for a task.++ Args:+ task: input task config+ """++ if "action" in task:+ action = task["action"]+ values = [action] if not isinstance(action, list) else action++ actions = []+ for a in values:+ if a in ["index", "upsert"]:+ # Add queue action to buffer documents to index+ actions.append(self.add)++ # Override and disable unpacking for indexing actions+ task["unpack"] = False++ # Add finalize to trigger indexing+ task["finalize"] = self.upsert if a == "upsert" else self.index+ else:+ # Resolve action to callable function+ actions.append(self.function(a))++ # Save resolved action(s)+ task["action"] = actions[0] if not isinstance(action, list) else actions++ # Resolve initializer+ if "initialize" in task and isinstance(task["initialize"], str):+ task["initialize"] = self.function(task["initialize"])++ # Resolve finalizer+ if "finalize" in task and isinstance(task["finalize"], str):+ task["finalize"] = self.function(task["finalize"])++ def function(self, function):+ """+ Get a handle to a callable function+ """++ if function in self.pipelines:+ return self.pipelines[function]++ # pylint: disable=W0702+ try:+ # Attempt to resolve action as a callable function+ return PipelineFactory.create({}, function)+ except:+ pass++ return None+def limit(self, limit):"""Parses the number of results to return from the request. Allows range of 1-250, with a default of 10.@@ -167,6 +214,9 @@ class API:Args:documents: list of {id: value, text: value}++ Returns:+ unmodified input documents"""if self.cluster:@@ -177,8 +227,28 @@ class API:if not self.documents:self.documents = Documents()+ batch = []+ index = self.count() + len(self.documents)+ for document in documents:+ if isinstance(document, dict):+ # Copy value from dict to a new tuple+ document = (document["id"], document["text"], None)+ elif isinstance(document, str):+ # Add uid via autosequence+ document = (index, document, None)+ index += 1+ elif isinstance(document, tuple) and len(document) < 3:+ # Copy partial tuple+ document = (document[0], document[1], None)++ # Add document tuple (id, text, element)+ batch.append(document)+# Add batch- self.documents.add([(document["id"], document["text"], None) for document in documents])+ self.documents.add(batch)++ # Return unmodified input documents+ return documentsdef index(self):"""@@ -404,29 +474,4 @@ class API:elements = [tuple(element) if isinstance(element, list) else element for element in elements]# Execute workflow- elements = self.workflows[name](elements)-- # Run post workflow action, if any- if name in self.actions:- documents = []- action = self.actions[name]- index = self.count() if self.count() and action != "index" else 0-- # Consume all elements- elements = list(elements)-- for element in elements:- if isinstance(element, (tuple, list)):- element = {"id": element[0], "text": element[1]}- else:- element = {"id": index, "text": element}-- documents.append(element)- index += 1-- # pylint: disable=W0106- # Add documents and run index operation- self.add(documents)- self.index() if self.actions[name] == "index" else self.upsert()-- return elements+ return self.workflows[name](elements)diff --git a/src/python/txtai/embeddings/documents.py b/src/python/txtai/embeddings/documents.pyindex 3e04da1f..c74efdde 100644--- a/src/python/txtai/embeddings/documents.py+++ b/src/python/txtai/embeddings/documents.py@@ -19,6 +19,14 @@ class Documents:self.documents = Noneself.batch = 0+ self.size = 0++ def __len__(self):+ """+ Returns total number of queued documents.+ """++ return self.sizedef __iter__(self):"""@@ -55,6 +63,7 @@ class Documents:# Add batchpickle.dump(documents, self.documents)self.batch += 1+ self.size += len(documents)return documents@@ -69,3 +78,4 @@ class Documents:# Reset document parametersself.documents = Noneself.batch = 0+ self.size = 0diff --git a/src/python/txtai/workflow/base.py b/src/python/txtai/workflow/base.pyindex 3859c44a..83e527a4 100644--- a/src/python/txtai/workflow/base.py+++ b/src/python/txtai/workflow/base.py@@ -25,12 +25,16 @@ class Workflow:Executes a workflow for input elements.Args:- elements: list of data elements+ elements: iterable data elementsReturns:transformed data elements"""+ # Run task initializers+ self.initialize()++ # Process elements in batches.batch = []for x in elements:batch.append(x)@@ -39,9 +43,23 @@ class Workflow:yield from self.process(batch)batch = []+ # Final batchif batch:yield from self.process(batch)+ # Run task finalizers+ self.finalize()++ def initialize(self):+ """+ Runs task initializer methods (if any) before processing data.+ """++ # Run task initializers+ for task in self.tasks:+ if task.initialize:+ task.initialize()+def process(self, elements):"""Processes a batch of data elements.@@ -58,7 +76,7 @@ class Workflow:indexed = list(enumerate(elements))# Filter data down to data this task handles- data = [(x, self.unpack(element) if task.unpack else element) for x, element in indexed if task.accept(self.unpack(element))]+ data = [(x, task.upack(element)) for x, element in indexed if task.accept(task.upack(element, True))]# Get list of filtered process idsids = [x for x, _ in data]@@ -75,10 +93,10 @@ class Workflow:if isinstance(result, list):# One-many transformations- elements.extend([self.pack(element, r) if task.unpack else r for r in result])+ elements.extend([task.pack(element, r) for r in result])else:# One-one transformations- elements.append(self.pack(element, result) if task.unpack else result)+ elements.append(task.pack(element, result))else:# Pass unprocessed elements throughelements.append(element)@@ -86,44 +104,12 @@ class Workflow:# Remove process index and yield resultsyield from elements- def unpack(self, element):- """- Unpacks data for processing.-- Args:- element: input data element-- Returns:- data- """-- # Extract data from (id, data, tag) formatted elements- if isinstance(element, tuple):- return element[1]-- return element-- def pack(self, element, data):+ def finalize(self):"""- Packs data for delivery to the next workflow task.-- Args:- element: transformed data element- data: item to pack element into-- Returns:- packed data+ Runs task finalizer methods (if any) after all data processed."""- # Package data into (id, data, tag) formatted elements- if isinstance(element, tuple):- # If new data is a (id, data, tag) tuple use that- if isinstance(data, tuple):- return data-- # Create a copy of tuple, update data element and return- element = list(element)- element[1] = data- return tuple(element)-- return data+ # Run task finalizers+ for task in self.tasks:+ if task.finalize:+ task.finalize()diff --git a/src/python/txtai/workflow/task/base.py b/src/python/txtai/workflow/task/base.pyindex 968bfa49..ecd625f9 100644--- a/src/python/txtai/workflow/task/base.py+++ b/src/python/txtai/workflow/task/base.py@@ -10,20 +10,34 @@ class Task:Base class for all workflow tasks."""- def __init__(self, action=None, select=None, unpack=True):+ def __init__(self, action=None, select=None, unpack=True, column=None, merge="hstack", initialize=None, finalize=None):"""Creates a new task. A task defines two methods, type of data it accepts and the action to execute- for each data element. Actions are callable functions.+ for each data element. Action is a callable function or list of callable functions.Args:- action: action to execute on each data element+ action: action(s) to execute on each data elementselect: filter(s) used to select data to processunpack: if data elements should be unpacked or unwrapped from (id, data, tag) tuples+ column: column index to select if element is a tuple, defaults to all+ merge: merge mode for joining multi-action outputs+ initialize: action to execute before processing+ finalize: action to execute after processing"""+ # Standardize into list of actions+ if not action:+ action = []+ elif not isinstance(action, list):+ action = [action]+self.action = actionself.select = selectself.unpack = unpack+ self.column = column+ self.merge = merge+ self.initialize = initialize+ self.finalize = finalizedef __call__(self, elements):"""@@ -39,7 +53,7 @@ class Task:# Run data preparation routineselements = [self.prepare(element) for element in elements]- # Run data elements through workflow execution+ # Run data elements through task executionreturn self.execute(elements)def accept(self, element):@@ -55,6 +69,49 @@ class Task:return (isinstance(element, str) and re.search(self.select, element.lower())) if element and self.select else True+ def upack(self, element, force=False):+ """+ Unpacks data for processing.++ Args:+ element: input data element+ force: if true data is unpacked even if task has unpack set to False++ Returns:+ data+ """++ # Extract data from (id, data, tag) formatted elements+ if (self.unpack or force) and isinstance(element, tuple):+ return element[1]++ return element++ def pack(self, element, data):+ """+ Packs data after processing.++ Args:+ element: transformed data element+ data: item to pack element into++ Returns:+ packed data+ """++ # Pack data into (id, data, tag) formatted elements+ if self.unpack and isinstance(element, tuple):+ # If new data is a (id, data, tag) tuple use that except for multi-action "hstack" merges which produce tuples+ if isinstance(data, tuple) and (len(self.action) <= 1 or self.merge != "hstack"):+ return data++ # Create a copy of tuple, update data element and return+ element = list(element)+ element[1] = data+ return tuple(element)++ return data+def prepare(self, element):"""Method that allows downstream tasks to prepare data element for processing.@@ -70,7 +127,7 @@ class Task:def execute(self, elements):"""- Executes action on elements.+ Executes action(s) on elements.Args:elements: list of data elements@@ -79,4 +136,115 @@ class Task:transformed data elements"""- return self.action(elements) if self.action else elements+ if self.action:+ # Run actions+ outputs = []+ for x, action in enumerate(self.action):+ # Filter elements by column index if necessary - supports a single int or an action index to column index mapping+ index = self.column[x] if isinstance(self.column, dict) else self.column+ inputs = [self.extract(e, index) for e in elements] if index is not None else elements++ # Run action and add outputs+ outputs.append(action(inputs))++ # Run post process operations+ return self.postprocess(outputs)++ return elements++ def extract(self, element, index):+ """+ Extracts a column from element by index if the element is a tuple.++ Args:+ element: input element+ index: column index++ Returns:+ extracted column+ """++ if isinstance(element, tuple):+ if not self.unpack and len(element) == 3 and isinstance(element[1], tuple):+ return (element[0], element[1][index], element[2])++ return element[index]++ return element++ def postprocess(self, outputs):+ """+ Runs post process routines after a task action.++ Args:+ outputs: task outputs++ Returns:+ postprocessed outputs+ """++ # Unpack single action tasks+ if len(self.action) == 1:+ return outputs[0]++ if self.merge == "vstack":+ return self.vstack(outputs)+ if self.merge == "concat":+ return self.concat(outputs)++ # Default mode is hstack+ return self.hstack(outputs)++ def vstack(self, outputs):+ """+ Merges outputs row-wise. Returns a list of lists which will be interpreted by workflows as a one-many transformation.++ # Row-wise merge example (2 actions)+ # Inputs: [a, b, c]+ # Outputs => [[a1, b1, c1], [a2, b2, c2]]+ # Row Merge => [[a1, a2], [b1, b2], [c1, c2]] = [a1, a2, b1, b2, c1, c2]++ Args:+ outputs: task outputs++ Returns:+ list of aggregated/zipped outputs as lists (row-wise)+ """++ return [list(x) for x in zip(*outputs)]++ def hstack(self, outputs):+ """+ Merges outputs column-wise. Returns a list of tuples which will be interpreted by workflows as a one-one transformation.++ # Column-wise merge example (2 actions)+ # Inputs: [a, b, c]+ # Outputs => [[a1, b1, c1], [a2, b2, c2]]+ # Column Merge => [(a1, a2), (b1, b2), (c1, c2)]++ Args:+ outputs: task outputs++ Returns:+ list of aggregated/zipped outputs as tuples (column-wise)+ """++ return list(zip(*outputs))++ def concat(self, outputs):+ """+ Merges outputs column-wise and concats values together into a string. Returns a list of strings.++ # Concat merge example (2 actions)+ # Inputs: [a, b, c]+ # Outputs => [[a1, b1, c1], [a2, b2, c2]]+ # Concat Merge => [(a1, a2), (b1, b2), (c1, c2)] => ["a1. a2", "b1. b2", "c1. c2"]++ Args:+ outputs: task outputs++ Returns:+ list of concat outputs+ """++ return [". ".join([str(y) for y in x if y]) for x in self.hstack(outputs)]diff --git a/src/python/txtai/workflow/task/factory.py b/src/python/txtai/workflow/task/factory.pyindex 987f6417..b73192c0 100644--- a/src/python/txtai/workflow/task/factory.py+++ b/src/python/txtai/workflow/task/factory.py@@ -2,6 +2,8 @@Task factory module"""+import functools+class TaskFactory:"""@@ -50,7 +52,25 @@ class TaskFactory:if "args" in config:args = config.pop("args")action = config["action"]- config["action"] = lambda x: action(x, *args)+ if action:+ if isinstance(action, list):+ config["action"] = [Partial(a, *args[i]) if args[i] else Partial(a) for i, a in enumerate(action)]+ else:+ config["action"] = lambda x: action(x, *args)# Get Task instancereturn TaskFactory.get(task)(**config)+++class Partial(functools.partial):+ """+ Modifies functools.partial to prepend arguments vs append.+ """++ def __call__(self, *args, **kwargs):+ # Update keyword arguments+ kw = self.keywords.copy()+ kw.update(kwargs)++ # Execute function with new arguments prepended to default arguments+ return self.func(*(args + self.args), **kw)diff --git a/src/python/txtai/workflow/task/image.py b/src/python/txtai/workflow/task/image.pyindex 8c44444d..ee14d332 100644--- a/src/python/txtai/workflow/task/image.py+++ b/src/python/txtai/workflow/task/image.py@@ -20,11 +20,12 @@ class ImageTask(FileTask):Task that processes image file urls"""- def __init__(self, action=None, select=None, unpack=True):+ def __init__(self, action=None, select=None, unpack=True, column=None, merge="hstack", initialize=None, finalize=None):+if not PIL:raise ImportError('ImageTask is not available - install "workflow" extra to enable')- super().__init__(action, select, unpack)+ super().__init__(action, select, unpack, column, merge, initialize, finalize)def accept(self, element):# Only accept image filesdiff --git a/src/python/txtai/workflow/task/retrieve.py b/src/python/txtai/workflow/task/retrieve.pyindex dea6b165..c3e144e7 100644--- a/src/python/txtai/workflow/task/retrieve.py+++ b/src/python/txtai/workflow/task/retrieve.py@@ -15,8 +15,8 @@ class RetrieveTask(UrlTask):Task that retrieves urls (local or remote) to a local directory."""- def __init__(self, action=None, select=None, unpack=True, directory=None):- super().__init__(action, select, unpack)+ def __init__(self, action=None, select=None, unpack=True, column=None, merge="hstack", initialize=None, finalize=None, directory=None):+ super().__init__(action, select, unpack, column, merge, initialize, finalize)# Create default temporary directory if not specifiedif not directory:diff --git a/src/python/txtai/workflow/task/service.py b/src/python/txtai/workflow/task/service.pyindex c2a5ae96..1d5d14f4 100644--- a/src/python/txtai/workflow/task/service.py+++ b/src/python/txtai/workflow/task/service.py@@ -19,11 +19,26 @@ class ServiceTask(Task):Task to runs requests against remote service urls."""- def __init__(self, action=None, select=None, unpack=True, url=None, method=None, params=None, batch=True, extract=None):+ # pylint: disable=R0913+ def __init__(+ self,+ action=None,+ select=None,+ unpack=True,+ column=None,+ merge="hstack",+ initialize=None,+ finalize=None,+ url=None,+ method=None,+ params=None,+ batch=True,+ extract=None,+ ):if not XML_TO_DICT:raise ImportError('ServiceTask is not available - install "workflow" extra to enable')- super().__init__(action, select, unpack)+ super().__init__(action, select, unpack, column, merge, initialize, finalize)# Save URL, method and parameter defaultsself.url = urldiff --git a/src/python/txtai/workflow/task/storage.py b/src/python/txtai/workflow/task/storage.pyindex c0ea66a8..b421bcde 100644--- a/src/python/txtai/workflow/task/storage.py+++ b/src/python/txtai/workflow/task/storage.py@@ -25,39 +25,37 @@ class StorageTask(Task):PREFIX = r"(\w+):\/\/.*"PATH = r"\w+:\/\/(.*)"- def __init__(self, action=None, select=None, unpack=True, ids=True):+ def __init__(self, action=None, select=None, unpack=True):if not LIBCLOUD:raise ImportError('StorageTask is not available - install "workflow" extra to enable')super().__init__(action, select, unpack)- # If true, elements returned will be tagged with ids and converted into (id, data, tag) tuples- self.ids = ids-def accept(self, element):# Only accept file URLs- return super().accept(element) and re.match(StorageTask.PREFIX, element.lower())+ return re.match(StorageTask.PREFIX, element.lower())- def execute(self, elements):- # List contents of each bucket- buckets = [self.list(element) for element in elements]+ def faccept(self, element):+ """+ Determines if this task can handle the input data format.++ Args:+ element: input file url- elements = []- for bucket in buckets:- # Execute actions- content = super().execute(bucket)+ Returns:+ True if url is accepted, False otherwise+ True if this task can process this data element, False otherwise+ """- # Combine with content ids if necessary- if self.ids:- values = []- for x, url in enumerate(bucket):- values.append((url, content[x], None))- else:- values = content+ return super().accept(element)- elements.append(values)+ def execute(self, elements):+ # Create aggregated directory listing for all elements+ outputs = []+ for element in elements:+ outputs.append(super().execute([url for url in self.list(element) if self.faccept(url)]))- return elements+ return outputsdef list(self, element):"""diff --git a/src/python/txtai/workflow/task/workflow.py b/src/python/txtai/workflow/task/workflow.pyindex 8dd63418..8ebcd5ef 100644--- a/src/python/txtai/workflow/task/workflow.py+++ b/src/python/txtai/workflow/task/workflow.py@@ -11,4 +11,4 @@ class WorkflowTask(Task):"""def __call__(self, elements):- return list(super().__call__(elements))+ return [list(result) for result in super().__call__(elements)]diff --git a/test/python/testapi/testworkflow.py b/test/python/testapi/testworkflow.pyindex 107e509e..eaa23009 100644--- a/test/python/testapi/testworkflow.py+++ b/test/python/testapi/testworkflow.py@@ -26,6 +26,8 @@ embeddings:labels:path: prajjwal1/bert-medium-mnli+nop:+# Text segmentationsegmentation:sentences: true@@ -35,7 +37,19 @@ workflow:labels:tasks:- action: labels+ initialize: testnotfoundargs: [[positive, negative]]+ multiaction:+ tasks:+ - action:+ - labels+ - nop+ initialize: testapi.testworkflow.TestInitFinal+ finalize: testapi.testworkflow.TestInitFinal+ merge: concat+ args:+ - [[positive, negative], false, True]+ - nullsegment:tasks:- action: segmentation@@ -184,17 +198,37 @@ class TestWorkflow(unittest.TestCase):self.assertEqual(len(results), 1)- def testWorkflow(self):+ def testWorkflowLabels(self):"""- Test workflow via API.+ Test workflow with labels via API."""- text = "This is a test sentence. And another sentence to split."+ text = "This is the best"+results = self.client.post("workflow", json={"name": "labels", "elements": [text]}).json()- self.assertEqual(len(results), 2)+ self.assertEqual(results[0][0], 0)++ results = self.client.post("workflow", json={"name": "multiaction", "elements": [text]}).json()+ self.assertEqual(results[0], "['positive']. This is the best")++ def testWorkflowSegment(self):+ """+ Test workflow with segmentation via API.+ """++ text = "This is a test sentence. And another sentence to split."results = self.client.post("workflow", json={"name": "segment", "elements": [text]}).json()self.assertEqual(len(results), 2)results = self.client.post("workflow", json={"name": "segment", "elements": [[0, text]]}).json()self.assertEqual(len(results), 2)+++class TestInitFinal:+ """+ Class to test task initialize and finalize calls.+ """++ def __call__(self):+ passdiff --git a/test/python/testworkflow.py b/test/python/testworkflow.pyindex 5e1a581d..7f9c3a20 100644--- a/test/python/testworkflow.py+++ b/test/python/testworkflow.py@@ -2,6 +2,8 @@Workflow module tests"""+import os+import tempfileimport unittestfrom txtai.embeddings import Documents, Embeddings@@ -72,6 +74,22 @@ class TestWorkflow(unittest.TestCase):index, _ = embeddings.search("search text", 1)[0]self.assertEqual(index, 0)+ def testExtractWorkflow(self):+ """+ Tests column extraction tasks+ """++ workflow = Workflow([Task(lambda x: x, unpack=False, column=0)], batch=1)++ results = list(workflow([(0, 1)]))+ self.assertEqual(results[0], 0)++ results = list(workflow([(0, (1, 2), None)]))+ self.assertEqual(results[0], (0, 1, None))++ results = list(workflow([1]))+ self.assertEqual(results[0], 1)+def testImageWorkflow(self):"""Tests an image task@@ -83,13 +101,47 @@ class TestWorkflow(unittest.TestCase):self.assertEqual(results[0].size, (1024, 682))+ def testMergeWorkflow(self):+ """+ Tests merge tasks+ """++ task = Task([lambda x: [pow(y, 2) for y in x], lambda x: [pow(y, 3) for y in x]], merge="hstack")++ # Test hstack (column-wise) merge+ workflow = Workflow([task])+ results = list(workflow([2]))+ self.assertEqual(results, [(4, 8)])++ # Test vstack (row-wise) merge+ task.merge = "vstack"+ workflow = Workflow([task])+ results = list(workflow([2]))+ self.assertEqual(results, [4, 8])++ # Test concat (values joined into single string) merge+ task.merge = "concat"+ workflow = Workflow([task])+ results = list(workflow([2]))+ self.assertEqual(results, ["4. 8"])++ # Test generated (id, data, tag) tuples are properly returned+ workflow = Workflow([Task(lambda x: [(0, y, None) for y in x])])+ results = list(workflow([(1, "text", "tags")]))+ self.assertEqual(results[0], (0, "text", None))+def testRetrieveWorkflow(self):"""Tests a retrieve task"""+ # Test retrieve with generated temporary directoryworkflow = Workflow([RetrieveTask()])+ results = list(workflow(["file://" + Utils.PATH + "/books.jpg"]))+ self.assertTrue(results[0].endswith("books.jpg"))+ # Test retrieve with specified temporary directory+ workflow = Workflow([RetrieveTask(directory=os.path.join(tempfile.gettempdir(), "retrieve"))])results = list(workflow(["file://" + Utils.PATH + "/books.jpg"]))self.assertTrue(results[0].endswith("books.jpg"))