Spaces:
Running

michdubai commited on
Commit
bd447d5
Β·
verified Β·
1 Parent(s): e8d2795

Update backend/gemini/client.py

Browse files
Files changed (1) hide show
  1. backend/gemini/client.py +55 -40
backend/gemini/client.py CHANGED
@@ -1,6 +1,7 @@
1
  import os
2
  import asyncio
3
- from typing import Dict, Optional, Any
 
4
  from google import genai
5
  from google.genai import types
6
 
@@ -17,13 +18,16 @@ class GeminiConnection:
17
  raise ValueError("GEMINI_API_KEY or GOOGLE_API_KEY not set")
18
 
19
  self.client = genai.Client(api_key=self.api_key)
20
- self.model = "models/gemini-3.1-flash-live-preview"
 
21
  self.session = None
22
  self.config = None
23
  self.resumption_handle = None
24
  self.last_consumed_index = None
25
  self.reconnect_count = 0
26
  self.max_reconnect_attempts = 5
 
 
27
 
28
  def set_config(self, config_data: Dict[str, Any]) -> None:
29
  """Store systemPrompt, voice, etc."""
@@ -31,7 +35,7 @@ class GeminiConnection:
31
 
32
  async def connect(self, resumption_handle: Optional[str] = None) -> bool:
33
  """
34
- Establish connection using official SDK
35
  Returns: True if session was resumed, False if new session
36
  """
37
  if not self.config:
@@ -40,19 +44,18 @@ class GeminiConnection:
40
  try:
41
  print(f"[DEBUG][{self.client_id}] 🌐 Connecting with official SDK...")
42
 
43
- # Build system instruction content
44
- system_instruction = types.Content(
 
 
 
 
 
45
  parts=[types.Part(
46
  text=self.config.get("systemPrompt", "You are a friendly AI Assistant.")
47
  )]
48
  )
49
 
50
- # Build LiveConnectConfig according to official sample
51
- live_config = types.LiveConnectConfig(
52
- response_modalities=["AUDIO"],
53
- system_instruction=system_instruction, # Put system_instruction INSIDE the config
54
- )
55
-
56
  # Add voice if specified
57
  if self.config.get("voice"):
58
  live_config.speech_config = types.SpeechConfig(
@@ -63,26 +66,32 @@ class GeminiConnection:
63
  )
64
  )
65
 
66
- # Add session resumption - Use SessionResumptionConfig (from official sample)
67
  if resumption_handle:
68
- # Reconnecting - provide the handle
69
- live_config.session_resumption = types.SessionResumptionConfig(
70
  handle=resumption_handle
71
  )
72
  print(f"[DEBUG][{self.client_id}] πŸ”„ Using resumption handle: {resumption_handle[:30]}...")
73
  else:
74
- # New session - enable session resumption with empty config
75
- live_config.session_resumption = types.SessionResumptionConfig()
76
  print(f"[DEBUG][{self.client_id}] πŸ†• Creating new session with resumption enabled")
77
 
78
- # Connect using the official SDK (system_instruction is INSIDE the config)
79
- self.session = await self.client.aio.live.connect(
80
  model=self.model,
81
  config=live_config,
82
  )
83
 
 
 
 
84
  print(f"[DEBUG][{self.client_id}] βœ… Connected successfully to {self.model}")
85
 
 
 
 
 
86
  # Check if session was resumed
87
  resumed = resumption_handle is not None
88
  if resumed:
@@ -98,8 +107,17 @@ class GeminiConnection:
98
  traceback.print_exc()
99
  raise ConnectionError(f"Connection failed: {e}")
100
 
 
 
 
 
 
 
 
 
 
101
  async def send_audio(self, data: str) -> None:
102
- """Send audio data to Gemini"""
103
  if not self.session:
104
  print(f"[DEBUG][{self.client_id}] ❌ Cannot send audio: no session")
105
  return
@@ -109,12 +127,11 @@ class GeminiConnection:
109
  print(f"[DEBUG][{self.client_id}] Send audio error: {e}")
110
 
111
  async def send_text(self, text: str) -> None:
112
- """Send text message to Gemini following official sample"""
113
  if not self.session:
114
  print(f"[DEBUG][{self.client_id}] ❌ Cannot send text: no session")
115
  return
116
  try:
