File size: 5,888 Bytes
5c1ff2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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()


@router.websocket("/ws/chat")
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")