💡 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 OpenAI API compatible endpoint to API, closes #883
davidmezzetti13ab0c3b9e3f
diff --git a/docs/api/index.md b/docs/api/index.mdindex 78c0e6bf..535df924 100644--- a/docs/api/index.md+++ b/docs/api/index.md@@ -120,8 +120,11 @@ The following programming languages have bindings with the txtai API:- [Rust](https://github.com/neuml/txtai.rs)- [Go](https://github.com/neuml/txtai.go)-See the link below for a detailed example covering how to use the API.+The API also supports hosting [OpenAI-compatible endpoints](./openai).++See the links below for detailed examples covering how to use the API.| Notebook | Description | ||:----------|:-------------|------:|| [API Gallery](https://github.com/neuml/txtai/blob/master/examples/08_API_Gallery.ipynb) | Using txtai in JavaScript, Java, Rust and Go | [](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/08_API_Gallery.ipynb) |+| [OpenAI Compatible API](https://github.com/neuml/txtai/blob/master/examples/74_OpenAI_Compatible_API.ipynb) | Connect to txtai with a standard OpenAI client library | [](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/74_OpenAI_Compatible_API.ipynb) |diff --git a/docs/api/openai.md b/docs/api/openai.mdnew file mode 100644index 00000000..3f21b42d--- /dev/null+++ b/docs/api/openai.md@@ -0,0 +1,13 @@+# OpenAI-compatible API++The API can be configured to serve an OpenAI-compatible API as follows.++```yaml+openai: True+```++See the link below for a detailed example.++| Notebook | Description | |+|:----------|:-------------|------:|+| [OpenAI Compatible API](https://github.com/neuml/txtai/blob/master/examples/74_OpenAI_Compatible_API.ipynb) | Connect to txtai with a standard OpenAI client library | [](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/74_OpenAI_Compatible_API.ipynb) |diff --git a/mkdocs.yml b/mkdocs.ymlindex 92182098..4b1a9d94 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -127,6 +127,7 @@ nav:- Configuration: api/configuration.md- Customization: api/customization.md- Methods: api/methods.md+ - OpenAI: api/openai.md- Security: api/security.md- Cloud: cloud.md- Examples: examples.mddiff --git a/src/python/txtai/api/routers/__init__.py b/src/python/txtai/api/routers/__init__.pyindex 9fbc3f0e..69021a25 100644--- a/src/python/txtai/api/routers/__init__.py+++ b/src/python/txtai/api/routers/__init__.py@@ -10,12 +10,15 @@ from . import extractorfrom . import labelsfrom . import llmfrom . import objects+from . import openaifrom . import ragfrom . import segmentationfrom . import similarityfrom . import summaryfrom . import tabularfrom . import textractor+from . import texttospeechfrom . import transcriptionfrom . import translationfrom . import workflow+from . import uploaddiff --git a/src/python/txtai/api/routers/openai.py b/src/python/txtai/api/routers/openai.pynew file mode 100644index 00000000..0a793ce1--- /dev/null+++ b/src/python/txtai/api/routers/openai.py@@ -0,0 +1,191 @@+"""+Defines an OpenAI-compatible API endpoint for txtai.++See the following specification for more information:+https://github.com/openai/openai-openapi+"""++import uuid+import json+import time++from typing import List, Optional, Union++from fastapi import APIRouter, Body, Form, UploadFile+from fastapi.responses import Response, StreamingResponse++from .. import application+from ..route import EncodingAPIRoute++router = APIRouter(route_class=EncodingAPIRoute)+++# pylint: disable=W0622[email protected]("/v1/chat/completions")+def chat(+ messages: List[dict] = Body(...),+ model: str = Body(...),+ max_completion_tokens: Optional[int] = Body(default=None),+ stream: Optional[bool] = Body(default=False),+):+ """+ Runs a chat completion request.++ Args:+ messages: list of messages [{"role": role, "content": content}]+ model: agent name, workflow name, pipeline name or embeddings+ max_completion_tokens: sets the max length to generate+ stream: streams response if True++ Returns:+ chat completion+ """++ # Build keyword arguments+ kwargs = {key: value for key, value in [("stream", stream), ("maxlength", max_completion_tokens)] if value}++ # Get first message+ message = messages[0]["content"]++ # Agent+ if model in application.get().agents:+ result = application.get().agent(model, message, **kwargs)++ # Embeddings search+ elif model == "embeddings":+ result = application.get().search(message, 1, **kwargs)[0]["text"]++ # Pipeline+ elif model in application.get().pipelines and model != "llm":+ result = application.get().pipeline(model, message, **kwargs)++ # Workflow+ elif model in application.get().workflows:+ result = list(application.get().workflow(model, [message], **kwargs))[0]++ # Default to running all messages through default LLM+ else:+ result = application.get().pipeline("llm", messages, **kwargs)++ # Write response+ return StreamingResponse(StreamingChatResponse()(model, result)) if stream else ChatResponse()(model, result)++[email protected]("/v1/embeddings")+def embeddings(input: Union[str, List[str]] = Body(...), model: str = Body(...)):+ """+ Creates an embeddings vector for the input text.++ Args:+ input: text|list+ model: model name++ Returns:+ list of embeddings vectors+ """++ # Convert to embeddings+ result = application.get().batchtransform([input] if isinstance(input, str) else input)++ # Build and return response+ data = []+ for index, embedding in enumerate(result):+ data.append({"object": "embedding", "embedding": embedding, "index": index})++ return {"object": "list", "data": data, "model": model}++[email protected]("/v1/audio/speech")+def speech(input: str = Body(...), voice: str = Body(...), response_format: Optional[str] = Body(default="mp3")):+ """+ Generates speech for the input text.++ Args:+ input: input text+ voice: speaker name+ response_format: audio encoding format, defaults to mp3++ Returns:+ audio data+ """++ # Convert to audio+ audio = application.get().pipeline("texttospeech", input, speaker=voice, encoding=response_format)++ # Write audio+ return Response(audio)++[email protected]("/v1/audio/transcriptions")+def transcribe(file: UploadFile, language: Optional[str] = Form(default=None), response_format: Optional[str] = Form(default="json")):+ """+ Transcribes audio to text.++ Args:+ file: audio input file+ language: language of input audio+ response_format: output format (json or text)++ Returns:+ transcribed text+ """++ # Transcribe+ text = application.get().pipeline("transcription", file.file, language=language, task="transcribe")+ return text if response_format == "text" else {"text": text}++[email protected]("/v1/audio/translations")+def translate(+ file: UploadFile,+ response_format: Optional[str] = Form(default="json"),+):+ """+ Translates audio to English.++ Args:+ file: audio input file+ response_format: output format (json or text)++ Returns:+ translated text+ """++ # Transcribe and translate to English+ text = application.get().pipeline("transcription", file.file, language="English", task="translate")+ return text if response_format == "text" else {"text": text}+++class ChatResponse:+ """+ Returns a chat response object.+ """++ def __call__(self, model, result):+ return {+ "id": str(uuid.uuid4()),+ "object": "chat.completion",+ "created": int(time.time() * 1000),+ "model": model,+ "choices": [{"id": 0, "message": {"role": "assistant", "content": result}, "finish_reason": "stop"}],+ }+++class StreamingChatResponse:+ """+ Returns a streaming chat response object.+ """++ def __call__(self, model, result):+ for chunk in result:+ yield "data: " + json.dumps(+ {+ "id": str(uuid.uuid4()),+ "object": "chat.completion.chunk",+ "created": int(time.time() * 1000),+ "model": model,+ "choices": [{"id": 0, "delta": {"content": chunk}}],+ }+ ) + "\n\n"++ yield "data: [DONE]\n\n"diff --git a/test/python/testapi/testopenai.py b/test/python/testapi/testopenai.pynew file mode 100644index 00000000..f25db225--- /dev/null+++ b/test/python/testapi/testopenai.py@@ -0,0 +1,201 @@+"""+OpenAI API module tests+"""++import os+import tempfile+import unittest++from unittest.mock import patch++from fastapi.testclient import TestClient++from txtai.api import application++# pylint: disable = C0411+from utils import Utils++# API Configuration+CONFIG = """+# Enable OpenAI-compatible API+openai: True++# Allow indexing of documents+writable: True++# Agent configuration+agent:+ hello:+ max_iterations: 1++# Embeddings settings+embeddings:+ path: sentence-transformers/nli-mpnet-base-v2+ content: True++# LLM configuration+llm:+ path: hf-internal-testing/tiny-random-LlamaForCausalLM++# Text segmentation+segmentation:++# Text to speech+texttospeech:++# Transcription+transcription:++# Workflow+workflow:+ echo:+ tasks:+ - task: console+"""+++# pylint: disable=R0904+class TestOpenAI(unittest.TestCase):+ """+ Tests for OpenAI-compatible API endpoint for txtai.+ """++ @staticmethod+ @patch.dict(os.environ, {"CONFIG": os.path.join(tempfile.gettempdir(), "testopenai.yml"), "API_CLASS": "txtai.api.API"})+ def start():+ """+ Starts a mock FastAPI client.+ """++ config = os.path.join(tempfile.gettempdir(), "testopenai.yml")++ with open(config, "w", encoding="utf-8") as output:+ output.write(CONFIG)++ # 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["hello"]+ 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 = TestOpenAI.start()++ cls.data = [+ "US tops 5 million confirmed virus cases",+ "Canada's last fully intact ice shelf has suddenly collapsed, forming a Manhattan-sized iceberg",+ "Beijing mobilises invasion craft along coast as Taiwan tensions escalate",+ "The National Park Service warns against sacrificing slower friends in a bear attack",+ "Maine man wins $1M from $25 lottery ticket",+ "Make huge profits without work, earn up to $100,000 a day",+ ]++ # Index data+ cls.client.post("add", json=[{"id": x, "text": row} for x, row in enumerate(cls.data)])+ cls.client.get("index")++ def testChatAgent(self):+ """+ Test a chat completion with an agent+ """++ response = self.client.post("/v1/chat/completions", json={"messages": [{"role": "user", "content": "Hello"}], "model": "hello"}).json()++ self.assertEqual(response["choices"][0]["message"]["content"], "Hi")++ def testChatLLM(self):+ """+ Test a chat completion with a LLM+ """++ response = self.client.post("/v1/chat/completions", json={"messages": [{"role": "user", "content": "Hello"}], "model": "llm"}).json()++ self.assertIsNotNone(response["choices"][0]["message"]["content"])++ def testChatPipeline(self):+ """+ Test a chat completion with a pipeline+ """++ response = self.client.post("/v1/chat/completions", json={"messages": [{"role": "user", "content": "Hello"}], "model": "segmentation"}).json()++ self.assertEqual(response["choices"][0]["message"]["content"], "Hello")++ def testChatSearch(self):+ """+ Test a chat completion with an embeddings search+ """++ response = self.client.post(+ "/v1/chat/completions", json={"messages": [{"role": "user", "content": "feel good story"}], "model": "embeddings"}+ ).json()++ self.assertEqual(response["choices"][0]["message"]["content"], self.data[4])++ def testChatStream(self):+ """+ Test a chat completion with a LLM+ """++ response = self.client.post("/v1/chat/completions", json={"messages": [{"role": "user", "content": "Hello"}], "model": "llm", "stream": True})++ self.assertGreater(len(response.text.split("\n\n")), 0)++ def testChatWorkflow(self):+ """+ Test a chat completion with a workflow+ """++ response = self.client.post("/v1/chat/completions", json={"messages": [{"role": "user", "content": "Hello"}], "model": "echo"}).json()++ self.assertEqual(response["choices"][0]["message"]["content"], "Hello")++ def testEmbeddings(self):+ """+ Test generating embeddings vectors+ """++ response = self.client.post("/v1/embeddings", json={"input": "text to embed", "model": "nli-mpnet-base-v2"}).json()++ self.assertEqual(len(response["data"][0]["embedding"]), 768)++ def testSpeech(self):+ """+ Test generating speech for input text+ """++ response = self.client.post(+ "/v1/audio/speech", json={"model": "tts", "input": "text to speak", "voice": "default", "response_format": "wav"}+ ).content++ self.assertTrue(response[0:4] == b"RIFF")++ def testTranscribe(self):+ """+ Test audio to text transcription+ """++ path = Utils.PATH + "/Make_huge_profits.wav"+ with open(path, "rb") as f:+ text = self.client.post("/v1/audio/transcriptions", files={"file": f}).json()["text"]+ self.assertEqual(text, "Make huge profits without working make up to one hundred thousand dollars a day")++ def testTranslate(self):+ """+ Test audio translation+ """++ path = Utils.PATH + "/Make_huge_profits.wav"+ with open(path, "rb") as f:+ text = self.client.post("/v1/audio/translations", files={"file": f}).json()["text"]+ self.assertEqual(text, "Make huge profits without working make up to one hundred thousand dollars a day")