Skip to content

armgit / txtai

Public Imported from GitHub
0

💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows

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.py
index 80ecd1ca..b0a6f369 100644
--- a/src/python/txtai/api/application.py
+++ b/src/python/txtai/api/application.py
@@ -4,8 +4,6 @@ FastAPI application module
import os
-import yaml
-
from fastapi import FastAPI
from .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 instance
api = os.getenv("API_CLASS")
diff --git a/src/python/txtai/api/base.py b/src/python/txtai/api/base.py
index 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 Cluster
from ..embeddings import Documents, Embeddings
from ..pipeline import PipelineFactory
from ..workflow import WorkflowFactory
-
+# pylint: disable=R0904
class 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 variables
self.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 lock
self.lock = Lock()
@@ -177,7 +210,7 @@ class API:
# Return between 1 and 250 results, defaults to 10
return 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. Returns
a list of {id: value, score: value} sorted by highest score, where id is the
diff --git a/test/python/testworkflow.py b/test/python/testworkflow.py
index 00b2f492..05c87af0 100644
--- a/test/python/testworkflow.py
+++ b/test/python/testworkflow.py
@@ -9,6 +9,7 @@ import unittest
import numpy as np
import torch
+from txtai.api import API
from txtai.embeddings import Documents, Embeddings
from txtai.pipeline import Summary, Translation, Textractor
from txtai.workflow import Workflow, Task, FileTask, ImageTask, RetrieveTask, StorageTask, WorkflowTask
@@ -234,3 +235,45 @@ class TestWorkflow(unittest.TestCase):
task.merge = None
results = 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."],
+ )