💡 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
Read YAML config from file if path provided, closes #162
davidmezzettidd29b3636c34
diff --git a/src/python/txtai/api/application.py b/src/python/txtai/api/application.pyindex 80ecd1ca..b0a6f369 100644--- a/src/python/txtai/api/application.py+++ b/src/python/txtai/api/application.py@@ -4,8 +4,6 @@ FastAPI application moduleimport os-import yaml-from fastapi import FastAPIfrom .base import API@@ -42,9 +40,7 @@ def start():global INSTANCE# Load YAML settings- with open(os.getenv("CONFIG"), "r", encoding="utf-8") as f:- # Read configuration- config = yaml.safe_load(f)+ config = API.read(os.getenv("CONFIG"))# Instantiate API instanceapi = os.getenv("API_CLASS")diff --git a/src/python/txtai/api/base.py b/src/python/txtai/api/base.pyindex ea6ad7a3..bc7d9fc1 100644--- a/src/python/txtai/api/base.py+++ b/src/python/txtai/api/base.py@@ -2,20 +2,49 @@API module"""+import os+from threading import Lock+import yaml+from .cluster import Clusterfrom ..embeddings import Documents, Embeddingsfrom ..pipeline import PipelineFactoryfrom ..workflow import WorkflowFactory-+# pylint: disable=R0904class API:"""Base API template. Downstream applications can extend this base template to add/modify functionality."""+ @staticmethod+ def read(data):+ """+ Reads a YAML configuration file.++ Args:+ data: input data++ Returns:+ yaml+ """++ if isinstance(data, str):+ if os.path.exists(data):+ # Read yaml from file+ with open(data, "r", encoding="utf-8") as f:+ # Read configuration+ return yaml.safe_load(f)+ else:+ # Read yaml from string+ return yaml.safe_load(data)++ # Return unmodified+ return data+def __init__(self, config):"""Creates an embeddings index instance that is called by FastAPI.@@ -27,6 +56,10 @@ class API:# Initialize member variablesself.config, self.documents, self.embeddings, self.cluster = config, None, None, None+ # Read configuration from file+ if isinstance(self.config, str):+ self.config = API.read(self.config)+# Write lockself.lock = Lock()@@ -177,7 +210,7 @@ class API:# Return between 1 and 250 results, defaults to 10return max(1, min(250, int(limit) if limit else 10))- def search(self, query, request):+ def search(self, query, request=None):"""Finds documents in the embeddings model most similar to the input query. Returnsa list of {id: value, score: value} sorted by highest score, where id is thediff --git a/test/python/testworkflow.py b/test/python/testworkflow.pyindex 00b2f492..05c87af0 100644--- a/test/python/testworkflow.py+++ b/test/python/testworkflow.py@@ -9,6 +9,7 @@ import unittestimport numpy as npimport torch+from txtai.api import APIfrom txtai.embeddings import Documents, Embeddingsfrom txtai.pipeline import Summary, Translation, Textractorfrom txtai.workflow import Workflow, Task, FileTask, ImageTask, RetrieveTask, StorageTask, WorkflowTask@@ -234,3 +235,45 @@ class TestWorkflow(unittest.TestCase):task.merge = Noneresults = np.array([x.numpy() for x in workflow(torch.tensor([2, 4, 6]))])self.assertTrue(np.array_equal(np.array(results), np.array([[4, 16, 36], [8, 64, 216]])))++ def testYamlWorkflow(self):+ """+ Tests reading a YAML workflow in Python.+ """++ # Read from string+ config = """+ # Text segmentation+ segmentation:+ sentences: true++ # Workflow definitions+ workflow:+ segment:+ tasks:+ - action: segmentation+ """++ app = API(config)+ self.assertEqual(+ list(app.workflow("segment", ["This is a test sentence. And another sentence to split."])),+ ["This is a test sentence.", "And another sentence to split."],+ )++ # Read from file+ path = os.path.join(tempfile.gettempdir(), "workflow.yml")+ with open(path, "w", encoding="utf-8") as f:+ f.write(config)++ app = API(path)+ self.assertEqual(+ list(app.workflow("segment", ["This is a test sentence. And another sentence to split."])),+ ["This is a test sentence.", "And another sentence to split."],+ )++ # Read from YAML object+ app = API(API.read(config))+ self.assertEqual(+ list(app.workflow("segment", ["This is a test sentence. And another sentence to split."])),+ ["This is a test sentence.", "And another sentence to split."],+ )