Spaces:
Running
Running
Fix SSE handling
Browse files
app.py
CHANGED
|
@@ -604,15 +604,41 @@ async def generate_text(request: Request):
|
|
| 604 |
headers = {"Authorization": f"Bearer {API_KEY}"}
|
| 605 |
|
| 606 |
if stream:
|
|
|
|
|
|
|
| 607 |
async def event_generator():
|
| 608 |
-
|
| 609 |
-
async with
|
| 610 |
-
async
|
| 611 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 612 |
|
| 613 |
return StreamingResponse(
|
| 614 |
event_generator(),
|
| 615 |
media_type="text/event-stream",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 616 |
)
|
| 617 |
else:
|
| 618 |
async with httpx.AsyncClient(timeout=None) as client:
|
|
|
|
| 604 |
headers = {"Authorization": f"Bearer {API_KEY}"}
|
| 605 |
|
| 606 |
if stream:
|
| 607 |
+
body["stream"] = True
|
| 608 |
+
|
| 609 |
async def event_generator():
|
| 610 |
+
try:
|
| 611 |
+
async with httpx.AsyncClient(timeout=None) as client:
|
| 612 |
+
async with client.stream(
|
| 613 |
+
"POST",
|
| 614 |
+
url,
|
| 615 |
+
json=body,
|
| 616 |
+
headers=headers,
|
| 617 |
+
) as r:
|
| 618 |
+
content_type = r.headers.get(
|
| 619 |
+
"content-type", "text/event-stream"
|
| 620 |
+
)
|
| 621 |
+
|
| 622 |
+
async for line in r.aiter_lines():
|
| 623 |
+
if line == "":
|
| 624 |
+
yield "\n"
|
| 625 |
+
continue
|
| 626 |
+
|
| 627 |
+
yield line + "\n"
|
| 628 |
+
|
| 629 |
+
except asyncio.CancelledError:
|
| 630 |
+
return
|
| 631 |
+
except Exception as e:
|
| 632 |
+
yield f"data: {{\"error\": \"{str(e)}\"}}\n\n"
|
| 633 |
|
| 634 |
return StreamingResponse(
|
| 635 |
event_generator(),
|
| 636 |
media_type="text/event-stream",
|
| 637 |
+
headers={
|
| 638 |
+
"Cache-Control": "no-cache",
|
| 639 |
+
"Connection": "keep-alive",
|
| 640 |
+
"X-Accel-Buffering": "no", # critical for nginx
|
| 641 |
+
},
|
| 642 |
)
|
| 643 |
else:
|
| 644 |
async with httpx.AsyncClient(timeout=None) as client:
|