💡 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
Return OpenAI-compliant index, created and finish_reason from chat completions, closes #1300
bob0abf3763b4ef
diff --git a/src/python/txtai/api/routers/openai.py b/src/python/txtai/api/routers/openai.pyindex 1b19291a..06171cd9 100644--- a/src/python/txtai/api/routers/openai.py+++ b/src/python/txtai/api/routers/openai.py@@ -165,9 +165,9 @@ class ChatResponse:return {"id": str(uuid.uuid4()),"object": "chat.completion",- "created": int(time.time() * 1000),+ "created": int(time.time()),"model": model,- "choices": [{"id": 0, "message": {"role": "assistant", "content": result}, "finish_reason": "stop"}],+ "choices": [{"index": 0, "message": {"role": "assistant", "content": result}, "finish_reason": "stop"}],}@@ -177,15 +177,38 @@ class StreamingChatResponse:"""def __call__(self, model, result):+ # All chunks of a response share the same id and creation time+ uid, created = str(uuid.uuid4()), int(time.time())+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 self.chunk(uid, created, model, {"content": chunk}, None)++ # Final chunk signals the end of the response+ yield self.chunk(uid, created, model, {}, "stop")yield "data: [DONE]\n\n"++ def chunk(self, uid, created, model, delta, reason):+ """+ Builds a server-sent event for a single chat completion chunk.++ Args:+ uid: response id+ created: response creation time in seconds+ model: model name+ delta: chunk content+ reason: finish reason, None until the final chunk++ Returns:+ server-sent event+ """++ data = {+ "id": uid,+ "object": "chat.completion.chunk",+ "created": created,+ "model": model,+ "choices": [{"index": 0, "delta": delta, "finish_reason": reason}],+ }++ return "data: " + json.dumps(data) + "\n\n"diff --git a/test/python/testapi/testopenai.py b/test/python/testapi/testopenai.pyindex fd377fa1..3294edb4 100644--- a/test/python/testapi/testopenai.py+++ b/test/python/testapi/testopenai.py@@ -2,8 +2,10 @@OpenAI API module tests"""+import jsonimport osimport tempfile+import timeimport unittestfrom unittest.mock import patch@@ -148,6 +150,20 @@ class TestOpenAI(unittest.TestCase):self.assertEqual(response["choices"][0]["message"]["content"], "Hello")+ def testChatResponseFormat(self):+ """+ Test that a chat completion follows the OpenAI response format+ """++ response = self.client.post("/v1/chat/completions", json={"messages": [{"role": "user", "content": "Hello"}], "model": "segmentation"}).json()++ self.assertEqual(response["object"], "chat.completion")+ self.assertEqual(response["choices"][0]["index"], 0)+ self.assertEqual(response["choices"][0]["finish_reason"], "stop")++ # Creation time is a Unix timestamp in seconds+ self.assertLessEqual(response["created"], time.time())+def testChatSearch(self):"""Test a chat completion with an embeddings search@@ -168,6 +184,23 @@ class TestOpenAI(unittest.TestCase):self.assertGreater(len(response.text.split("\n\n")), 0)+ def testChatStreamFormat(self):+ """+ Test that a streaming chat completion follows the OpenAI chunk format+ """++ response = self.client.post("/v1/chat/completions", json={"messages": [{"role": "user", "content": "Hello"}], "model": "llm", "stream": True})++ events = [event[len("data: ") :] for event in response.text.split("\n\n") if event]+ self.assertEqual(events[-1], "[DONE]")++ # All chunks share one id, and only the last one has a finish reason+ chunks = [json.loads(event) for event in events[:-1]]+ self.assertEqual(len({chunk["id"] for chunk in chunks}), 1)+ self.assertEqual({chunk["choices"][0]["index"] for chunk in chunks}, {0})+ self.assertEqual([chunk["choices"][0]["finish_reason"] for chunk in chunks], [None] * (len(chunks) - 1) + ["stop"])+ self.assertLessEqual(chunks[0]["created"], time.time())+def testChatWorkflow(self):"""Test a chat completion with a workflow