💡 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 workflow to API #82. Add service workflow task #83. Add object storage workflow task #84. Add URL workflow task #85
davidmezzettib2c9bbf7c4f9
diff --git a/setup.py b/setup.pyindex 3c637946..d72e0dfd 100644--- a/setup.py+++ b/setup.py@@ -24,6 +24,7 @@ setup(python_requires=">=3.6",install_requires=["annoy>=1.16.3",+ "apache-libcloud>=3.3.1","faiss-cpu>=1.7.0; os_name != 'nt'","fastapi>=0.61.1","fasttext>=0.9.2",@@ -34,6 +35,7 @@ setup("pillow>=7.2.0","PyYAML>=5.3","regex>=2020.5.14",+ "requests>=2.24.0","scikit-learn>=0.23.1","sentence-transformers>=1.0.3","sentencepiece>=0.1.91",diff --git a/src/python/txtai/api/application.py b/src/python/txtai/api/application.pyindex ba773a16..16d89957 100644--- a/src/python/txtai/api/application.py+++ b/src/python/txtai/api/application.py@@ -12,7 +12,7 @@ from .base import APIfrom .factory import Factory# pylint: disable=R0401-from .routers import embeddings, extractor, labels, segmentation, similarity, summary, textractor, transcription, translation+from .routers import embeddings, extractor, labels, segmentation, similarity, summary, textractor, transcription, translation, workflows# API instanceapp = FastAPI()@@ -63,6 +63,7 @@ def start():("textractor", textractor.router),("transcription", transcription.router),("translation", translation.router),+ ("workflows", workflows.router),]# Conditionally add routes based on configurationdiff --git a/src/python/txtai/api/base.py b/src/python/txtai/api/base.pyindex df43ea11..d6e76aab 100644--- a/src/python/txtai/api/base.py+++ b/src/python/txtai/api/base.py@@ -3,7 +3,8 @@ API module"""from ..embeddings import Documents, Embeddings-from ..pipeline import Factory+from ..pipeline import PipelineFactory+from ..workflow import WorkflowFactoryclass API:@@ -29,6 +30,17 @@ class API:self.embeddings = Embeddings()self.embeddings.load(self.config["path"])+ # Create pipelines+ self.pipes()++ # Create workflows+ self.flows()++ def pipes(self):+ """+ Initialize pipelines.+ """+# Pipeline definitionsself.pipelines = {}@@ -51,7 +63,23 @@ class API:elif pipeline == "similarity" and "path" not in config and "labels" in self.pipelines:config["model"] = self.pipelines["labels"]- self.pipelines[pipeline] = Factory.create(config, pipeline)+ self.pipelines[pipeline] = PipelineFactory.create(config, pipeline)++ def flows(self):+ """+ Initialize workflows.+ """++ self.workflows = {}++ # Resolve pipeline actions and create workflow+ if "workflows" in self.config:+ for workflow, config in self.config["workflows"].items():+ for task in config["tasks"]:+ if "action" in task:+ task["action"] = self.pipelines[task["action"]]++ self.workflows[workflow] = WorkflowFactory.create(config)def limit(self, limit):"""@@ -281,3 +309,21 @@ class API:return self.pipelines[name](*args)return None++ def workflow(self, name, elements):+ """+ Executes a workflow.++ Args:+ name: workflow name+ elements: elements to process++ Returns:+ processed elements+ """++ # Convert lists to tuples+ elements = [tuple(element) if isinstance(element, list) else element for element in elements]++ # Execute workflow+ return self.workflows[name](elements)diff --git a/src/python/txtai/api/routers/__init__.py b/src/python/txtai/api/routers/__init__.pyindex 09ef8cb8..5d7090ef 100644--- a/src/python/txtai/api/routers/__init__.py+++ b/src/python/txtai/api/routers/__init__.py@@ -10,3 +10,4 @@ from . import summaryfrom . import textractorfrom . import transcriptionfrom . import translation+from . import workflowsdiff --git a/src/python/txtai/api/routers/workflows.py b/src/python/txtai/api/routers/workflows.pynew file mode 100644index 00000000..953db87c--- /dev/null+++ b/src/python/txtai/api/routers/workflows.py@@ -0,0 +1,27 @@+"""+Defines API paths for workflow endpoints.+"""++from typing import List++from fastapi import APIRouter, Body++from .. import application++router = APIRouter()++[email protected]("/workflow")+def workflow(name: str = Body(...), elements: List = Body(...)):+ """+ Executes a named workflow using elements as input.++ Args:+ name: workflow name+ elements: list of elements to run through workflow++ Returns:+ list of processed elements+ """++ return application.get().workflow(name, elements)diff --git a/src/python/txtai/pipeline/__init__.py b/src/python/txtai/pipeline/__init__.pyindex 2f628e4c..c12506f4 100644--- a/src/python/txtai/pipeline/__init__.py+++ b/src/python/txtai/pipeline/__init__.py@@ -4,7 +4,7 @@ Pipeline importsfrom .base import Pipelinefrom .extractor import Extractor-from .factory import Factory+from .factory import PipelineFactoryfrom .hfmodel import HFModelfrom .hfpipeline import HFPipelinefrom .labels import Labelsdiff --git a/src/python/txtai/pipeline/factory.py b/src/python/txtai/pipeline/factory.pyindex eb9fe2cd..00194520 100644--- a/src/python/txtai/pipeline/factory.py+++ b/src/python/txtai/pipeline/factory.py@@ -3,7 +3,7 @@ Pipeline factory module"""-class Factory:+class PipelineFactory:"""Pipeline factory. Creates new Pipeline instances."""@@ -36,7 +36,7 @@ class Factory:@staticmethoddef create(config, pipeline):"""- Creates a new Pipeline instance+ Creates a new Pipeline instance.Args:config: Pipeline configuration@@ -47,4 +47,4 @@ class Factory:"""# Get Pipeline instance- return Factory.get(pipeline)(**config)+ return PipelineFactory.get(pipeline)(**config)diff --git a/src/python/txtai/workflow/__init__.py b/src/python/txtai/workflow/__init__.pyindex fbdda280..5aab278e 100644--- a/src/python/txtai/workflow/__init__.py+++ b/src/python/txtai/workflow/__init__.py@@ -3,4 +3,5 @@ Workflow imports"""from .base import Workflow+from .factory import WorkflowFactoryfrom .task import *diff --git a/src/python/txtai/workflow/base.py b/src/python/txtai/workflow/base.pyindex f4f5ec9c..21a813ab 100644--- a/src/python/txtai/workflow/base.py+++ b/src/python/txtai/workflow/base.py@@ -116,6 +116,10 @@ class Workflow:# Package data into (id, data, tag) formatted elementsif 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 returnelement = list(element)element[1] = datadiff --git a/src/python/txtai/workflow/factory.py b/src/python/txtai/workflow/factory.pynew file mode 100644index 00000000..2713415b--- /dev/null+++ b/src/python/txtai/workflow/factory.py@@ -0,0 +1,35 @@+"""+Workflow factory module+"""++from .base import Workflow+from .task import TaskFactory+++class WorkflowFactory:+ """+ Workflow factory. Creates new Workflow instances.+ """++ @staticmethod+ def create(config):+ """+ Creates a new Workflow instance.++ Args:+ config: Workflow configuration++ Returns:+ Workflow+ """++ # Resolve workflow tasks+ tasks = []+ for tconfig in config["tasks"]:+ task = tconfig.pop("task") if "task" in tconfig else ""+ tasks.append(TaskFactory.create(tconfig, task))++ config["tasks"] = tasks++ # Create workflow+ return Workflow(**config)diff --git a/src/python/txtai/workflow/task/__init__.py b/src/python/txtai/workflow/task/__init__.pyindex ee3390d9..6e2be8ab 100644--- a/src/python/txtai/workflow/task/__init__.py+++ b/src/python/txtai/workflow/task/__init__.py@@ -3,6 +3,10 @@ Task imports"""from .base import Task+from .factory import TaskFactoryfrom .file import FileTaskfrom .image import ImageTask+from .service import ServiceTask+from .storage import StorageTask+from .url import UrlTaskfrom .workflow import WorkflowTaskdiff --git a/src/python/txtai/workflow/task/base.py b/src/python/txtai/workflow/task/base.pyindex b5daee59..968bfa49 100644--- a/src/python/txtai/workflow/task/base.py+++ b/src/python/txtai/workflow/task/base.py@@ -39,8 +39,8 @@ class Task:# Run data preparation routineselements = [self.prepare(element) for element in elements]- # Run data elements through workflow action- return self.action(elements) if self.action else elements+ # Run data elements through workflow execution+ return self.execute(elements)def accept(self, element):"""@@ -67,3 +67,16 @@ class Task:"""return element++ def execute(self, elements):+ """+ Executes action on elements.++ Args:+ elements: list of data elements++ Returns:+ transformed data elements+ """++ return self.action(elements) if self.action else elementsdiff --git a/src/python/txtai/workflow/task/factory.py b/src/python/txtai/workflow/task/factory.pynew file mode 100644index 00000000..987f6417--- /dev/null+++ b/src/python/txtai/workflow/task/factory.py@@ -0,0 +1,56 @@+"""+Task factory module+"""+++class TaskFactory:+ """+ Task factory. Creates new Task instances.+ """++ @staticmethod+ def get(task):+ """+ Gets a new instance of task class.++ Args:+ task: Task instance class++ Returns:+ Task class+ """++ # Local task if no package+ if "." not in task:+ # Get parent package+ task = ".".join(__name__.split(".")[:-1]) + "." + task.capitalize() + "Task"++ parts = task.split(".")+ module = ".".join(parts[:-1])+ m = __import__(module)+ for comp in parts[1:]:+ m = getattr(m, comp)++ return m++ @staticmethod+ def create(config, task):+ """+ Creates a new Task instance.++ Args:+ config: Task configuration+ task: Task instance class++ Returns:+ Task+ """++ # Create lambda function if additional arguments present+ if "args" in config:+ args = config.pop("args")+ action = config["action"]+ config["action"] = lambda x: action(x, *args)++ # Get Task instance+ return TaskFactory.get(task)(**config)diff --git a/src/python/txtai/workflow/task/file.py b/src/python/txtai/workflow/task/file.pyindex 7a12da25..895b064e 100644--- a/src/python/txtai/workflow/task/file.py+++ b/src/python/txtai/workflow/task/file.py@@ -4,20 +4,14 @@ FileTask moduleimport re-from .base import Task+from .url import UrlTask-class FileTask(Task):+class FileTask(UrlTask):"""Task that processes file urls"""- # File prefix- FILE = r"file:\/\/"-def accept(self, element):# Only accept file URLs- return super().accept(element) and re.match(FileTask.FILE, element.lower())-- def prepare(self, element):- return re.sub(FileTask.FILE, "", element)+ return super().accept(element) and re.match(UrlTask.FILE, element.lower())diff --git a/src/python/txtai/workflow/task/service.py b/src/python/txtai/workflow/task/service.pynew file mode 100644index 00000000..58c1ad15--- /dev/null+++ b/src/python/txtai/workflow/task/service.py@@ -0,0 +1,46 @@+"""+ServiceTask module+"""++import requests++from .base import Task+++class ServiceTask(Task):+ """+ Task to runs requests against remote service urls.+ """++ def __init__(self, url=None, method=None, params=None, select=None, unpack=True):+ super().__init__(lambda x: self.request(url, method, params, x), select, unpack)++ def request(self, url, method, params, data):+ """+ Execute service request.++ Args:+ url: service url+ method: method (get or post)+ params: dict of constant parameters to pass to request+ data: dynamic data for this specific request++ Returns:+ response as JSON+ """++ if not params:+ params = data+ else:+ # Create copy of parameters+ params = params.copy()++ # Add data to parameters+ for key in params:+ if not params[key]:+ params[key] = data++ if method == "get":+ return requests.get(url, params=params).json()++ return requests.post(url, json=params).json()diff --git a/src/python/txtai/workflow/task/storage.py b/src/python/txtai/workflow/task/storage.pynew file mode 100644index 00000000..8a796a02--- /dev/null+++ b/src/python/txtai/workflow/task/storage.py@@ -0,0 +1,73 @@+"""+StorageTask module+"""++import os+import re++from libcloud.storage.providers import get_driver++from .base import Task+++class StorageTask(Task):+ """+ Task that processes object storage buckets. Supports local and cloud providers in Apache libcloud.+ """++ # URL prefix+ PREFIX = r"(\w+):\/\/.*"+ PATH = r"\w+:\/\/(.*)"++ def __init__(self, action=None, select=None, unpack=True, ids=True):+ 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())++ def execute(self, elements):+ # List contents of each bucket+ buckets = [self.list(element) for element in elements]++ elements = []+ for bucket in buckets:+ # Execute actions+ content = super().execute(bucket)++ # 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++ elements.append(values)++ return elements++ def list(self, element):+ """+ Gets a list of urls for a object container.++ Args:+ element: object container++ Returns:+ list of urls+ """++ provider = re.sub(StorageTask.PREFIX, r"\1", element.lower())+ path = re.sub(StorageTask.PATH, r"\1", element)++ key, container = os.path.dirname(path), os.path.basename(path)++ client = get_driver(provider)+ driver = client(key)++ container = driver.get_container(container_name=container)+ return [driver.get_object_cdn_url(obj) for obj in driver.list_container_objects(container=container)]diff --git a/src/python/txtai/workflow/task/url.py b/src/python/txtai/workflow/task/url.pynew file mode 100644index 00000000..9eba7fab--- /dev/null+++ b/src/python/txtai/workflow/task/url.py@@ -0,0 +1,26 @@+"""+UrlTask module+"""++import re++from .base import Task+++class UrlTask(Task):+ """+ Task that processes urls+ """++ # URL prefix+ PREFIX = r"\w+:\/\/"++ # File prefix+ FILE = r"file:\/\/"++ def accept(self, element):+ # Only accept file URLs+ return super().accept(element) and re.match(UrlTask.PREFIX, element.lower())++ def prepare(self, element):+ return re.sub(UrlTask.FILE, "", element)diff --git a/test/python/testapi/testextension.py b/test/python/testapi/testextension.pyindex 4d4ea9c8..4d3d5958 100644--- a/test/python/testapi/testextension.py+++ b/test/python/testapi/testextension.py@@ -78,9 +78,6 @@ class TestExtension(unittest.TestCase):def start():"""Starts a mock FastAPI client.-- Args:- full: true if full api configuration should be loaded, otherwise a read-only configuration is used"""config = os.path.join(tempfile.gettempdir(), "testapi.yml")diff --git a/test/python/testapi/testpipelines.py b/test/python/testapi/testpipelines.pyindex 7e0ff9b1..8482378c 100644--- a/test/python/testapi/testpipelines.py+++ b/test/python/testapi/testpipelines.py@@ -54,9 +54,6 @@ class TestPipelines(unittest.TestCase):def start():"""Starts a mock FastAPI client.-- Args:- full: true if full api configuration should be loaded, otherwise a read-only configuration is used"""config = os.path.join(tempfile.gettempdir(), "testapi.yml")diff --git a/test/python/testapi/testworkflow.py b/test/python/testapi/testworkflow.pynew file mode 100644index 00000000..e004993f--- /dev/null+++ b/test/python/testapi/testworkflow.py@@ -0,0 +1,152 @@+"""+Workflow API module tests+"""++import json+import os+import tempfile+import unittest++from http.server import HTTPServer, BaseHTTPRequestHandler+from threading import Thread+from unittest.mock import patch++from fastapi.testclient import TestClient++from txtai.api import app, start++# Configuration for workflows+WORKFLOWS = """+# Text segmentation+segmentation:+ sentences: true++# Workflows+workflows:+ segment:+ tasks:+ - action: segmentation+ get:+ tasks:+ - task: service+ url: http://127.0.0.1:8001/testget+ method: get+ params:+ text:+ post:+ tasks:+ - task: service+ url: http://127.0.0.1:8001/batchsegment+ params:+"""+++class RequestHandler(BaseHTTPRequestHandler):+ """+ Test HTTP handler+ """++ def do_GET(self):+ """+ GET request handler.+ """++ response = '[{"text": "test"}]'.encode("utf-8")++ self.send_response(200)+ self.send_header("content-type", "application/json")+ self.send_header("content-length", len(response))+ self.end_headers()++ self.wfile.write(response)++ def do_POST(self):+ """+ POST request handler.+ """++ length = int(self.headers["content-length"])+ data = json.loads(self.rfile.read(length))++ response = json.dumps([[y for y in x.split(".") if y] for x in data]).encode("utf-8")++ self.send_response(200)+ self.send_header("content-type", "application/json")+ self.send_header("content-length", len(response))+ self.end_headers()++ self.wfile.write(response)+++class TestWorkflow(unittest.TestCase):+ """+ API tests for workflows+ """++ @staticmethod+ @patch.dict(os.environ, {"CONFIG": os.path.join(tempfile.gettempdir(), "testapi.yml"), "API_CLASS": "txtai.api.API"})+ def start():+ """+ Starts a mock FastAPI client.+ """++ config = os.path.join(tempfile.gettempdir(), "testapi.yml")++ with open(config, "w") as output:+ output.write(WORKFLOWS)++ client = TestClient(app)+ start()++ return client++ @classmethod+ def setUpClass(cls):+ """+ Create API client on creation of class.+ """++ cls.client = TestWorkflow.start()++ cls.httpd = HTTPServer(("127.0.0.1", 8001), RequestHandler)++ server = Thread(target=cls.httpd.serve_forever)+ server.setDaemon(True)+ server.start()++ @classmethod+ def tearDownClass(cls):+ """+ Shutdown mock http server.+ """++ cls.httpd.shutdown()++ def testServiceGet(self):+ """+ Test workflow with ServiceTask GET via API.+ """++ text = "This is a test sentence. And another sentence to split."+ results = self.client.post("workflow", json={"name": "get", "elements": [text]}).json()++ self.assertEqual(len(results), 1)++ def testServicePost(self):+ """+ Test workflow with ServiceTask POST via API.+ """++ text = "This is a test sentence. And another sentence to split."+ results = self.client.post("workflow", json={"name": "post", "elements": [text]}).json()++ self.assertEqual(len(results), 2)++ def testWorkflow(self):+ """+ Test workflow 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)diff --git a/test/python/testworkflow.py b/test/python/testworkflow.pyindex d44d01ce..a4c5e0bb 100644--- a/test/python/testworkflow.py+++ b/test/python/testworkflow.py@@ -6,13 +6,13 @@ import unittestfrom txtai.embeddings import Documents, Embeddingsfrom txtai.pipeline import Summary, Translation, Textractor-from txtai.workflow import Workflow, Task, FileTask, ImageTask, WorkflowTask+from txtai.workflow import Workflow, Task, FileTask, ImageTask, StorageTask, WorkflowTask# pylint: disable = C0411from utils import Utils-class TestWorkFlow(unittest.TestCase):+class TestWorkflow(unittest.TestCase):"""Workflow tests"""@@ -82,3 +82,14 @@ class TestWorkFlow(unittest.TestCase):results = list(workflow(["file://" + Utils.PATH + "/books.jpg"]))self.assertEqual(results[0].size, (1024, 682))++ def testStorageWorkflow(self):+ """+ Tests a storage task+ """++ workflow = Workflow([StorageTask()])++ results = list(workflow(["local://" + Utils.PATH]))++ self.assertEqual(len(results), 17)