Spaces:
Running

michdubai commited on
Commit
43f2054
Β·
verified Β·
1 Parent(s): 2c4e131

Update backend/routes/websocket.py

Browse files
Files changed (1) hide show
  1. backend/routes/websocket.py +143 -164
backend/routes/websocket.py CHANGED
@@ -5,127 +5,181 @@ 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()
@@ -133,114 +187,39 @@ async def receive_from_client(websocket: WebSocket, gemini: GeminiConnection, cl
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}")
 
5
 
6
  from gemini.client import GeminiConnection
7
 
 
8
  router = APIRouter()
 
 
9
  connections: Dict[str, GeminiConnection] = {}
10
 
11
 
12
+ async def handle_session_resumption(websocket: WebSocket, client_id: str,
13
+ gemini: GeminiConnection, update: dict):
14
+ """Handle session resumption update from Gemini"""
15
+ new_handle = update.get("newHandle")
16
+ resumable = update.get("resumable", False)
17
+
18
+ print(f"[DEBUG][{client_id}] πŸ”‘ Session update - resumable: {resumable}")
19
+
20
+ if resumable and new_handle:
21
+ gemini.resumption_handle = new_handle
22
+ print(f"[DEBUG][{client_id}] βœ… Saved resumption handle: {new_handle[:50]}...")
 
 
 
 
 
23
  await websocket.send_json({
24
+ "type": "session_resumption_ready",
25
+ "handle": new_handle
 
 
26
  })
27
+ else:
28
+ print(f"[DEBUG][{client_id}] ⏳ Handle not ready yet")
 
 
 
 
 
29
  await websocket.send_json({
30
+ "type": "session_resumption_pending",
31
+ "message": "Session resumption will be available soon"
32
  })
33
+
34
+
35
+ async def handle_go_away(websocket: WebSocket, client_id: str, go_away: dict):
36
+ """Handle goAway message from Gemini"""
37
+ time_left = go_away.get("timeLeft", 0)
38
+ print(f"[DEBUG][{client_id}] ⚠️ Server will disconnect in {time_left}s")
39
+ await websocket.send_json({
40
+ "type": "connection_warning",
41
+ "message": f"Server will disconnect in {time_left} seconds",
42
+ "time_left": time_left
43
+ })
44
+
45
+
46
+ async def handle_server_content(websocket: WebSocket, client_id: str, content: dict):
47
+ """Handle server content from Gemini"""
48
+ # User transcription
49
+ if "inputTranscription" in content:
50
+ text = content["inputTranscription"].get("text", "")
51
+ if text:
52
+ print(f"[DEBUG][{client_id}] 🎀 User: {text[:100]}")
53
+ await websocket.send_json({"type": "user_text", "text": text})
54
+
55
+ # Gemini transcription
56
+ if "outputTranscription" in content:
57
+ text = content["outputTranscription"].get("text", "")
58
+ if text:
59
+ print(f"[DEBUG][{client_id}] πŸ€– Gemini: {text[:100]}")
60
+ await websocket.send_json({"type": "gemini_text", "text": text})
61
+
62
+ # Model turn with audio
63
+ if "modelTurn" in content:
64
+ for part in content["modelTurn"].get("parts", []):
65
+ if "inlineData" in part:
66
+ await websocket.send_json({
67
+ "type": "audio",
68
+ "data": part["inlineData"]["data"],
69
+ "mimeType": part["inlineData"].get("mimeType", "audio/pcm")
70
+ })
71
+ elif "text" in part:
72
+ await websocket.send_json({"type": "gemini_text", "text": part["text"]})
73
+
74
+ # Turn complete
75
+ if content.get("turnComplete"):
76
+ print(f"[DEBUG][{client_id}] βœ… Turn complete")
77
+ await websocket.send_json({"type": "turn_complete"})
78
+
79
+ # Generation complete
80
+ if content.get("generationComplete"):
81
+ print(f"[DEBUG][{client_id}] βœ… Generation complete")
82
+ await websocket.send_json({"type": "generation_complete"})
83
+
84
+ # Interrupted
85
+ if content.get("interrupted"):
86
+ print(f"[DEBUG][{client_id}] ⚠️ Generation interrupted")
87
+ await websocket.send_json({"type": "interrupted"})
88
 
89
 
90
  @router.websocket("/ws/{client_id}")
91
  async def websocket_endpoint(websocket: WebSocket, client_id: str):
92
+ """Main WebSocket endpoint for client communication"""
93
  await websocket.accept()
94
+ print(f"[DEBUG][{client_id}] πŸ“‘ Client connected")
95
 
96
+ gemini = GeminiConnection(client_id)
97
  connections[client_id] = gemini
98
+ reconnect_attempts = 0
 
99
  receive_task = None
100
  send_task = None
101
 
102
  try:
