|
| 1 | +from fastapi import APIRouter, WebSocket, WebSocketDisconnect |
| 2 | +from pydantic import BaseModel |
| 3 | +from datetime import datetime |
| 4 | +import asyncio |
| 5 | +import logging |
| 6 | +import json |
| 7 | +import openai |
| 8 | +import os |
| 9 | + |
| 10 | +logger = logging.getLogger(__name__) |
| 11 | + |
| 12 | +router = APIRouter() |
| 13 | + |
| 14 | +openai.api_key = os.getenv("OPENAI_API_KEY") |
| 15 | + |
| 16 | +class PromptRequest(BaseModel): |
| 17 | + prompt: str |
| 18 | + model: str = "gpt-4o" |
| 19 | + temperature: float = 0.7 |
| 20 | + max_tokens: int = 100 |
| 21 | + |
| 22 | + |
| 23 | +@router.websocket("/ws/generate") |
| 24 | +async def websocket_generate(websocket: WebSocket): |
| 25 | + await websocket.accept() |
| 26 | + logger.info("WebSocket connection accepted") |
| 27 | + |
| 28 | + stop_generation = False |
| 29 | + |
| 30 | + async def heartbeat(): |
| 31 | + """Send periodic ping to client to keep connection alive.""" |
| 32 | + while True: |
| 33 | + await asyncio.sleep(10) |
| 34 | + try: |
| 35 | + await websocket.send_text(json.dumps({"event": "ping", "timestamp": datetime.utcnow().isoformat()})) |
| 36 | + except Exception: |
| 37 | + logger.info("Heartbeat failed, connection might be closed") |
| 38 | + break |
| 39 | + |
| 40 | + heartbeat_task = asyncio.create_task(heartbeat()) |
| 41 | + |
| 42 | + try: |
| 43 | + while True: |
| 44 | + data = await websocket.receive_text() |
| 45 | + logger.info(f"Received input: {data}") |
| 46 | + |
| 47 | + try: |
| 48 | + message = json.loads(data) |
| 49 | + except json.JSONDecodeError: |
| 50 | + await websocket.send_text(json.dumps({"error": "Invalid JSON input."})) |
| 51 | + continue |
| 52 | + |
| 53 | + if isinstance(message, dict) and message.get("command") == "stop": |
| 54 | + logger.info("Stop command received.") |
| 55 | + stop_generation = True |
| 56 | + continue |
| 57 | + |
| 58 | + try: |
| 59 | + request_data = PromptRequest.parse_obj(message) |
| 60 | + except Exception as e: |
| 61 | + logger.error(f"Invalid prompt input: {e}") |
| 62 | + await websocket.send_text(json.dumps({ |
| 63 | + "error": "Invalid input format. Expected JSON with prompt, model, temperature, max_tokens." |
| 64 | + })) |
| 65 | + continue |
| 66 | + |
| 67 | + stop_generation = False |
| 68 | + |
| 69 | + async for token_data in generate_openai_stream(request_data): |
| 70 | + if stop_generation: |
| 71 | + logger.info("Generation stopped by client.") |
| 72 | + break |
| 73 | + await websocket.send_text(json.dumps(token_data)) |
| 74 | + |
| 75 | + await websocket.send_text(json.dumps({"event": "end_of_stream"})) |
| 76 | + |
| 77 | + except WebSocketDisconnect: |
| 78 | + logger.info("WebSocket connection disconnected") |
| 79 | + finally: |
| 80 | + heartbeat_task.cancel() |
| 81 | + |
| 82 | + |
| 83 | +async def generate_openai_stream(request: PromptRequest): |
| 84 | + try: |
| 85 | + response = await openai.ChatCompletion.acreate( |
| 86 | + model=request.model, |
| 87 | + messages=[{"role": "user", "content": request.prompt}], |
| 88 | + temperature=request.temperature, |
| 89 | + max_tokens=request.max_tokens, |
| 90 | + stream=True |
| 91 | + ) |
| 92 | + |
| 93 | + async for chunk in response: |
| 94 | + content = chunk["choices"][0].get("delta", {}).get("content") |
| 95 | + if content: |
| 96 | + yield { |
| 97 | + "token": content, |
| 98 | + "timestamp": datetime.utcnow().isoformat(), |
| 99 | + "model": request.model |
| 100 | + } |
| 101 | + except Exception as e: |
| 102 | + logger.error(f"OpenAI streaming error: {e}") |
| 103 | + yield {"error": str(e), "timestamp": datetime.utcnow().isoformat()} |
0 commit comments