Spaces:
Runtime error
Runtime error
File size: 2,959 Bytes
b334624 |
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 |
from fastapi import WebSocket, WebSocketDisconnect
from app.ai_responder import ai_answer
from app.session_manager import get_session
import json
SALES_NUMBER = "+91 7249477972"
class ConnectionManager:
def __init__(self):
self.active_connections = {}
async def connect(self, websocket: WebSocket, session_id: str):
await websocket.accept()
self.active_connections[session_id] = websocket
def disconnect(self, session_id: str):
self.active_connections.pop(session_id, None)
async def receive_audio(self, session_id: str):
websocket = self.active_connections.get(session_id)
session = get_session(session_id)
if not session:
print(f"Session {session_id} not found, disconnecting...")
print(f"current active connections: {self.active_connections}")
if websocket:
try:
while True:
message = await websocket.receive_json()
print(f"Received message: {message}")
message_type = message.get("type")
print(f"Received message type: {message_type}")
if message_type == "setup":
print(f"This is the setup message:- {message}")
print(f"Setup message received for session {session_id}.")
elif message_type == "prompt":
user_input = message["voicePrompt"]
print(f"Received transcription:- {user_input}")
ai_response = await ai_answer(user_input)
lower = ai_answer.lower()
if "sales" in lower:
dept = SALES_NUMBER
else:
dept = None
if dept:
await websocket.send_text(json.dumps({
"type": "handoff",
"dialNumber": dept
}))
break # end session so Twilio exits ConversationRelay
await websocket.send_json({
"type": "text",
"token": ai_response,
"last": True # Assuming this is the last message in the conversation
})
elif message_type == "interrupt":
print(f"Interrupt message received for session {session_id}.")
# break
continue
except WebSocketDisconnect:
self.disconnect(session_id)
manager = ConnectionManager()
async def websocket_endpoint(websocket: WebSocket, session_id: str):
await manager.connect(websocket, session_id)
await manager.receive_audio(session_id) |