103
+ # Get configuration from client
104
  initial_msg = await websocket.receive_json()
105
  if initial_msg.get("type") != "config":
106
+ raise ValueError("First message must be 'config' type")
107
+
108
+ gemini.set_config(initial_msg.get("config", {}))
109
+ print(f"[DEBUG][{client_id}] βœ… Configuration received")
 
110
 
111
  # Connect to Gemini
112
  await gemini.connect()
113
+ print(f"[DEBUG][{client_id}] βœ… Connected to Gemini")
114
 
115
+ # Main communication loop
116
  while True:
117
+ receive_task = asyncio.create_task(_receive_from_client(websocket, gemini, client_id))
118
+ send_task = asyncio.create_task(_send_to_client(websocket, gemini, client_id))
119
 
120
  done, pending = await asyncio.wait(
121
  [receive_task, send_task],
122
  return_when=asyncio.FIRST_COMPLETED
123
  )
124
 
125
+ # Cancel pending tasks
126
  for task in pending:
127
  task.cancel()
128
 
129
+ # Check if we need to reconnect
130
+ if not await gemini.check_connection():
131
+ if gemini.resumption_handle and reconnect_attempts < 5:
132
+ reconnect_attempts += 1
133
+ print(f"[DEBUG][{client_id}] πŸ”„ Reconnect attempt {reconnect_attempts}")
134
+
135
+ # Close old connection
136
+ await gemini.close()
137
+
138
+ # Create new connection with resumption handle
139
+ new_gemini = GeminiConnection(client_id)
140
+ new_gemini.set_config(gemini.config)
141
+
142
+ try:
143
+ await new_gemini.connect(resumption_handle=gemini.resumption_handle)
144
+ gemini = new_gemini
145
+ connections[client_id] = gemini
146
+ print(f"[DEBUG][{client_id}] βœ… Reconnected successfully")
147
+
148
+ # Notify client
149
+ await websocket.send_json({
150
+ "type": "reconnected",
151
+ "attempts": reconnect_attempts
152
+ })
153
+ continue # Restart loop with new connection
154
+ except Exception as e:
155
+ print(f"[DEBUG][{client_id}] ❌ Reconnect failed: {e}")
156
+ break
157
  else:
158
+ print(f"[DEBUG][{client_id}] πŸ’€ Max reconnects reached or no handle")
159
  break
160
  else:
161
+ break # Exit loop if connection is healthy and tasks completed
162
 
163
  except WebSocketDisconnect:
164
+ print(f"[DEBUG][{client_id}] πŸ”Œ Client disconnected")
165
  except Exception as e:
166
  print(f"[DEBUG][{client_id}] ❌ Error: {e}")
167
  import traceback
168
  traceback.print_exc()
169
  finally:
170
+ # Cleanup
171
  if receive_task and not receive_task.done():
172
  receive_task.cancel()
173
  if send_task and not send_task.done():
174
  send_task.cancel()
175
 
176
  await gemini.close()
177
+ connections.pop(client_id, None)
 
178
  print(f"[DEBUG][{client_id}] 🧹 Cleanup complete")
179
 
180
 
181
+ async def _receive_from_client(websocket: WebSocket, gemini: GeminiConnection, client_id: str):
182
+ """Receive messages from client and forward to Gemini"""
183
  try:
184
  while True:
185
  message = await websocket.receive()
 
187
  if message["type"] == "websocket.disconnect":
188
  return
189
 
190
+ data = json.loads(message["text"])
191
+ msg_type = data.get("type")
192
+
193
  if msg_type == "audio":
194
+ await gemini.send_audio(data["data"])
195
  elif msg_type == "image":
196
+ await gemini.send_image(data["data"])
197
  elif msg_type == "text":
198
+ await gemini.send_text(data["data"])
199
+
 
 
200
  except Exception as e:
201
+ print(f"[DEBUG][{client_id}] Receive error: {e}")
202
 
203
 
204
+ async def _send_to_client(websocket: WebSocket, gemini: GeminiConnection, client_id: str):
205
+ """Receive messages from Gemini and forward to client"""
 
206
  try:
207
  while True:
208
+ message = await gemini.receive()
209
+ if not message:
210
  continue
 
 
 
211
 
212
+ data = json.loads(message)
 
 
213
 
214
+ # Handle different message types
215
+ if "sessionResumptionUpdate" in data:
216
+ await handle_session_resumption(websocket, client_id, gemini, data["sessionResumptionUpdate"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217
 
218
+ elif "goAway" in data:
219
+ await handle_go_away(websocket, client_id, data["goAway"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
 
221
+ elif "serverContent" in data:
222
+ await handle_server_content(websocket, client_id, data["serverContent"])
223
+
 
 
224
  except Exception as e:
225
+ print(f"[DEBUG][{client_id}] Send error: {e}")