💡 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 agent support to Applications and API #804
davidmezzetti731ecd234879
diff --git a/src/python/txtai/api/routers/__init__.py b/src/python/txtai/api/routers/__init__.pyindex 154c0439..9fbc3f0e 100644--- a/src/python/txtai/api/routers/__init__.py+++ b/src/python/txtai/api/routers/__init__.py@@ -2,6 +2,7 @@Router imports"""+from . import agentfrom . import captionfrom . import embeddingsfrom . import entitydiff --git a/src/python/txtai/api/routers/agent.py b/src/python/txtai/api/routers/agent.pynew file mode 100644index 00000000..fd57052a--- /dev/null+++ b/src/python/txtai/api/routers/agent.py@@ -0,0 +1,38 @@+"""+Defines API paths for agent endpoints.+"""++from typing import Optional++from fastapi import APIRouter, Body+from fastapi.responses import StreamingResponse++from .. import application+from ..route import EncodingAPIRoute++router = APIRouter(route_class=EncodingAPIRoute)++[email protected]("/agent")+def agent(name: str = Body(...), text: str = Body(...), maxlength: Optional[int] = Body(default=None), stream: Optional[bool] = Body(default=None)):+ """+ Executes a named agent for input text.++ Args:+ name: agent name+ text: instructions to run+ maxlength: maximum sequence length+ stream: stream response if True, defaults to False++ Returns:+ response text+ """++ # Build keyword arguments+ kwargs = {key: value for key, value in [("stream", stream), ("maxlength", maxlength)] if value}++ # Run agent+ result = application.get().agent(name, text, **kwargs)++ # Handle both standard and streaming responses+ return StreamingResponse(result) if stream else resultdiff --git a/src/python/txtai/app/base.py b/src/python/txtai/app/base.pyindex 3cb3fd53..39c00b28 100644--- a/src/python/txtai/app/base.py+++ b/src/python/txtai/app/base.py@@ -9,6 +9,7 @@ from threading import RLockimport yaml+from ..agent import Agentfrom ..embeddings import Documents, Embeddingsfrom ..pipeline import PipelineFactoryfrom ..workflow import WorkflowFactory@@ -69,10 +70,13 @@ class Application:self.pool = None# Create pipelines- self.pipes()+ self.createpipelines()# Create workflows- self.flows()+ self.createworkflows()++ # Create agents+ self.createagents()# Create embeddings indexself.indexes(loaddata)@@ -86,9 +90,9 @@ class Application:self.pool.close()self.pool = None- def pipes(self):+ def createpipelines(self):"""- Initialize pipelines.+ Create pipelines."""# Pipeline definitions@@ -133,9 +137,9 @@ class Application:self.pipelines[pipeline] = PipelineFactory.create(config, pipeline)- def flows(self):+ def createworkflows(self):"""- Initialize workflows.+ Create workflows."""# Workflow definitions@@ -168,6 +172,31 @@ class Application:self.pool.apply_async(self.workflows[workflow].schedule, kwds=schedule)+ def createagents(self):+ """+ Create agents.+ """++ # Agent definitions+ self.agents = {}++ # Create agents+ if "agent" in self.config:+ for agent, config in self.config["agent"].items():+ # Create copy of config+ config = config.copy()++ # Resolve LLM+ config["llm"] = self.function("llm")++ # Resolve tools+ for tool in config.get("tools", []):+ if isinstance(tool, dict) and "target" in tool:+ tool["target"] = self.function(tool["target"])++ # Create agent+ self.agents[agent] = Agent(**config)+def indexes(self, loaddata):"""Initialize an embeddings index.@@ -752,6 +781,21 @@ class Application:# Execute workflowreturn self.workflows[name](elements)+ def agent(self, name, *args, **kwargs):+ """+ Executes an agent.++ Args:+ name: agent name+ args: agent positional arguments+ kwargs: agent keyword arguments+ """++ if name in self.agents:+ return self.agents[name](*args, **kwargs)++ return None+def wait(self):"""Closes threadpool and waits for completion.diff --git a/test/python/testapi/testapiagent.py b/test/python/testapi/testapiagent.pynew file mode 100644index 00000000..0844b2d4--- /dev/null+++ b/test/python/testapi/testapiagent.py@@ -0,0 +1,91 @@+"""+Agent API module tests+"""++import os+import tempfile+import unittest++from unittest.mock import patch++from fastapi.testclient import TestClient++from txtai.api import API, application++# Configuration for agents+AGENTS = """+agent:+ test:+ max_iterations: 1+ tools:+ - name: today+ description: Today's date+ target: testapi.testapiagent.TestTool++llm:+ path: hf-internal-testing/tiny-random-LlamaForCausalLM+"""+++# pylint: disable=R0904+class TestAgent(unittest.TestCase):+ """+ API tests for agents.+ """++ @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", encoding="utf-8") as output:+ output.write(AGENTS)++ # Create new application and set on client+ application.app = application.create()+ client = TestClient(application.app)+ application.start()++ # Patch LLM to generate answer+ agent = application.get().agents["test"]+ agent.process.llm_engine.llm = lambda *args, **kwargs: 'Action:\n{"action": "final_answer", "action_input": "Hi"}<end_action>'++ return client++ @classmethod+ def setUpClass(cls):+ """+ Create API client on creation of class.+ """++ cls.client = TestAgent.start()++ def testAgent(self):+ """+ Test agent via API+ """++ results = self.client.post("agent", json={"name": "test", "text": "Hello"}).json()+ self.assertEqual(results, "Hi")++ def testEmpty(self):+ """+ Test empty API configuration+ """++ api = API({})++ self.assertIsNone(api.agent("junk", "test"))+++class TestTool:+ """+ Class to test agent tools+ """++ def __call__(self):+ pass