AnatoliiG commited on
Commit ·
fca7a73
1
Parent(s): eddf357
Update routes.py
Browse files- src/api/routes.py +66 -10
src/api/routes.py
CHANGED
|
@@ -3,10 +3,10 @@ import json
|
|
| 3 |
|
| 4 |
from fastapi import APIRouter, Request
|
| 5 |
from fastapi.responses import JSONResponse, StreamingResponse
|
| 6 |
-
from src.utils.helpers import get_clean_text
|
| 7 |
|
| 8 |
from src.core.config import settings
|
| 9 |
from src.core.engine import engine
|
|
|
|
| 10 |
|
| 11 |
router = APIRouter()
|
| 12 |
|
|
@@ -25,23 +25,79 @@ async def chat_completions(request: Request):
|
|
| 25 |
stream = data.get("stream", True)
|
| 26 |
|
| 27 |
async def stream_generator():
|
|
|
|
| 28 |
async with engine.lock:
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
)
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
if stream:
|
| 39 |
return StreamingResponse(stream_generator(), media_type="text/event-stream")
|
| 40 |
|
|
|
|
| 41 |
async with engine.lock:
|
| 42 |
-
|
|
|
|
| 43 |
messages,
|
| 44 |
data.get("max_tokens", settings.DEFAULT_MAX_TOKENS),
|
| 45 |
data.get("temperature", settings.DEFAULT_TEMP),
|
| 46 |
stream=False,
|
| 47 |
)
|
|
|
|
|
|
| 3 |
|
| 4 |
from fastapi import APIRouter, Request
|
| 5 |
from fastapi.responses import JSONResponse, StreamingResponse
|
|
|
|
| 6 |
|
| 7 |
from src.core.config import settings
|
| 8 |
from src.core.engine import engine
|
| 9 |
+
from src.utils.helpers import get_clean_text
|
| 10 |
|
| 11 |
router = APIRouter()
|
| 12 |
|
|
|
|
| 25 |
stream = data.get("stream", True)
|
| 26 |
|
| 27 |
async def stream_generator():
|
| 28 |
+
# Ensure sequential processing: acquire the engine lock for the whole generation
|
| 29 |
async with engine.lock:
|
| 30 |
+
import threading
|
| 31 |
+
|
| 32 |
+
# Use an asyncio.Queue to safely transfer chunks from a blocking worker thread to the async generator
|
| 33 |
+
q: asyncio.Queue = asyncio.Queue()
|
| 34 |
+
stop_event = threading.Event()
|
| 35 |
+
loop = asyncio.get_running_loop()
|
| 36 |
+
|
| 37 |
+
def worker():
|
| 38 |
+
try:
|
| 39 |
+
for chunk in engine.llm.create_chat_completion(
|
| 40 |
+
messages=messages,
|
| 41 |
+
max_tokens=int(
|
| 42 |
+
data.get("max_tokens", settings.DEFAULT_MAX_TOKENS)
|
| 43 |
+
),
|
| 44 |
+
temperature=float(
|
| 45 |
+
data.get("temperature", settings.DEFAULT_TEMP)
|
| 46 |
+
),
|
| 47 |
+
stream=True,
|
| 48 |
+
):
|
| 49 |
+
# stop early if requested (e.g. client disconnected)
|
| 50 |
+
if stop_event.is_set():
|
| 51 |
+
break
|
| 52 |
+
loop.call_soon_threadsafe(q.put_nowait, chunk)
|
| 53 |
+
except Exception as e:
|
| 54 |
+
# Pass exception to the async side so we can surface an error or terminate cleanly
|
| 55 |
+
loop.call_soon_threadsafe(q.put_nowait, {"__error": str(e)})
|
| 56 |
+
finally:
|
| 57 |
+
# Sentinel to mark completion
|
| 58 |
+
loop.call_soon_threadsafe(q.put_nowait, None)
|
| 59 |
+
|
| 60 |
+
# Run the blocking model iteration in a thread so it doesn't block the event loop
|
| 61 |
+
worker_future = loop.run_in_executor(None, worker)
|
| 62 |
+
|
| 63 |
+
try:
|
| 64 |
+
while True:
|
| 65 |
+
item = await q.get()
|
| 66 |
+
if item is None:
|
| 67 |
+
# worker finished normally
|
| 68 |
+
break
|
| 69 |
+
# If worker reported an error, stream it and break
|
| 70 |
+
if isinstance(item, dict) and item.get("__error"):
|
| 71 |
+
yield f"data: {json.dumps({'error': item['__error']})}\n\n"
|
| 72 |
+
break
|
| 73 |
+
yield f"data: {json.dumps(item)}\n\n"
|
| 74 |
+
yield "data: [DONE]\n\n"
|
| 75 |
+
except asyncio.CancelledError:
|
| 76 |
+
# Client disconnected: signal the worker to stop and wait for it to finish, then re-raise to terminate streaming
|
| 77 |
+
stop_event.set()
|
| 78 |
+
try:
|
| 79 |
+
await worker_future
|
| 80 |
+
except Exception:
|
| 81 |
+
pass
|
| 82 |
+
raise
|
| 83 |
+
finally:
|
| 84 |
+
# Ensure worker is signalled to stop and awaited (idempotent)
|
| 85 |
+
stop_event.set()
|
| 86 |
+
try:
|
| 87 |
+
await worker_future
|
| 88 |
+
except Exception:
|
| 89 |
+
pass
|
| 90 |
|
| 91 |
if stream:
|
| 92 |
return StreamingResponse(stream_generator(), media_type="text/event-stream")
|
| 93 |
|
| 94 |
+
# For non-streaming responses: keep sequential processing but run blocking work in a thread
|
| 95 |
async with engine.lock:
|
| 96 |
+
result = await asyncio.to_thread(
|
| 97 |
+
engine.generate,
|
| 98 |
messages,
|
| 99 |
data.get("max_tokens", settings.DEFAULT_MAX_TOKENS),
|
| 100 |
data.get("temperature", settings.DEFAULT_TEMP),
|
| 101 |
stream=False,
|
| 102 |
)
|
| 103 |
+
return result
|