117
- # Match official sample format exactly
118
  await self.session.send_client_content(
119
  turns=[text],
120
  turn_complete=True
@@ -146,29 +163,23 @@ class GeminiConnection:
146
  print(f"[DEBUG][{self.client_id}] Send file error: {e}")
147
 
148
  async def receive(self) -> Optional[Dict]:
149
- """Receive next message from Gemini following official sample pattern"""
150
- if not self.session:
151
  return None
152
  try:
153
- async for message in self.session.receive():
154
- # Follow the official sample: check for session_resumption_update
155
- if hasattr(message, 'session_resumption_update') and message.session_resumption_update:
156
- update = message.session_resumption_update
157
- if update.resumable and update.new_handle:
158
- self.resumption_handle = update.new_handle
159
- print(f"[DEBUG][{self.client_id}] πŸ”‘ Session handle stored: {self.resumption_handle[:50]}...")
160
- return self._parse_message(message)
161
-
162
- return self._parse_message(message)
163
  except Exception as e:
164
  print(f"[DEBUG][{self.client_id}] Receive error: {e}")
165
  return None
166
 
167
  def _parse_message(self, message) -> Dict:
168
- """Parse SDK message - following official sample field names"""
169
  result = {}
170
 
171
- # Session resumption update (from official sample)
172
  if hasattr(message, 'session_resumption_update') and message.session_resumption_update:
173
  update = message.session_resumption_update
174
  result["session_resumption_update"] = {
@@ -223,7 +234,7 @@ class GeminiConnection:
223
  part_dict["text"] = part.text
224
  content["model_turn"]["parts"].append(part_dict)
225
 
226
- # Flags from official sample
227
  if hasattr(server_content, 'turn_complete'):
228
  content["turn_complete"] = server_content.turn_complete
229
 
@@ -237,15 +248,19 @@ class GeminiConnection:
237
 
238
  async def check_connection(self) -> bool:
239
  """Check if connection is alive"""
240
- return self.session is not None
241
 
242
  async def close(self) -> None:
243
- """Close the connection"""
244
- if self.session:
 
 
 
245
  try:
246
- await self.session.close()
247
  except Exception as e:
248
  print(f"[DEBUG][{self.client_id}] Close error: {e}")
249
  finally:
 
250
  self.session = None
251
  print(f"[DEBUG][{self.client_id}] 🧹 Connection closed")
 
1
  import os
2
  import asyncio
3
+ from typing import Dict, Optional, Any, AsyncGenerator
4
+ from contextlib import asynccontextmanager
5
  from google import genai
6
  from google.genai import types
7
 
 
18
  raise ValueError("GEMINI_API_KEY or GOOGLE_API_KEY not set")
19
 
20
  self.client = genai.Client(api_key=self.api_key)
21
+ self.model = "models/gemini-2.0-flash-live-preview"
22
+ self._session_context = None
23
  self.session = None
24
  self.config = None
25
  self.resumption_handle = None
26
  self.last_consumed_index = None
27
  self.reconnect_count = 0
28
  self.max_reconnect_attempts = 5
29
+ self._receive_queue = None
30
+ self._receive_task = None
31
 
32
  def set_config(self, config_data: Dict[str, Any]) -> None:
33
  """Store systemPrompt, voice, etc."""
 
35
 
36
  async def connect(self, resumption_handle: Optional[str] = None) -> bool:
37
  """
38
+ Establish connection using official SDK with context manager pattern
39
  Returns: True if session was resumed, False if new session
40
  """
41
  if not self.config:
 
44
  try:
45
  print(f"[DEBUG][{self.client_id}] 🌐 Connecting with official SDK...")
46
 
47
+ # Build LiveConnectConfig according to official docs
48
+ live_config = types.LiveConnectConfig(
49
+ response_modalities=["AUDIO"],
50
+ )
51
+
52
+ # Add system instruction inside the config
53
+ live_config.system_instruction = types.Content(
54
  parts=[types.Part(
55
  text=self.config.get("systemPrompt", "You are a friendly AI Assistant.")
56
  )]
57
  )
58
 
 
 
 
 
 
 
59
  # Add voice if specified
60
  if self.config.get("voice"):
61
  live_config.speech_config = types.SpeechConfig(
 
66
  )
67
  )
68
 
69
+ # Add session resumption - Use SessionResumption (from official docs)
70
  if resumption_handle:
71
+ live_config.session_resumption = types.SessionResumption(
 
72
  handle=resumption_handle
73
  )
74
  print(f"[DEBUG][{self.client_id}] πŸ”„ Using resumption handle: {resumption_handle[:30]}...")
75
  else:
76
+ # New session - enable session resumption
77
+ live_config.session_resumption = types.SessionResumption()
78
  print(f"[DEBUG][{self.client_id}] πŸ†• Creating new session with resumption enabled")
79
 
80
+ # Connect using context manager pattern
81
+ self._session_context = self.client.aio.live.connect(
82
  model=self.model,
83
  config=live_config,
84
  )
85
 
86
+ # Enter the context manager
87
+ self.session = await self._session_context.__aenter__()
88
+
89
  print(f"[DEBUG][{self.client_id}] βœ… Connected successfully to {self.model}")
90
 
91
+ # Start receive task to handle incoming messages
92
+ self._receive_queue = asyncio.Queue()
93
+ self._receive_task = asyncio.create_task(self._receive_loop())
94
+
95
  # Check if session was resumed
96
  resumed = resumption_handle is not None
97
  if resumed:
 
107
  traceback.print_exc()
108
  raise ConnectionError(f"Connection failed: {e}")
109
 
110
+ async def _receive_loop(self):
111
+ """Background task to receive messages from Gemini"""
112
+ try:
113
+ async for message in self.session.receive():
114
+ await self._receive_queue.put(message)
115
+ except Exception as e:
116
+ print(f"[DEBUG][{self.client_id}] Receive loop error: {e}")
117
+ await self._receive_queue.put(None)
118
+
119
  async def send_audio(self, data: str) -> None:
120
+ """Send audio data to Gemini using send_realtime_input"""
121
  if not self.session:
122
  print(f"[DEBUG][{self.client_id}] ❌ Cannot send audio: no session")
123
  return
 
127
  print(f"[DEBUG][{self.client_id}] Send audio error: {e}")
128
 
129
  async def send_text(self, text: str) -> None:
130
+ """Send text message to Gemini using send_client_content"""
131
  if not self.session:
132
  print(f"[DEBUG][{self.client_id}] ❌ Cannot send text: no session")
133
  return
134
  try:
 
135
  await self.session.send_client_content(
136
  turns=[text],
137
  turn_complete=True
 
163
  print(f"[DEBUG][{self.client_id}] Send file error: {e}")
164
 
165
  async def receive(self) -> Optional[Dict]:
166
+ """Receive next message from Gemini"""
167
+ if not self._receive_queue:
168
  return None
169
  try:
170
+ message = await self._receive_queue.get()
171
+ if message is None:
172
+ return None
173
+ return self._parse_message(message)
 
 
 
 
 
 
174
  except Exception as e:
175
  print(f"[DEBUG][{self.client_id}] Receive error: {e}")
176
  return None
177
 
178
  def _parse_message(self, message) -> Dict:
179
+ """Parse SDK message - following official docs field names"""
180
  result = {}
181
 
182
+ # Session resumption update
183
  if hasattr(message, 'session_resumption_update') and message.session_resumption_update:
184
  update = message.session_resumption_update
185
  result["session_resumption_update"] = {
 
234
  part_dict["text"] = part.text
235
  content["model_turn"]["parts"].append(part_dict)
236
 
237
+ # Flags
238
  if hasattr(server_content, 'turn_complete'):
239
  content["turn_complete"] = server_content.turn_complete
240
 
 
248
 
249
  async def check_connection(self) -> bool:
250
  """Check if connection is alive"""
251
+ return self.session is not None and self._receive_task is not None
252
 
253
  async def close(self) -> None:
254
+ """Close the connection by exiting the context manager"""
255
+ if self._receive_task and not self._receive_task.done():
256
+ self._receive_task.cancel()
257
+
258
+ if self._session_context:
259
  try:
260
+ await self._session_context.__aexit__(None, None, None)
261
  except Exception as e:
262
  print(f"[DEBUG][{self.client_id}] Close error: {e}")
263
  finally:
264
+ self._session_context = None
265
  self.session = None
266
  print(f"[DEBUG][{self.client_id}] 🧹 Connection closed")