import io import os import asyncio import base64 import time from typing import Dict, Optional, Any, List, Callable from google import genai from google.genai import types class GeminiConnection: """Clean SDK-based connection to Gemini Live API with full capability support.""" # DEFAULT_MODEL = "models/gemini-2.5-flash-native-audio-latest" DEFAULT_MODEL = "models/gemini-3.1-flash-live-preview" # Supported MIME types for file upload validation SUPPORTED_MIME_TYPES = { "application/pdf", "text/plain", "text/markdown", "text/html", "audio/mpeg", "audio/mp3", "audio/wav", "audio/ogg", "audio/flac", "video/mp4", "video/mpeg", "video/webm", "video/quicktime", "image/jpeg", "image/png", "image/webp", "image/gif", } def __init__(self, client_id: str = "unknown", model: Optional[str] = None): self.client_id = client_id api_key = os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY") if not api_key: raise ValueError("API key not set") self.client = genai.Client(api_key=api_key) self.model = model or self.DEFAULT_MODEL self._context = None self.session = None self.config = None self.resumption_handle = None self._receive_queue: Optional[asyncio.Queue] = None self._receive_task: Optional[asyncio.Task] = None self._closed = False self._tool_registry: Dict[str, Callable] = {} self._send_fail_count = 0 self._last_send_error_time = 0.0 def set_config(self, config_data: Dict[str, Any]) -> None: self.config = config_data def register_tool(self, name: str, handler: Callable) -> None: self._tool_registry[name] = handler def _build_live_config(self, resumption_handle: Optional[str] = None) -> types.LiveConnectConfig: if not self.config: raise ValueError("Configuration required") config = types.LiveConnectConfig( response_modalities=[types.Modality.AUDIO, types.Modality.TEXT], system_instruction=types.Content( parts=[types.Part(text=self.config.get("systemPrompt", "You are a helpful assistant."))] ), ) # Session resumption if resumption_handle: config.session_resumption = types.SessionResumptionConfig(handle=resumption_handle) else: config.session_resumption = types.SessionResumptionConfig() # Voice — default to Puck if not specified so audio output is always enabled voice = self.config.get("voice") or "Puck" config.speech_config = types.SpeechConfig( voice_config=types.VoiceConfig( prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name=voice) ) ) # Response modalities override modalities = self.config.get("responseModalities") if modalities: config.response_modalities = [ types.Modality[m] if isinstance(m, str) and m in types.Modality.__members__ else m for m in modalities ] # Context window compression — essential for sessions longer than 15 min (audio) or 2 min (audio+video) config.context_window_compression = types.ContextWindowCompressionConfig( sliding_window=types.SlidingWindow() ) # Audio transcriptions — enable real-time transcription of both user input and Gemini output config.input_audio_transcription = types.AudioTranscriptionConfig() config.output_audio_transcription = types.AudioTranscriptionConfig() # Tools / Function calling tools_config = self.config.get("tools") if tools_config: tools: List[types.Tool] = [] for tool_def in tools_config: if isinstance(tool_def, dict): if "function_declarations" in tool_def: func_decls = [] for fd in tool_def["function_declarations"]: func_decls.append( types.FunctionDeclaration( name=fd.get("name"), description=fd.get("description", ""), parameters=fd.get("parameters") or {}, ) ) tools.append(types.Tool(function_declarations=func_decls)) elif "name" in tool_def: # Single function declaration shorthand tools.append( types.Tool( function_declarations=[ types.FunctionDeclaration( name=tool_def.get("name"), description=tool_def.get("description", ""), parameters=tool_def.get("parameters") or {}, ) ] ) ) elif isinstance(tool_def, types.Tool): tools.append(tool_def) if tools: config.tools = tools return config async def connect(self, resumption_handle: Optional[str] = None) -> bool: """Establish connection using official SDK""" if self._closed: raise RuntimeError("Connection has been permanently closed") # Prevent duplicate receive loops if connect is called without a prior close if self._receive_task and not self._receive_task.done(): print(f"[DEBUG][{self.client_id}] ⚠️ Already connected, skipping redundant connect") return resumption_handle is not None config = self._build_live_config(resumption_handle) print( f"[DEBUG][{self.client_id}] 🔗 Connecting model={self.model} " f"resumption={resumption_handle is not None}" ) self._context = self.client.aio.live.connect(model=self.model, config=config) self.session = await self._context.__aenter__() print(f"[DEBUG][{self.client_id}] ✅ Connected") self._receive_queue = asyncio.Queue() self._receive_task = asyncio.create_task(self._receive_loop()) return resumption_handle is not None async def _receive_loop(self): """Background task to receive messages - parsed instantly to prevent keepalive drops""" try: # session.receive() yields one complete turn and then breaks; # wrap it in while True so we keep processing subsequent turns. while True: async for msg in self.session.receive(): # Parse right away to clear the low-level buffer and minimize serialization weight in the queue parsed = self._parse_message(msg) if parsed and self._receive_queue: await self._receive_queue.put(parsed) except asyncio.CancelledError: print(f"[DEBUG][{self.client_id}] Receive loop cancelled") except Exception as e: if "closed" not in str(e).lower(): print(f"[DEBUG][{self.client_id}] Receive loop ended: {e}") finally: # Always signal queue consumers so send_to_client can exit cleanly queue = self._receive_queue if queue: try: await queue.put(None) except Exception: pass async def _handle_tool_call(self, tool_call): """Execute registered tools and send responses back""" try: func_responses = [] for call in tool_call.function_calls: name = call.name args = dict(call.args) if hasattr(call.args, "items") else (call.args or {}) print(f"[DEBUG][{self.client_id}] 🔧 Tool call: {name}({args})") result = {"error": f"Tool '{name}' not found"} if name in self._tool_registry: try: handler = self._tool_registry[name] if asyncio.iscoroutinefunction(handler): result = await handler(**args) else: result = handler(**args) except Exception as te: result = {"error": str(te)} print(f"[DEBUG][{self.client_id}] Tool error: {te}") func_responses.append( types.FunctionResponse(name=name, response=result) ) await self.session.send_tool_response(function_responses=func_responses) print(f"[DEBUG][{self.client_id}] 📤 Tool responses sent") except Exception as e: print(f"[DEBUG][{self.client_id}] Tool handling error: {e}") async def send_audio(self, data: str) -> None: """Send audio data with correct sampling rate""" if not self.session or self._closed: return try: audio_bytes = base64.b64decode(data) if isinstance(data, str) else data await self.session.send_realtime_input( audio=types.Blob( data=audio_bytes, mime_type="audio/pcm;rate=16000", ) ) except Exception as e: if "closed" not in str(e).lower(): self._send_fail_count += 1 now = time.time() if now - self._last_send_error_time > 5: print(f"[DEBUG][{self.client_id}] Send audio error: {e}") self._last_send_error_time = now if self._send_fail_count >= 5: print(f"[DEBUG][{self.client_id}] 🔌 Too many send failures, closing connection") await self.close() async def send_text(self, text: str) -> None: """Send text message via realtime input (best practice for live sessions)""" if not self.session or self._closed: return try: await self.session.send_realtime_input(text=text) except Exception as e: if "closed" not in str(e).lower(): self._send_fail_count += 1 now = time.time() if now - self._last_send_error_time > 5: print(f"[DEBUG][{self.client_id}] Send text error: {e}") self._last_send_error_time = now if self._send_fail_count >= 5: print(f"[DEBUG][{self.client_id}] 🔌 Too many send failures, closing connection") await self.close() async def send_image(self, data: str) -> None: """Send image data frame""" if not self.session or self._closed: return try: image_bytes = base64.b64decode(data) if isinstance(data, str) else data await self.session.send_realtime_input( video=types.Blob(data=image_bytes, mime_type="image/jpeg") ) except Exception as e: if "closed" not in str(e).lower(): self._send_fail_count += 1 now = time.time() if now - self._last_send_error_time > 5: print(f"[DEBUG][{self.client_id}] Send image error: {e}") self._last_send_error_time = now if self._send_fail_count >= 5: print(f"[DEBUG][{self.client_id}] 🔌 Too many send failures, closing connection") await self.close() async def send_file(self, file_uri: str, mime_type: str) -> None: """Send file reference into the active session""" if not self.session or self._closed: return try: await self.session.send_client_content( turns=[ types.Content( role="user", parts=[ types.Part( file_data=types.FileData(file_uri=file_uri, mime_type=mime_type) ) ], ) ], turn_complete=True, ) except Exception as e: if "closed" not in str(e).lower(): self._send_fail_count += 1 now = time.time() if now - self._last_send_error_time > 5: print(f"[DEBUG][{self.client_id}] Send file error: {e}") self._last_send_error_time = now if self._send_fail_count >= 5: print(f"[DEBUG][{self.client_id}] 🔌 Too many send failures, closing connection") await self.close() # Gracefully swallow to keep session alive; caller notified via error packet async def upload_file(self, file_bytes: bytes, mime_type: str) -> Dict[str, str]: """Upload file to Gemini Files API and return URI + mime_type""" try: print(f"[DEBUG][{self.client_id}] 📤 Uploading file ({len(file_bytes)} bytes, {mime_type})") file_obj = await self.client.aio.files.upload( file=io.BytesIO(file_bytes), config={"mime_type": mime_type}, ) print(f"[DEBUG][{self.client_id}] ✅ File uploaded: {file_obj.uri}") return {"uri": file_obj.uri, "mime_type": file_obj.mime_type or mime_type} except Exception as e: print(f"[DEBUG][{self.client_id}] ❌ File upload error: {e}") raise async def receive(self) -> Optional[Dict]: """Get pre-parsed message from the queue""" if not self._receive_queue: return None try: msg = await self._receive_queue.get() return msg except Exception: return None def _parse_message(self, msg) -> Optional[Dict]: """Convert SDK message to flat structure expected by frontend""" # GoAway notification if hasattr(msg, "go_away") and msg.go_away: time_left = msg.go_away.time_left # Convert protobuf Duration / timedelta to seconds for JSON serialization if hasattr(time_left, "total_seconds"): time_left = time_left.total_seconds() elif hasattr(time_left, "seconds"): time_left = time_left.seconds + getattr(time_left, "nanos", 0) / 1e9 return {"type": "go_away", "time_left": time_left} # Session resumption update if hasattr(msg, "session_resumption_update") and msg.session_resumption_update: update = msg.session_resumption_update return { "type": "session_resumption", "new_handle": getattr(update, "new_handle", None), "resumable": getattr(update, "resumable", False), } # Tool call if hasattr(msg, "tool_call") and msg.tool_call: calls = [] for call in msg.tool_call.function_calls: calls.append( { "id": getattr(call, "id", None), "name": call.name, "args": dict(call.args) if hasattr(call.args, "items") else (call.args or {}), } ) return {"type": "tool_call", "calls": calls} # Server content if hasattr(msg, "server_content") and msg.server_content: sc = msg.server_content result: Dict[str, Any] = {"type": "server_content"} # Include state flags rather than returning early so we don't drop # audio/text that arrives in the same message (common in 3.1). if getattr(sc, "interrupted", False): result["interrupted"] = True if getattr(sc, "turn_complete", False): result["turn_complete"] = True if getattr(sc, "generation_complete", False): result["generation_complete"] = True if hasattr(sc, "input_transcription") and sc.input_transcription: result["user_text"] = sc.input_transcription.text if hasattr(sc, "output_transcription") and sc.output_transcription: result["gemini_text"] = sc.output_transcription.text if hasattr(sc, "model_turn") and sc.model_turn: audio_chunks: list = [] mime_type = None for part in sc.model_turn.parts: if hasattr(part, "inline_data") and part.inline_data: audio_chunks.append(part.inline_data.data) mime_type = part.inline_data.mime_type elif hasattr(part, "text") and part.text: result["gemini_text"] = (result.get("gemini_text") or "") + part.text if audio_chunks: result["audio"] = base64.b64encode(b"".join(audio_chunks)).decode("utf-8") result["mime_type"] = mime_type return result return None async def check_connection(self) -> bool: return ( self.session is not None and self._receive_task is not None and not self._receive_task.done() and not self._closed ) async def close(self) -> None: """Close the connection properly""" self._closed = True # Signal queue consumers first so send_to_client wakes up and returns if self._receive_queue: try: await self._receive_queue.put(None) except Exception: pass if self._receive_task and not self._receive_task.done(): self._receive_task.cancel() try: await self._receive_task except asyncio.CancelledError: pass if self._context: try: await self._context.__aexit__(None, None, None) except Exception: pass finally: self._context = None self.session = None self._receive_queue = None print(f"[DEBUG][{self.client_id}] 🧹 Connection closed")