-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgemini.py
More file actions
255 lines (208 loc) · 7.69 KB
/
gemini.py
File metadata and controls
255 lines (208 loc) · 7.69 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
"""
Gemini Live API Backend
Implements the DuplexStream interface for Google's Gemini Live API,
enabling real-time bidirectional audio/text communication with
multimodal models.
"""
import os
import asyncio
from typing import AsyncIterator, Optional, Any
from dataclasses import dataclass, field
from .stream import (
DuplexStream, Symbol, StreamEvent, StreamItem,
Modality
)
# Gemini SDK import (deferred to allow module to load without it)
_genai = None
_types = None
def _ensure_genai():
"""Lazy import of google-genai SDK."""
global _genai, _types
if _genai is None:
try:
from google import genai
from google.genai import types
_genai = genai
_types = types
except ImportError:
raise ImportError(
"Gemini backend requires 'google-genai' package. "
"Install with: pip install google-genai"
)
return _genai, _types
@dataclass
class GeminiConfig:
"""Configuration for Gemini Live connection."""
model: str = "gemini-live-2.5-flash-preview"
api_key: Optional[str] = None # Falls back to GOOGLE_API_KEY env var
# Audio settings
input_sample_rate: int = 16000
output_sample_rate: int = 24000
# Response configuration
response_modalities: list = field(default_factory=lambda: ["AUDIO"])
# System instruction
system_instruction: Optional[str] = None
# Generation config
temperature: Optional[float] = None
top_p: Optional[float] = None
top_k: Optional[int] = None
class GeminiStream(DuplexStream):
"""
Full-duplex stream implementation for Gemini Live API.
Wraps the google-genai library's native audio session to provide
a standardized streaming interface. Supports real-time audio
input/output with transcription.
Example:
async with GeminiStream(GeminiConfig()) as stream:
# Send audio
await stream.send(Symbol.audio(audio_bytes))
await stream.send_end()
# Receive response
async for item in stream.receive():
if isinstance(item, Symbol):
play_audio(item.data)
"""
def __init__(self, config: Optional[GeminiConfig] = None):
self.config = config or GeminiConfig()
self._client = None
self._session = None
self._session_context = None
self._connected = False
self._receive_queue: asyncio.Queue[StreamItem] = asyncio.Queue()
self._receive_task: Optional[asyncio.Task] = None
async def connect(self) -> None:
"""Establish connection to Gemini Live API."""
if self._connected:
return
genai, types = _ensure_genai()
# Initialize client
api_key = self.config.api_key or os.environ.get("GOOGLE_API_KEY")
if api_key:
self._client = genai.Client(api_key=api_key)
else:
self._client = genai.Client()
# Build session config
session_config = {
"response_modalities": self.config.response_modalities
}
if self.config.system_instruction:
session_config["system_instruction"] = self.config.system_instruction
# Connect to live session
self._session_context = self._client.aio.live.connect(
model=self.config.model,
config=session_config
)
self._session = await self._session_context.__aenter__()
self._connected = True
# Start background receiver
self._receive_task = asyncio.create_task(self._receive_loop())
async def disconnect(self) -> None:
"""Close the Gemini Live session."""
if not self._connected:
return
# Cancel receiver
if self._receive_task and not self._receive_task.done():
self._receive_task.cancel()
try:
await self._receive_task
except asyncio.CancelledError:
pass
# Close session
if self._session_context:
await self._session_context.__aexit__(None, None, None)
self._session = None
self._session_context = None
self._client = None
self._connected = False
# Signal end to any receivers
await self._receive_queue.put(StreamEvent(type="disconnected"))
async def send(self, symbol: Symbol) -> None:
"""Send a symbol to Gemini."""
if not self._connected:
raise RuntimeError("Stream not connected")
_, types = _ensure_genai()
if symbol.modality == Modality.AUDIO:
await self._session.send_realtime_input(
audio=types.Blob(
data=symbol.data,
mime_type=symbol.mime_type
)
)
elif symbol.modality == Modality.TEXT:
await self._session.send_realtime_input(
text=symbol.text_value
)
else:
raise ValueError(f"Unsupported modality for Gemini: {symbol.modality}")
async def send_end(self) -> None:
"""Signal end of audio input stream."""
if not self._connected:
raise RuntimeError("Stream not connected")
await self._session.send_realtime_input(audio_stream_end=True)
async def _receive_loop(self) -> None:
"""Background task to receive from Gemini and queue items."""
try:
async for msg in self._session.receive():
# Handle text (usually transcription)
if getattr(msg, "text", None):
symbol = Symbol.text(
msg.text,
transcription=True # Mark as transcription
)
await self._receive_queue.put(symbol)
# Handle audio data
if getattr(msg, "data", None):
symbol = Symbol.audio(
msg.data,
sample_rate=self.config.output_sample_rate
)
await self._receive_queue.put(symbol)
# Session ended normally
await self._receive_queue.put(StreamEvent(type="stream_end"))
except asyncio.CancelledError:
raise
except Exception as e:
await self._receive_queue.put(
StreamEvent(type="error", data=str(e))
)
async def receive(self) -> AsyncIterator[StreamItem]:
"""Iterate over received symbols and events."""
while self._connected or not self._receive_queue.empty():
try:
item = await asyncio.wait_for(
self._receive_queue.get(),
timeout=0.1
)
yield item
# Stop on terminal events
if isinstance(item, StreamEvent):
if item.type in ("disconnected", "stream_end"):
break
except asyncio.TimeoutError:
continue
@property
def is_connected(self) -> bool:
"""Check if connected to Gemini."""
return self._connected
async def create_gemini_stream(
model: str = "gemini-live-2.5-flash-preview",
system_instruction: Optional[str] = None,
**kwargs
) -> GeminiStream:
"""
Factory function to create and connect a Gemini stream.
Args:
model: Gemini model ID
system_instruction: Optional system prompt
**kwargs: Additional GeminiConfig parameters
Returns:
Connected GeminiStream instance
"""
config = GeminiConfig(
model=model,
system_instruction=system_instruction,
**kwargs
)
stream = GeminiStream(config)
await stream.connect()
return stream