Skip to content

armgit / txtai

Public Imported from GitHub
0

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

Fix msgpack Accept header crashing streaming API endpoints (#1144)

Andrew Chen597ba8133d7b
diff --git a/src/python/txtai/api/route.py b/src/python/txtai/api/route.py
index 68a23d49..cc74358f 100644
--- a/src/python/txtai/api/route.py
+++ b/src/python/txtai/api/route.py
@@ -4,6 +4,7 @@ Route module
import json
+from fastapi.responses import StreamingResponse
from fastapi.routing import APIRoute
from .responses import ResponseFactory, MessagePackResponse
@@ -40,7 +41,7 @@ class EncodingAPIRoute(APIRoute):
status_code=response.status_code,
headers={k: v for k, v in response.headers.items() if k.lower() not in ["content-length", "content-type"]},
)
- if not isinstance(response, target) and target == MessagePackResponse
+ if not isinstance(response, (target, StreamingResponse)) and target == MessagePackResponse
else response
)
diff --git a/test/python/testapi/testencoding.py b/test/python/testapi/testencoding.py
index 1b7cfe99..1133f6f2 100644
--- a/test/python/testapi/testencoding.py
+++ b/test/python/testapi/testencoding.py
@@ -121,6 +121,34 @@ class TestEncoding(unittest.TestCase):
# Test reading image
self.assertIsInstance(PIL.Image.open(BytesIO(results[0]["object"])), PIL.Image.Image)
+ def testMessagePackStreaming(self):
+ """
+ Test a streaming response is passed through unchanged when msgpack is requested
+ """
+
+ from fastapi import FastAPI
+ from fastapi.responses import StreamingResponse
+
+ from txtai.api.route import EncodingAPIRoute
+
+ app = FastAPI()
+ app.router.route_class = EncodingAPIRoute
+
+ @app.get("/stream")
+ def stream():
+ def generate():
+ yield b"hello"
+ yield b"world"
+
+ return StreamingResponse(generate())
+
+ client = TestClient(app)
+
+ # A msgpack Accept header on a streaming endpoint must not try to re-wrap it (no .body)
+ response = client.get("stream", headers={"Accept": "application/msgpack"})
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.content, b"helloworld")
+
def testObjects(self):
"""
Test object encoding