💡 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 RAG API endpoint, closes #735
davidmezzettica7672c70e17
diff --git a/src/python/txtai/api/routers/__init__.py b/src/python/txtai/api/routers/__init__.pyindex 5e1a3fab..154c0439 100644--- a/src/python/txtai/api/routers/__init__.py+++ b/src/python/txtai/api/routers/__init__.py@@ -7,7 +7,9 @@ from . import embeddingsfrom . import entityfrom . import extractorfrom . import labels+from . import llmfrom . import objects+from . import ragfrom . import segmentationfrom . import similarityfrom . import summarydiff --git a/src/python/txtai/api/routers/llm.py b/src/python/txtai/api/routers/llm.pynew file mode 100644index 00000000..ed65ceca--- /dev/null+++ b/src/python/txtai/api/routers/llm.py@@ -0,0 +1,46 @@+"""+Defines API paths for llm endpoints.+"""++from typing import List, Optional++from fastapi import APIRouter, Body++from .. import application+from ..route import EncodingAPIRoute++router = APIRouter(route_class=EncodingAPIRoute)++[email protected]("/llm")+def llm(text: str, maxlength: Optional[int] = None):+ """+ Runs a LLM pipeline for the input text.++ Args:+ text: input text+ maxlength: optional response max length++ Returns:+ response text+ """++ kwargs = {"maxlength": maxlength} if maxlength else {}+ return application.get().pipeline("llm", text, **kwargs)++[email protected]("/batchllm")+def batchllm(texts: List[str] = Body(...), maxlength: Optional[int] = Body(default=None)):+ """+ Runs a LLM pipeline for the input texts.++ Args:+ texts: input texts+ maxlength: optional response max length++ Returns:+ list of response texts+ """++ kwargs = {"maxlength": maxlength} if maxlength else {}+ return application.get().pipeline("llm", texts, **kwargs)diff --git a/src/python/txtai/api/routers/rag.py b/src/python/txtai/api/routers/rag.pynew file mode 100644index 00000000..23735c30--- /dev/null+++ b/src/python/txtai/api/routers/rag.py@@ -0,0 +1,46 @@+"""+Defines API paths for rag endpoints.+"""++from typing import List, Optional++from fastapi import APIRouter, Body++from .. import application+from ..route import EncodingAPIRoute++router = APIRouter(route_class=EncodingAPIRoute)++[email protected]("/rag")+def rag(query: str, maxlength: Optional[int] = None):+ """+ Runs a RAG pipeline for the input query.++ Args:+ query: input RAG query+ maxlength: optional response max length++ Returns:+ answer+ """++ kwargs = {"maxlength": maxlength} if maxlength else {}+ return application.get().pipeline("rag", query, **kwargs)++[email protected]("/batchrag")+def batchrag(queries: List[str] = Body(...), maxlength: Optional[int] = Body(default=None)):+ """+ Runs a RAG pipeline for the input queries.++ Args:+ queries: input RAG queries+ maxlength: optional response max length++ Returns:+ list of answers+ """++ kwargs = {"maxlength": maxlength} if maxlength else {}+ return application.get().pipeline("rag", queries, **kwargs)diff --git a/src/python/txtai/app/base.py b/src/python/txtai/app/base.pyindex 19985df2..3cb3fd53 100644--- a/src/python/txtai/app/base.py+++ b/src/python/txtai/app/base.py@@ -103,7 +103,8 @@ class Application:pipelines.append(key)# Move dependent pipelines to end of list- pipelines = sorted(pipelines, key=lambda x: x in ["similarity", "extractor"])+ dependent = ["similarity", "extractor", "rag"]+ pipelines = sorted(pipelines, key=lambda x: dependent.index(x) + 1 if x in dependent else 0)# Create pipelinesfor pipeline in pipelines:@@ -115,11 +116,15 @@ class Application:config["application"] = self# Custom pipeline parameters- if pipeline == "extractor" and "similarity" not in config:- # Add placeholder, will be set to embeddings index once initialized- config["similarity"] = None+ if pipeline in ["extractor", "rag"]:+ if "similarity" not in config:+ # Add placeholder, will be set to embeddings index once initialized+ config["similarity"] = None++ # Resolve reference pipelines+ if config.get("similarity") in self.pipelines:+ config["similarity"] = self.pipelines[config["similarity"]]- # Resolve reference pipeline, if necessaryif config.get("path") in self.pipelines:config["path"] = self.pipelines[config["path"]]@@ -194,9 +199,12 @@ class Application:self.embeddings = Embeddings(config)# If an extractor pipeline is defined and the similarity attribute is None, set to embeddings index- extractor = self.pipelines.get("extractor")- if extractor and not extractor.similarity:- extractor.similarity = self.embeddings+ for key in ["extractor", "rag"]:+ pipeline = self.pipelines.get(key)+ config = self.config.get(key)++ if pipeline and config is not None and config["similarity"] is None:+ pipeline.similarity = self.embeddingsdef resolvetask(self, task):"""@@ -701,20 +709,24 @@ class Application:return None- def pipeline(self, name, args):+ def pipeline(self, name, *args, **kwargs):"""Generic pipeline execution method.Args:name: pipeline name- args: pipeline arguments+ args: pipeline positional arguments+ kwargs: pipeline keyword argumentsReturns:pipeline results"""+ # Backwards compatible with previous pipeline function arguments+ args = args[0] if args and len(args) == 1 and isinstance(args[0], tuple) else args+if name in self.pipelines:- return self.pipelines[name](*args)+ return self.pipelines[name](*args, **kwargs)return Nonediff --git a/test/python/testapi/testembeddings.py b/test/python/testapi/testembeddings.pyindex 8d506f33..891ac084 100644--- a/test/python/testapi/testembeddings.py+++ b/test/python/testapi/testembeddings.py@@ -48,8 +48,10 @@ embeddings:# Configuration for an index with custom functionsFUNCTIONS = """+# Ignore existing indexpathignore: %s+# Allow indexing of documentswritable: True# Embeddings settings@@ -66,6 +68,30 @@ embeddings:transform: testapi.testembeddings.transform"""+# Configuration for RAG+RAG = """+# Ignore existing index+pathignore: %s++# Allow indexing of documents+writable: True++# Embeddings settings+embeddings:+ path: sentence-transformers/nli-mpnet-base-v2+ content: True++# LLM+llm:+ path: hf-internal-testing/tiny-random-gpt2+ task: language-generation++# RAG settings+rag:+ path: llm+ output: flatten+"""+class TestEmbeddings(unittest.TestCase):"""@@ -357,6 +383,24 @@ class TestEmbeddings(unittest.TestCase):self.assertEqual(text, [self.data[4], self.data[1]])self.assertIsNotNone(results[0][0].get("tokens"))+ def testXRAG(self):+ """+ Test RAG via API+ """++ # Re-create model with custom functions+ self.client = TestEmbeddings.start(RAG)++ # Index data+ self.client.post("add", json=[{"id": x, "text": row} for x, row in enumerate(self.data)])+ self.client.get("index")++ response = self.client.get("rag?query=bear").json()+ self.assertIsInstance(response, str)++ response = self.client.post("batchrag", json={"queries": ["bear", "bear"]}).json()+ self.assertEqual(len(response), 2)+class Elements:"""diff --git a/test/python/testapi/testpipelines.py b/test/python/testapi/testpipelines.pyindex 74a8bf42..98bee028 100644--- a/test/python/testapi/testpipelines.py+++ b/test/python/testapi/testpipelines.py@@ -25,10 +25,20 @@ caption:entity:path: dslim/bert-base-NER+# Extractor settings+extractor:+ similarity: similarity+ path: llm+# Label settingslabels:path: prajjwal1/bert-medium-mnli+# LLM settings+llm:+ path: hf-internal-testing/tiny-random-gpt2+ task: language-generation+# Image objectsobjects:@@ -175,6 +185,22 @@ class TestPipelines(unittest.TestCase):results = [l[0]["id"] for l in labels]self.assertEqual(results, [0, 1])+ def testLLM(self):+ """+ Test LLM inference via API+ """++ response = self.client.get("llm?text=test").json()+ self.assertIsInstance(response, str)++ def testLLMBatch(self):+ """+ Test batch LLM inference via API+ """++ response = self.client.post("batchllm", json={"texts": ["test", "test"]}).json()+ self.assertEqual(len(response), 2)+def testObjects(self):"""Test objects via API