Spaces:
Running

michdubai commited on
Commit
2c4e131
ยท
verified ยท
1 Parent(s): 46e9d54

Update backend/routes/websocket.py

Browse files
Files changed (1) hide show
  1. backend/routes/websocket.py +236 -232
backend/routes/websocket.py CHANGED
@@ -1,242 +1,246 @@
1
- import json
2
- import os
3
  import asyncio
4
- from websockets import connect
5
- from typing import Dict, Optional, Any
6
-
7
-
8
- class GeminiConnection:
9
- """
10
- Client for connecting to the Gemini Multimodal API
11
- Handles WebSocket communication, audio/video streaming, and response processing
12
- """
13
-
14
- def __init__(self, client_id: str = "unknown"):
15
- """Initialize the Gemini connection with API key from environment"""
16
- self.client_id = client_id
17
- self.api_key = os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY")
18
- if not self.api_key:
19
- raise ValueError("GEMINI_API_KEY or GOOGLE_API_KEY environment variable is not set")
20
-
21
- # Use model that supports session resumption
22
- self.model = "gemini-3.1-flash-live-preview"
23
- self.uri = (
24
- "wss://generativelanguage.googleapis.com/ws/"
25
- "google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContent"
26
- f"?key={self.api_key}"
27
- )
28
- self.ws = None
29
- self.config = None
30
- self.resumption_handle = None
31
- self.last_consumed_index = None # Track for advanced resumption
32
- self.reconnect_count = 0
33
- self.max_reconnect_attempts = 5
34
-
35
- def set_config(self, config_data: Dict[str, Any]) -> None:
36
- """Store systemPrompt, voice, etc."""
37
- self.config = config_data
38
-
39
- async def connect(self, resumption_handle: Optional[str] = None) -> bool:
40
- """
41
- Establish WebSocket connection and send initial setup message
42
- Returns: True if session was resumed, False if new session
43
- """
44
- if not self.config:
45
- raise ValueError("Configuration must be set before connecting.")
46
-
47
- try:
48
- print(f"[DEBUG][{self.client_id}] ๐ŸŒ Connecting to Gemini API with model: {self.model}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
- self.ws = await connect(
51
- self.uri,
52
- additional_headers={"Content-Type": "application/json"}
53
  )
54
- print(f"[DEBUG][{self.client_id}] โœ… WebSocket established")
55
-
56
- # Build setup message with optional resumption handle
57
- setup_message = self._build_setup_message(resumption_handle)
58
 
59
- print(f"[DEBUG][{self.client_id}] ๐Ÿ“ค Sending setup message...")
60
- if resumption_handle:
61
- print(f"[DEBUG][{self.client_id}] ๐Ÿ”„ Using resumption handle: {resumption_handle[:30]}...")
 
 
62
 
63
- await self.ws.send(json.dumps(setup_message))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
- # Read initialization acknowledgment from Gemini
66
- setup_response = await self.ws.recv()
67
- response_data = json.loads(setup_response)
 
 
68
 
69
- print(f"[DEBUG][{self.client_id}] ๐Ÿ“‹ Setup response received")
70
- print(f"[DEBUG][{self.client_id}] ๐Ÿ“‹ Response preview: {json.dumps(response_data)[:500]}")
71
 
72
- # Check if session was resumed
73
- resumed = False
74
- if "setupComplete" in response_data:
75
- setup_complete = response_data["setupComplete"]
76
- if "sessionResumption" in setup_complete:
77
- session_info = setup_complete["sessionResumption"]
78
- if session_info.get("resumed", False):
79
- resumed = True
80
- print(f"[DEBUG][{self.client_id}] โœ… Session resumed successfully")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
- self.reconnect_count = 0
83
- return resumed
84
-
85
- except Exception as e:
86
- raise ConnectionError(f"Failed to connect to Gemini API: {str(e)}")
87
-
88
- def _build_setup_message(self, resumption_handle: Optional[str] = None) -> dict:
89
- """Build the setup message following official documentation"""
90
- # Build live_connect_config according to official docs [citation:3][citation:7]
91
- live_connect_config = {
92
- "response_modalities": ["AUDIO"]
93
- }
94
-
95
- # Add session resumption config
96
- if resumption_handle:
97
- # Reconnecting - provide the handle [citation:3]
98
- live_connect_config["sessionResumption"] = {
99
- "handle": resumption_handle
100
- }
101
- else:
102
- # New session - enable session resumption (empty object enables it) [citation:7]
103
- live_connect_config["sessionResumption"] = {}
104
-
105
- # Add voice configuration if specified
106
- if self.config.get("voice"):
107
- live_connect_config["speechConfig"] = {
108
- "voiceConfig": {
109
- "prebuiltVoiceConfig": {
110
- "voiceName": self.config.get("voice")
111
- }
112
- }
113
- }
114
-
115
- setup_message = {
116
- "setup": {
117
- "model": f"models/{self.model}",
118
- "liveConnectConfig": live_connect_config,
119
- "systemInstruction": {
120
- "parts": [
121
- {
122
- "text": self.config.get(
123
- "systemPrompt",
124
- "You are a friendly AI Assistant."
125
- )
126
- }
127
- ]
128
- }
129
- }
130
- }
131
-
132
- return setup_message
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
 
134
- async def check_connection(self) -> bool:
135
- """Check if WebSocket connection is still alive"""
136
- if not self.ws:
137
- return False
138
-
139
- try:
140
- pong_waiter = await self.ws.ping()
141
- await asyncio.wait_for(pong_waiter, timeout=2.0)
142
- return True
143
- except Exception:
144
- return False
145
-
146
- async def send_audio(self, base64_pcm: str) -> None:
147
- """Send 16-bit PCM audio (base64) to Gemini under 'realtimeInput'."""
148
- if not self.ws:
149
- return
150
-
151
- payload = {
152
- "realtimeInput": {
153
- "mediaChunks": [
154
- {
155
- "data": base64_pcm,
156
- "mimeType": "audio/pcm"
157
- }
158
- ]
159
- }
160
- }
161
- await self.ws.send(json.dumps(payload))
162
-
163
- async def send_text(self, text: str) -> None:
164
- """Send text message to Gemini."""
165
- if not self.ws:
166
- return
167
-
168
- text_msg = {
169
- "clientContent": {
170
- "turns": [
171
- {
172
- "role": "user",
173
- "parts": [{"text": text}]
174
- }
175
- ],
176
- "turnComplete": True
177
- }
178
- }
179
- await self.ws.send(json.dumps(text_msg))
180
-
181
- async def send_image(self, base64_jpeg: str) -> None:
182
- """Send image data to Gemini."""
183
- if not self.ws:
184
- return
185
-
186
- payload = {
187
- "realtimeInput": {
188
- "mediaChunks": [
189
- {
190
- "data": base64_jpeg,
191
- "mimeType": "image/jpeg"
192
- }
193
- ]
194
- }
195
- }
196
- await self.ws.send(json.dumps(payload))
197
-
198
- async def send_file(self, file_uri: str, mime_type: str) -> None:
199
- """Send a file reference (from Gemini File API) to Gemini."""
200
- if not self.ws:
201
- return
202
-
203
- payload = {
204
- "clientContent": {
205
- "turns": [
206
- {
207
- "role": "user",
208
- "parts": [
209
- {
210
- "fileData": {
211
- "mimeType": mime_type,
212
- "fileUri": file_uri
213
- }
214
- }
215
- ]
216
- }
217
- ],
218
- "turnComplete": True
219
- }
220
- }
221
- await self.ws.send(json.dumps(payload))
222
-
223
- async def receive(self) -> Optional[str]:
224
- """Wait for next message from Gemini."""
225
- if not self.ws:
226
- return None
227
- try:
228
- return await self.ws.recv()
229
- except Exception as e:
230
- print(f"[DEBUG][{self.client_id}] โŒ Receive error: {e}")
231
- return None
232
-
233
- async def close(self) -> None:
234
- """Close the WebSocket connection."""
235
- if self.ws:
236
- try:
237
- await self.ws.close()
238
- except Exception:
239
- pass
240
- finally:
241
- self.ws = None
242
- print(f"[DEBUG][{self.client_id}] ๐Ÿงน Cleanup complete")
 
 
 
1
  import asyncio
2
+ import json
3
+ from fastapi import APIRouter, WebSocket, WebSocketDisconnect
4
+ from typing import Dict
5
+
6
+ from gemini.client import GeminiConnection
7
+
8
+ # Create router - THIS IS REQUIRED
9
+ router = APIRouter()
10
+
11
+ # Store active connections
12
+ connections: Dict[str, GeminiConnection] = {}
13
+
14
+
15
+ async def reconnect_gemini(websocket: WebSocket, client_id: str, old_gemini: GeminiConnection, resumption_handle: str):
16
+ """Reconnect Gemini using session resumption"""
17
+ try:
18
+ print(f"[DEBUG][{client_id}] ๐Ÿ”„ Attempting to reconnect with resumption handle: {resumption_handle[:50]}...")
19
+
20
+ new_gemini = GeminiConnection(client_id=client_id)
21
+ new_gemini.set_config(old_gemini.config)
22
+
23
+ start_time = asyncio.get_event_loop().time()
24
+ await new_gemini.connect(resumption_handle=resumption_handle)
25
+ connect_time = asyncio.get_event_loop().time() - start_time
26
+
27
+ print(f"[DEBUG][{client_id}] โœ… Reconnection successful in {connect_time:.2f}s")
28
+
29
+ connections[client_id] = new_gemini
30
+
31
+ await websocket.send_json({
32
+ "type": "reconnection",
33
+ "message": "Connection restored",
34
+ "resumed": True,
35
+ "elapsed_ms": int(connect_time * 1000)
36
+ })
37
+
38
+ return new_gemini
39
+
40
+ except Exception as e:
41
+ print(f"[DEBUG][{client_id}] โŒ Reconnection failed: {e}")
42
+ import traceback
43
+ traceback.print_exc()
44
+ await websocket.send_json({
45
+ "type": "error",
46
+ "message": f"Reconnection failed: {str(e)}"
47
+ })
48
+ return None
49
+
50
+
51
+ @router.websocket("/ws/{client_id}")
52
+ async def websocket_endpoint(websocket: WebSocket, client_id: str):
53
+ await websocket.accept()
54
+ print(f"[DEBUG][{client_id}] ๐Ÿ“ก WebSocket accepted")
55
+
56
+ gemini = GeminiConnection(client_id=client_id)
57
+ connections[client_id] = gemini
58
+
59
+ reconnect_count = 0
60
+ receive_task = None
61
+ send_task = None
62
+
63
+ try:
64
+ # Receive config
65
+ initial_msg = await websocket.receive_json()
66
+ if initial_msg.get("type") != "config":
67
+ raise ValueError("First WebSocket message must be configuration.")
68
+
69
+ config_data = initial_msg.get("config", {})
70
+ gemini.set_config(config_data)
71
+ print(f"[DEBUG][{client_id}] ๐Ÿ“ Config received")
72
+
73
+ # Connect to Gemini
74
+ await gemini.connect()
75
+ print(f"[DEBUG][{client_id}] ๐Ÿ”— Gemini connected")
76
+
77
+ # Main loop with reconnection support
78
+ while True:
79
+ receive_task = asyncio.create_task(receive_from_client(websocket, gemini, client_id))
80
+ send_task = asyncio.create_task(send_to_frontend(websocket, gemini, client_id))
81
 
82
+ done, pending = await asyncio.wait(
83
+ [receive_task, send_task],
84
+ return_when=asyncio.FIRST_COMPLETED
85
  )
 
 
 
 
86
 
87
+ for task in pending:
88
+ task.cancel()
89
+
90
+ connection_alive = await gemini.check_connection()
91
+ print(f"[DEBUG][{client_id}] ๐Ÿ“Š Connection check: alive={connection_alive}, reconnect_count={reconnect_count}")
92
 
93
+ if not connection_alive and gemini.resumption_handle and reconnect_count < 5:
94
+ reconnect_count += 1
95
+ print(f"[DEBUG][{client_id}] ๐Ÿ”„ Auto-reconnect attempt #{reconnect_count}")
96
+
97
+ new_gemini = await reconnect_gemini(websocket, client_id, gemini, gemini.resumption_handle)
98
+ if new_gemini:
99
+ gemini = new_gemini
100
+ connections[client_id] = gemini
101
+ print(f"[DEBUG][{client_id}] โœ… Reconnect successful")
102
+ continue
103
+ else:
104
+ print(f"[DEBUG][{client_id}] โŒ Reconnect failed")
105
+ break
106
+ else:
107
+ break
108
+
109
+ except WebSocketDisconnect:
110
+ print(f"[DEBUG][{client_id}] ๐Ÿ”Œ WebSocket disconnected")
111
+ except Exception as e:
112
+ print(f"[DEBUG][{client_id}] โŒ Error: {e}")
113
+ import traceback
114
+ traceback.print_exc()
115
+ finally:
116
+ if receive_task and not receive_task.done():
117
+ receive_task.cancel()
118
+ if send_task and not send_task.done():
119
+ send_task.cancel()
120
+
121
+ await gemini.close()
122
+ if client_id in connections:
123
+ del connections[client_id]
124
+ print(f"[DEBUG][{client_id}] ๐Ÿงน Cleanup complete")
125
+
126
 
127
+ async def receive_from_client(websocket: WebSocket, gemini: GeminiConnection, client_id: str):
128
+ """Process incoming messages from the client browser"""
129
+ try:
130
+ while True:
131
+ message = await websocket.receive()
132
 
133
+ if message["type"] == "websocket.disconnect":
134
+ return
135
 
136
+ content = json.loads(message["text"])
137
+ msg_type = content.get("type")
138
+
139
+ if msg_type == "audio":
140
+ await gemini.send_audio(content["data"])
141
+ elif msg_type == "image":
142
+ await gemini.send_image(content["data"])
143
+ elif msg_type == "text":
144
+ await gemini.send_text(content["data"])
145
+ elif msg_type == "file":
146
+ await gemini.send_file(content["uri"], content["mime_type"])
147
+
148
+ except Exception as e:
149
+ print(f"[DEBUG][{client_id}] โŒ receive_from_client error: {e}")
150
+
151
+
152
+ async def send_to_frontend(websocket: WebSocket, gemini: GeminiConnection, client_id: str):
153
+ """Forward Gemini responses to the client browser following official docs"""
154
+ message_count = 0
155
+ try:
156
+ while True:
157
+ msg = await gemini.receive()
158
+ if not msg:
159
+ continue
160
+
161
+ response = json.loads(msg)
162
+ message_count += 1
163
 
164
+ # Log first few raw responses for debugging
165
+ if message_count <= 10:
166
+ print(f"[DEBUG][{client_id}] ๐Ÿ“จ Raw response #{message_count}: {msg[:300]}...")
167
+
168
+ # Handle sessionResumptionUpdate (camelCase as per official docs)
169
+ if "sessionResumptionUpdate" in response:
170
+ update = response["sessionResumptionUpdate"]
171
+ print(f"[DEBUG][{client_id}] ๐Ÿ”‘ Session resumption update received")
172
+
173
+ # Check if we got a valid handle
174
+ new_handle = update.get("newHandle")
175
+ resumable = update.get("resumable", False)
176
+ last_index = update.get("lastConsumedClientMessageIndex")
177
+
178
+ print(f"[DEBUG][{client_id}] resumable: {resumable}")
179
+ print(f"[DEBUG][{client_id}] newHandle: {new_handle[:50] if new_handle else 'None'}...")
180
+ print(f"[DEBUG][{client_id}] lastConsumedClientMessageIndex: {last_index}")
181
+
182
+ # Store the handle ONLY if resumable is True
183
+ if resumable and new_handle:
184
+ gemini.resumption_handle = new_handle
185
+ gemini.last_consumed_index = last_index
186
+ print(f"[DEBUG][{client_id}] โœ… Session handle stored: {new_handle[:50]}...")
187
+ await websocket.send_json({
188
+ "type": "session_resumption_ready",
189
+ "handle": new_handle,
190
+ "resumable": resumable
191
+ })
192
+ else:
193
+ print(f"[DEBUG][{client_id}] โš ๏ธ Handle not ready yet (resumable={resumable}, has handle={new_handle is not None})")
194
+ print(f"[DEBUG][{client_id}] Will wait for future sessionResumptionUpdate messages")
195
+ continue
196
+
197
+ # Handle goAway (camelCase as per official docs)
198
+ if "goAway" in response:
199
+ go_away = response["goAway"]
200
+ time_left = go_away.get("timeLeft")
201
+ print(f"[DEBUG][{client_id}] โš ๏ธ GoAway received! Time left: {time_left}")
202
+ await websocket.send_json({
203
+ "type": "connection_warning",
204
+ "message": f"Connection will close in {time_left}s",
205
+ "time_left": time_left
206
+ })
207
+ continue
208
+
209
+ # Handle server content
210
+ server_content = response.get("serverContent", {})
211
+
212
+ # User speech transcription
213
+ if "inputTranscription" in server_content:
214
+ text_val = server_content["inputTranscription"].get("text", "")
215
+ if text_val:
216
+ print(f"[DEBUG][{client_id}] ๐ŸŽ™๏ธ User: {text_val[:50]}")
217
+ await websocket.send_json({"type": "user_text", "text": text_val})
218
+
219
+ # Gemini output transcription
220
+ if "outputTranscription" in server_content:
221
+ text_val = server_content["outputTranscription"].get("text", "")
222
+ if text_val:
223
+ print(f"[DEBUG][{client_id}] ๐Ÿค– Gemini: {text_val[:50]}")
224
+ await websocket.send_json({"type": "gemini_text", "text": text_val})
225
+
226
+ # Audio output
227
+ if "modelTurn" in server_content:
228
+ parts = server_content["modelTurn"].get("parts", [])
229
+ for part in parts:
230
+ if "inlineData" in part:
231
+ await websocket.send_json({"type": "audio", "data": part["inlineData"]["data"]})
232
+ elif "text" in part:
233
+ await websocket.send_json({"type": "gemini_text", "text": part["text"]})
234
+
235
+ # Turn complete
236
+ if server_content.get("turnComplete"):
237
+ print(f"[DEBUG][{client_id}] ๐Ÿ”„ Turn complete")
238
+ await websocket.send_json({"type": "turn_complete"})
239
+
240
+ # Generation complete
241
+ if server_content.get("generationComplete"):
242
+ print(f"[DEBUG][{client_id}] โœ… Generation complete")
243
+ await websocket.send_json({"type": "generation_complete"})
244
 
245
+ except Exception as e:
246
+ print(f"[DEBUG][{client_id}] โŒ send_to_frontend error: {e}")