Download fastapi-backend/app/api/websocket.py from APIMoral/README: direct link, hf CLI and curl.
- Browser
- Download file 5.89 kB
-
https://huggingface.co/spaces/APIMoral/README/resolve/main/fastapi-backend/app/api/websocket.py
- Command line
-
hf download hf://spaces/APIMoral/README/fastapi-backend/app/api/websocket.py
-
curl -L -o websocket.py https://huggingface.co/spaces/APIMoral/README/resolve/main/fastapi-backend/app/api/websocket.py
5.89 kB
| from fastapi import APIRouter, WebSocket, WebSocketDisconnect, Depends, HTTPException | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from sqlalchemy import select | |
| from app.database import get_db | |
| from app.services.auth import decode_token | |
| from app.services.rag import process_chat_message_stream, build_system_prompt, retrieve_relevant_documents | |
| from app.models.bot import Bot | |
| from app.config import settings | |
| import json | |
| import asyncio | |
| router = APIRouter(tags=["websocket"]) | |
| class ConnectionManager: | |
| def __init__(self): | |
| # Active connections: {session_id: [websocket]} | |
| self.active_connections: dict[str, list[WebSocket]] = {} | |
| async def connect(self, websocket: WebSocket, session_id: str): | |
| await websocket.accept() | |
| if session_id not in self.active_connections: | |
| self.active_connections[session_id] = [] | |
| self.active_connections[session_id].append(websocket) | |
| def disconnect(self, websocket: WebSocket, session_id: str): | |
| if session_id in self.active_connections: | |
| if websocket in self.active_connections[session_id]: | |
| self.active_connections[session_id].remove(websocket) | |
| if not self.active_connections[session_id]: | |
| del self.active_connections[session_id] | |
| async def send_personal_message(self, message: dict, websocket: WebSocket): | |
| await websocket.send_json(message) | |
| async def broadcast(self, message: dict, session_id: str): | |
| if session_id in self.active_connections: | |
| for connection in self.active_connections[session_id]: | |
| await connection.send_json(message) | |
| manager = ConnectionManager() | |
| async def websocket_chat( | |
| websocket: WebSocket, | |
| token: str, | |
| db: AsyncSession = Depends(get_db) | |
| ): | |
| """WebSocket endpoint for streaming chat responses""" | |
| # Verify token | |
| payload = decode_token(token) | |
| if payload is None: | |
| await websocket.close(code=4001, reason="Invalid token") | |
| return | |
| user_email: str = payload.get("sub") | |
| if user_email is None: | |
| await websocket.close(code=4002, reason="Invalid token payload") | |
| return | |
| await manager.connect(websocket, "global") | |
| try: | |
| while True: | |
| # Receive message from client | |
| data = await websocket.receive_text() | |
| try: | |
| message_data = json.loads(data) | |
| bot_id = message_data.get("bot_id") | |
| user_message = message_data.get("message") | |
| session_id = message_data.get("session_id", f"ws_{user_email}_{int(asyncio.get_event_loop().time())}") | |
| lead_name = message_data.get("lead_name") | |
| lead_phone = message_data.get("lead_phone") | |
| lead_email = message_data.get("lead_email") | |
| if not bot_id or not user_message: | |
| await manager.send_personal_message({ | |
| "type": "error", | |
| "message": "bot_id и message обязательны" | |
| }, websocket) | |
| continue | |
| # Get bot from database | |
| result = await db.execute( | |
| select(Bot).where(Bot.id == bot_id) | |
| ) | |
| bot = result.scalar_one_or_none() | |
| if not bot: | |
| await manager.send_personal_message({ | |
| "type": "error", | |
| "message": "Bot not found" | |
| }, websocket) | |
| continue | |
| if not bot.is_active: | |
| await manager.send_personal_message({ | |
| "type": "error", | |
| "message": "Bot is not active" | |
| }, websocket) | |
| continue | |
| # Send typing indicator | |
| await manager.send_personal_message({ | |
| "type": "typing_start" | |
| }, websocket) | |
| # Create ChatRequest object | |
| from app.schemas.message import ChatRequest | |
| chat_request = ChatRequest( | |
| bot_id=bot_id, | |
| message=user_message, | |
| session_id=session_id, | |
| lead_name=lead_name, | |
| lead_phone=lead_phone, | |
| lead_email=lead_email | |
| ) | |
| # Stream response | |
| full_response = "" | |
| async for chunk in process_chat_message_stream(bot, chat_request, db): | |
| full_response += chunk | |
| await manager.send_personal_message({ | |
| "type": "chunk", | |
| "content": chunk | |
| }, websocket) | |
| # Send complete response | |
| await manager.send_personal_message({ | |
| "type": "complete", | |
| "content": full_response, | |
| "session_id": session_id | |
| }, websocket) | |
| except json.JSONDecodeError: | |
| await manager.send_personal_message({ | |
| "type": "error", | |
| "message": "Invalid JSON" | |
| }, websocket) | |
| except Exception as e: | |
| await manager.send_personal_message({ | |
| "type": "error", | |
| "message": str(e) | |
| }, websocket) | |
| print(f"WebSocket error: {e}") | |
| except WebSocketDisconnect: | |
| manager.disconnect(websocket, "global") | |
| except Exception as e: | |
| print(f"WebSocket connection error: {e}") | |
| manager.disconnect(websocket, "global") | |