💡 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
Process task actions concurrently, closes #164
davidmezzettiffb371311413
diff --git a/src/python/txtai/workflow/__init__.py b/src/python/txtai/workflow/__init__.pyindex 5aab278e..24e56efc 100644--- a/src/python/txtai/workflow/__init__.py+++ b/src/python/txtai/workflow/__init__.py@@ -3,5 +3,6 @@ Workflow imports"""from .base import Workflow+from .execute import Executefrom .factory import WorkflowFactoryfrom .task import *diff --git a/src/python/txtai/workflow/base.py b/src/python/txtai/workflow/base.pyindex 8c8dacc5..f8bc5c79 100644--- a/src/python/txtai/workflow/base.py+++ b/src/python/txtai/workflow/base.py@@ -2,23 +2,30 @@Workflow module"""+from .execute import Execute+class Workflow:"""Base class for all workflows."""- def __init__(self, tasks, batch=100):+ def __init__(self, tasks, batch=100, workers=None):"""Creates a new workflow. Workflows are lists of tasks to execute.Args:tasks: list of workflow tasksbatch: how many items to process at a time, defaults to 100+ workers: number of concurrent workers"""self.tasks = tasksself.batch = batch+ self.workers = workers++ # Set default number of executor workers to max number of actions in a task+ self.workers = max(len(task.action) for task in self.tasks) if not self.workers else self.workersdef __call__(self, elements):"""@@ -31,15 +38,17 @@ class Workflow:transformed data elements"""- # Run task initializers- self.initialize()+ # Create execute instance for this run+ with Execute(self.workers) as executor:+ # Run task initializers+ self.initialize()- # Process elements in batches- for batch in self.chunk(elements):- yield from self.process(batch)+ # Process elements in batches+ for batch in self.chunk(elements):+ yield from self.process(batch, executor)- # Run task finalizers- self.finalize()+ # Run task finalizers+ self.finalize()def initialize(self):"""@@ -82,12 +91,13 @@ class Workflow:if batch:yield batch- def process(self, elements):+ def process(self, elements, executor):"""Processes a batch of data elements.Args:elements: iterable data elements+ executor: execute instance, enables concurrent task actionsReturns:transformed data elements@@ -95,7 +105,7 @@ class Workflow:# Run elements through each taskfor task in self.tasks:- elements = task(elements)+ elements = task(elements, executor)# Yield results processed by all tasksyield from elementsdiff --git a/src/python/txtai/workflow/execute.py b/src/python/txtai/workflow/execute.pynew file mode 100644index 00000000..24ee9cad--- /dev/null+++ b/src/python/txtai/workflow/execute.py@@ -0,0 +1,97 @@+"""+Execute module+"""++from multiprocessing.pool import Pool, ThreadPool++import torch.multiprocessing+++class Execute:+ """+ Supports sequential, multithreading and multiprocessing based execution of tasks.+ """++ def __init__(self, workers=None):+ """+ Creates a new execute instance. Functions can be executed sequentially, in a thread pool+ or in a process pool. Once created, the thread and/or process pool will stay open until the+ close method is called.++ Args:+ workers: number of workers for thread/process pools+ """++ # Number of workers to use in thread/process pools+ self.workers = workers++ self.thread = None+ self.process = None++ def __del__(self):+ self.close()++ def __enter__(self):+ return self++ def __exit__(self, etype, value, traceback):+ self.close()++ def run(self, method, function, args):+ """+ Runs multiple calls of function for each tuple in args. The method parameter controls if the calls are+ sequential (method = None), multithreaded (method = "thread") or with multiprocessing (method="process").++ Args:+ method: run method - "thread" for multithreading, "process" for multiprocessing, otherwise runs sequentially+ function: function to run+ args: list of tuples with arguments to each call+ """++ # Concurrent processing+ if method and len(args) > 1:+ pool = self.pool(method)+ if pool:+ return pool.starmap(function, args, 1)++ # Sequential processing+ return [function(*arg) for arg in args]++ def pool(self, method):+ """+ Gets a handle to a concurrent processing pool. This method will create the pool if it doesn't already exist.++ Args:+ method: pool type - "thread" or "process"++ Returns:+ concurrent processing pool or None if no pool of that type available+ """++ if method == "thread":+ if not self.thread:+ self.thread = ThreadPool(self.workers)++ return self.thread++ if method == "process":+ if not self.process:+ # Importing torch.multiprocessing will register torch shared memory serialization for cuda+ self.process = Pool(self.workers, context=torch.multiprocessing.get_context("spawn"))++ return self.process++ return None++ def close(self):+ """+ Closes concurrent processing pools.+ """++ if self.thread:+ self.thread.close()+ self.thread = None++ if self.process:+ self.process.close()+ self.process = Nonediff --git a/src/python/txtai/workflow/task/base.py b/src/python/txtai/workflow/task/base.pyindex 36efbb0f..8709212e 100644--- a/src/python/txtai/workflow/task/base.py+++ b/src/python/txtai/workflow/task/base.py@@ -13,7 +13,9 @@ class Task:Base class for all workflow tasks."""- def __init__(self, action=None, select=None, unpack=True, column=None, merge="hstack", initialize=None, finalize=None):+ def __init__(+ self, action=None, select=None, unpack=True, column=None, merge="hstack", initialize=None, finalize=None, concurrency=None, **kwargs+ ):"""Creates a new task. A task defines two methods, type of data it accepts and the action to executefor each data element. Action is a callable function or list of callable functions.@@ -26,6 +28,9 @@ class Task:merge: merge mode for joining multi-action outputs, defaults to hstackinitialize: action to execute before processingfinalize: action to execute after processing+ concurrency: sets concurrency method when execute instance available+ valid values: "thread" for thread-based concurrency, "process" for process-based concurrency+ kwargs: additional keyword arguments"""# Standardize into list of actions@@ -41,30 +46,41 @@ class Task:self.merge = mergeself.initialize = initializeself.finalize = finalize+ self.concurrency = concurrency- def __call__(self, elements):+ # Check for custom registration. Adds additional instance members and validates required dependencies available.+ if hasattr(self, "register"):+ self.register(**kwargs)+ elif kwargs:+ # Raise error if additional keyword arguments passed in without register method+ kwargs = ", ".join(f"'{kw}'" for kw in kwargs)+ raise TypeError(f"__init__() got unexpected keyword arguments: {kwargs}")++ def __call__(self, elements, executor=None):"""Executes action for a list of data elements.Args:elements: iterable data elements+ executor: execute instance, enables concurrent task actionsReturns:transformed data elements"""if isinstance(elements, list):- return self.filteredrun(elements)+ return self.filteredrun(elements, executor)- return self.run(elements)+ return self.run(elements, executor)- def filteredrun(self, elements):+ def filteredrun(self, elements, executor):"""Executes a filtered run, which will tag all inputs with a process id, filter elements down to elements thetask can handle and execute on that subset. Items not selected for processing will be returned unmodified.Args:elements: iterable data elements+ executor: execute instance, enables concurrent task actionsReturns:transformed data elements@@ -80,7 +96,7 @@ class Task:ids = [x for x, _ in data]# Prepare elements and execute task action(s)- results = self.execute([self.prepare(element) for _, element in data])+ results = self.execute([self.prepare(element) for _, element in data], executor)# Pack results back into elementsif self.merge:@@ -122,19 +138,20 @@ class Task:return elements- def run(self, elements):+ def run(self, elements, executor):"""Executes a task run for elements. A standard run processes all elements.Args:elements: iterable data elements+ executor: execute instance, enables concurrent task actionsReturns:transformed data elements"""# Execute task actions- results = self.execute(elements)+ results = self.execute(elements, executor)# Handle one to many transformationsif isinstance(results, list):@@ -220,12 +237,13 @@ class Task:return element- def execute(self, elements):+ def execute(self, elements, executor):"""Executes action(s) on elements.Args:elements: list of data elements+ executor: execute instance, enables concurrent task actionsReturns:transformed data elements@@ -239,8 +257,12 @@ class Task:index = self.column[x] if isinstance(self.column, dict) else self.columninputs = [self.extract(e, index) for e in elements] if index is not None else elements- # Run action and add outputs- outputs.append(self.process(action, inputs))+ # Queue arguments for executor, process immediately if no executor available+ outputs.append((action, inputs) if executor else self.process(action, inputs))++ # Run with executor if available+ if executor:+ outputs = executor.run(self.concurrency, self.process, outputs)# Run post process operationsreturn self.postprocess(outputs)@@ -280,13 +302,7 @@ class Task:"""# Execute action and get outputs- outputs = action(inputs)-- # Wrap one to many transformations if necessary- if isinstance(outputs, list):- outputs = [OneToMany(output) if isinstance(output, list) else output for output in outputs]-- return outputs+ return action(inputs)def postprocess(self, outputs):"""@@ -301,7 +317,7 @@ class Task:# Unpack single action tasksif len(self.action) == 1:- return outputs[0]+ return self.single(outputs[0])# Return unmodified outputs when merge set to Noneif not self.merge:@@ -315,6 +331,23 @@ class Task:# Default mode is hstackreturn self.hstack(outputs)+ def single(self, outputs):+ """+ Post processes and returns single action outputs.++ Args:+ outputs: outputs from a single task++ Returns:+ post processed outputs+ """++ if isinstance(outputs, list):+ # Wrap one to many transformations+ outputs = [OneToMany(output) if isinstance(output, list) else output for output in outputs]++ return outputs+def vstack(self, outputs):"""Merges outputs row-wise. Returns a list of lists which will be interpreted as a one to many transformation.@@ -343,8 +376,19 @@ class Task:if all(torch.is_tensor(output) for output in outputs):return torch.cat(tuple(torch.stack(outputs, axis=1)))- # Wrap as one to many transforms- return [OneToMany(x) for x in zip(*outputs)]+ # Flatten into lists of outputs per input row. Wrap as one to many transformation.+ merge = []+ for x in zip(*outputs):+ combine = []+ for y in x:+ if isinstance(y, list):+ combine.extend(y)+ else:+ combine.append(y)++ merge.append(OneToMany(combine))++ return mergedef hstack(self, outputs):"""@@ -415,6 +459,3 @@ class OneToMany:def __iter__(self):return self.values.__iter__()-- def __str__(self):- return self.values.__str__()diff --git a/src/python/txtai/workflow/task/image.py b/src/python/txtai/workflow/task/image.pyindex 29cccf86..f6a2e9f9 100644--- a/src/python/txtai/workflow/task/image.py+++ b/src/python/txtai/workflow/task/image.py@@ -20,12 +20,14 @@ class ImageTask(FileTask):Task that processes image file urls"""- def __init__(self, action=None, select=None, unpack=True, column=None, merge="hstack", initialize=None, finalize=None):+ def register(self):+ """+ Checks if required dependencies are installed.+ """+if not PIL:raise ImportError('ImageTask is not available - install "workflow" extra to enable')- super().__init__(action, select, unpack, column, merge, initialize, finalize)-def accept(self, element):# Only accept image filesreturn super().accept(element) and re.search(r"\.(gif|bmp|jpg|jpeg|png|webp)$", element.lower())diff --git a/src/python/txtai/workflow/task/retrieve.py b/src/python/txtai/workflow/task/retrieve.pyindex 41c77b9b..fa9ec088 100644--- a/src/python/txtai/workflow/task/retrieve.py+++ b/src/python/txtai/workflow/task/retrieve.py@@ -15,9 +15,15 @@ class RetrieveTask(UrlTask):Task that retrieves urls (local or remote) to a local directory."""- 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)+ def register(self, directory=None):+ """+ Adds retrieve parameters to task.+ Args:+ directory: local directory used to store retrieved files+ """++ # pylint: disable=W0201# Create default temporary directory if not specifiedif not directory:# Save tempdir to prevent content from being deleted until this task is out of scope@@ -32,9 +38,6 @@ class RetrieveTask(UrlTask):self.directory = directorydef prepare(self, element):- # Run super() method to format element- element = super().prepare(element)-# Extract file name_, name = os.path.split(element)diff --git a/src/python/txtai/workflow/task/service.py b/src/python/txtai/workflow/task/service.pyindex 1d5d14f4..bbb6bb17 100644--- a/src/python/txtai/workflow/task/service.py+++ b/src/python/txtai/workflow/task/service.py@@ -19,27 +19,22 @@ class ServiceTask(Task):Task to runs requests against remote service urls."""- # 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,- ):+ def register(self, url=None, method=None, params=None, batch=True, extract=None):+ """+ Adds service parameters to task. Checks if required dependencies are installed.++ Args:+ url: url to connect to+ method: http method, GET or POST+ params: default query parameters+ batch: If True, all elements are passed in a single batch request, otherwise a service call is executed per element+ extract: list of sections to extract from response+ """+if not XML_TO_DICT:raise ImportError('ServiceTask is not available - install "workflow" extra to enable')- super().__init__(action, select, unpack, column, merge, initialize, finalize)-+ # pylint: disable=W0201# Save URL, method and parameter defaultsself.url = urlself.method = method@@ -53,13 +48,13 @@ class ServiceTask(Task):if self.extract:self.extract = [self.extract] if isinstance(self.extract, str) else self.extract- def execute(self, elements):+ def execute(self, elements, executor=None):if self.batch:elements = self.request(elements)else:elements = [self.request(element) for element in elements]- return super().execute(elements)+ return super().execute(elements, executor)def request(self, data):"""diff --git a/src/python/txtai/workflow/task/storage.py b/src/python/txtai/workflow/task/storage.pyindex 8601c8dd..9327084f 100644--- a/src/python/txtai/workflow/task/storage.py+++ b/src/python/txtai/workflow/task/storage.py@@ -25,19 +25,21 @@ class StorageTask(Task):PREFIX = r"(\w+):\/\/.*"PATH = r"\w+:\/\/(.*)"- def __init__(self, action=None, select=None, unpack=True):+ def register(self):+ """+ Checks if required dependencies are installed.+ """+if not LIBCLOUD:raise ImportError('StorageTask is not available - install "workflow" extra to enable')- super().__init__(action, select, unpack)-- def __call__(self, elements):+ def __call__(self, elements, executor=None):# Create aggregated directory listing for all elementsoutputs = []for element in elements:if self.matches(element):# Get directory listing and run actions- outputs.extend(super().__call__(self.list(element)))+ outputs.extend(super().__call__(self.list(element), executor))else:outputs.append(element)