edgevoiceai 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. edgevoiceai/__init__.py +105 -0
  2. edgevoiceai/agent.py +454 -0
  3. edgevoiceai/audio/__init__.py +20 -0
  4. edgevoiceai/audio/device.py +243 -0
  5. edgevoiceai/audio/media.py +122 -0
  6. edgevoiceai/audio/player.py +128 -0
  7. edgevoiceai/audio/stream.py +155 -0
  8. edgevoiceai/audio/vad.py +117 -0
  9. edgevoiceai/config.py +61 -0
  10. edgevoiceai/docs.py +110 -0
  11. edgevoiceai/guardrails/__init__.py +11 -0
  12. edgevoiceai/guardrails/farewell.py +106 -0
  13. edgevoiceai/guardrails/topic_guard.py +63 -0
  14. edgevoiceai/memory/__init__.py +19 -0
  15. edgevoiceai/memory/extractor.py +159 -0
  16. edgevoiceai/memory/message.py +59 -0
  17. edgevoiceai/memory/stores/__init__.py +13 -0
  18. edgevoiceai/memory/stores/base.py +89 -0
  19. edgevoiceai/memory/stores/memory.py +68 -0
  20. edgevoiceai/memory/stores/sqlite.py +213 -0
  21. edgevoiceai/notifications/__init__.py +15 -0
  22. edgevoiceai/notifications/whatsapp.py +460 -0
  23. edgevoiceai/protocol/__init__.py +15 -0
  24. edgevoiceai/protocol/gemini.py +162 -0
  25. edgevoiceai/rag/__init__.py +24 -0
  26. edgevoiceai/rag/chunk.py +48 -0
  27. edgevoiceai/rag/embeddings/__init__.py +11 -0
  28. edgevoiceai/rag/embeddings/base.py +35 -0
  29. edgevoiceai/rag/embeddings/gemini.py +186 -0
  30. edgevoiceai/rag/retriever.py +138 -0
  31. edgevoiceai/rag/stores/__init__.py +15 -0
  32. edgevoiceai/rag/stores/base.py +71 -0
  33. edgevoiceai/rag/stores/memory.py +209 -0
  34. edgevoiceai/rag/stores/pinecone.py +236 -0
  35. edgevoiceai/rag/stores/qdrant.py +261 -0
  36. edgevoiceai/tests/__init__.py +0 -0
  37. edgevoiceai/tests/test_core.py +196 -0
  38. edgevoiceai/tests/test_memory.py +199 -0
  39. edgevoiceai/tests/test_rag.py +206 -0
  40. edgevoiceai/tests/test_tools.py +194 -0
  41. edgevoiceai/tests/test_whatsapp.py +247 -0
  42. edgevoiceai/tools/__init__.py +18 -0
  43. edgevoiceai/tools/audio_tool.py +130 -0
  44. edgevoiceai/tools/base.py +110 -0
  45. edgevoiceai/tools/notification_tool.py +177 -0
  46. edgevoiceai/tools/rag_tool.py +167 -0
  47. edgevoiceai/tools/registry.py +109 -0
  48. edgevoiceai/tools/sensor_tool.py +89 -0
  49. edgevoiceai-0.1.1.dist-info/METADATA +271 -0
  50. edgevoiceai-0.1.1.dist-info/RECORD +53 -0
  51. edgevoiceai-0.1.1.dist-info/WHEEL +5 -0
  52. edgevoiceai-0.1.1.dist-info/licenses/LICENSE +22 -0
  53. edgevoiceai-0.1.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,105 @@
1
+ """
2
+ Voice AI Framework.
3
+ A modular, full-duplex conversational voice framework for edge devices and servers.
4
+ Supports Raspberry Pi, Linux, macOS, and Windows on Python 3.10+.
5
+ """
6
+
7
+ from edgevoiceai.agent import VoiceAgent
8
+ from edgevoiceai.audio.device import AudioDeviceManager, AudioDeviceInfo
9
+ from edgevoiceai.audio.media import MediaAudioPlayer
10
+ from edgevoiceai.audio.player import AudioPlayer
11
+ from edgevoiceai.audio.stream import MicrophoneStream
12
+ from edgevoiceai.audio.vad import VADConfig, VoiceActivityDetector, compute_rms
13
+ from edgevoiceai.config import VoiceConfig
14
+ from edgevoiceai.guardrails.farewell import FarewellDetector
15
+ from edgevoiceai.guardrails.topic_guard import TopicGuard
16
+ from edgevoiceai.memory.extractor import EntityExtractor
17
+ from edgevoiceai.memory.message import ChatMessage, ConversationSession
18
+ from edgevoiceai.memory.stores.base import BaseMemoryStore
19
+ from edgevoiceai.memory.stores.memory import InMemoryMemoryStore
20
+ from edgevoiceai.memory.stores.sqlite import SQLiteMemoryStore
21
+ from edgevoiceai.notifications.whatsapp import (
22
+ WhatsAppClient,
23
+ WhatsAppConfig,
24
+ WhatsAppNotificationTool,
25
+ )
26
+ from edgevoiceai.protocol.gemini import GeminiLiveProtocol, ParsedServerMessage
27
+ from edgevoiceai.rag.chunk import DocumentChunk
28
+ from edgevoiceai.rag.embeddings.base import BaseEmbeddingModel
29
+ from edgevoiceai.rag.embeddings.gemini import GeminiEmbeddings
30
+ from edgevoiceai.rag.retriever import RAGRetriever
31
+ from edgevoiceai.rag.stores.base import BaseVectorStore
32
+ from edgevoiceai.rag.stores.memory import InMemoryVectorStore
33
+ from edgevoiceai.rag.stores.pinecone import PineconeVectorStore
34
+ from edgevoiceai.rag.stores.qdrant import QdrantVectorStore
35
+ from edgevoiceai.tools.audio_tool import AudioPlaybackTool
36
+ from edgevoiceai.tools.base import BaseTool, ToolExecutionContext, ToolResult
37
+ from edgevoiceai.tools.notification_tool import (
38
+ TwoTurnConfirmationNotificationTool,
39
+ default_normalize_phone,
40
+ )
41
+ from edgevoiceai.docs import get_site_directory, mount_docs, serve_docs
42
+ from edgevoiceai.tools.rag_tool import KnowledgeBaseTool
43
+ from edgevoiceai.tools.registry import ToolRegistry
44
+ from edgevoiceai.tools.sensor_tool import SensorTelemetryTool
45
+
46
+ __version__ = "0.1.1"
47
+
48
+
49
+ __all__ = [
50
+ # Core Agent & Config
51
+ "VoiceAgent",
52
+ "VoiceConfig",
53
+ # Documentation & Mounting
54
+ "mount_docs",
55
+ "serve_docs",
56
+ "get_site_directory",
57
+ # Tools System
58
+ "BaseTool",
59
+ "ToolRegistry",
60
+ "ToolResult",
61
+ "ToolExecutionContext",
62
+ "KnowledgeBaseTool",
63
+ "AudioPlaybackTool",
64
+ "SensorTelemetryTool",
65
+ "TwoTurnConfirmationNotificationTool",
66
+ "default_normalize_phone",
67
+ # Notifications & WhatsApp
68
+ "WhatsAppConfig",
69
+ "WhatsAppClient",
70
+ "WhatsAppNotificationTool",
71
+
72
+ # Audio Subsystem
73
+ "AudioDeviceManager",
74
+ "AudioDeviceInfo",
75
+ "AudioPlayer",
76
+ "MediaAudioPlayer",
77
+ "MicrophoneStream",
78
+ "VoiceActivityDetector",
79
+ "VADConfig",
80
+ "compute_rms",
81
+ # Guardrails
82
+ "TopicGuard",
83
+ "FarewellDetector",
84
+ # Memory & Context
85
+ "ChatMessage",
86
+ "ConversationSession",
87
+ "BaseMemoryStore",
88
+ "InMemoryMemoryStore",
89
+ "SQLiteMemoryStore",
90
+ "EntityExtractor",
91
+ # Protocol
92
+ "GeminiLiveProtocol",
93
+ "ParsedServerMessage",
94
+ # RAG & Vector Stores
95
+ "DocumentChunk",
96
+ "BaseEmbeddingModel",
97
+ "GeminiEmbeddings",
98
+ "BaseVectorStore",
99
+ "InMemoryVectorStore",
100
+ "QdrantVectorStore",
101
+ "PineconeVectorStore",
102
+ "RAGRetriever",
103
+ ]
104
+
105
+
edgevoiceai/agent.py ADDED
@@ -0,0 +1,454 @@
1
+ """
2
+ High-Level VoiceAgent Orchestrator.
3
+ Coordinates audio I/O, Gemini Live bidirectional WebSocket streaming,
4
+ voice activity detection, tool dispatch, and barge-in interruptions.
5
+ Runs across Raspberry Pi, Linux, macOS, and Windows.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import json
12
+ import time
13
+ from typing import Any, Callable
14
+
15
+ try:
16
+ import websockets
17
+ except ImportError:
18
+ websockets = None # type: ignore[assignment]
19
+
20
+ try:
21
+ import pyaudio # type: ignore[import-untyped]
22
+ PYAUDIO_AVAILABLE = True
23
+ except ImportError:
24
+ pyaudio = None # type: ignore[assignment]
25
+ PYAUDIO_AVAILABLE = False
26
+
27
+ from edgevoiceai.audio.device import AudioDeviceManager
28
+ from edgevoiceai.audio.media import MediaAudioPlayer
29
+ from edgevoiceai.audio.player import AudioPlayer
30
+ from edgevoiceai.audio.stream import MicrophoneStream
31
+ from edgevoiceai.audio.vad import VADConfig, VoiceActivityDetector, compute_rms
32
+ from edgevoiceai.config import VoiceConfig
33
+ from edgevoiceai.guardrails.farewell import FarewellDetector
34
+ from edgevoiceai.guardrails.topic_guard import TopicGuard
35
+ from edgevoiceai.memory.extractor import EntityExtractor
36
+ from edgevoiceai.memory.stores.base import BaseMemoryStore
37
+ from edgevoiceai.notifications.whatsapp import WhatsAppNotificationTool
38
+ from edgevoiceai.protocol.gemini import GeminiLiveProtocol
39
+ from edgevoiceai.tools.base import BaseTool, ToolExecutionContext
40
+ from edgevoiceai.tools.registry import ToolRegistry
41
+
42
+
43
+ class VoiceAgent:
44
+ """
45
+ Full-duplex real-time Conversational Voice AI Agent.
46
+ """
47
+
48
+ def __init__(
49
+ self,
50
+ config: VoiceConfig,
51
+ tools: ToolRegistry | None = None,
52
+ topic_guard: TopicGuard | None = None,
53
+ farewell_detector: FarewellDetector | None = None,
54
+ memory: BaseMemoryStore | None = None,
55
+ entity_extractor: EntityExtractor | None = None,
56
+ ) -> None:
57
+ self.config = config
58
+ self.tools = tools or ToolRegistry()
59
+ self.topic_guard = topic_guard
60
+ self.farewell_detector = farewell_detector or FarewellDetector()
61
+ self.memory = memory
62
+ self.entity_extractor = entity_extractor
63
+
64
+ # Auto-register WhatsApp notification tool if configured
65
+ if self.config.whatsapp is not None:
66
+ wa_tool = WhatsAppNotificationTool(config=self.config.whatsapp)
67
+ if not self.tools.has_tool(wa_tool.name):
68
+ self.tools.register(wa_tool)
69
+
70
+ # Optional event callbacks
71
+ self.on_user_speech_start: Callable[[], None] | None = None
72
+ self.on_ai_speech_start: Callable[[], None] | None = None
73
+ self.on_turn_complete: Callable[[str], None] | None = None
74
+ self.on_interrupted: Callable[[], None] | None = None
75
+ self.on_tool_executed: Callable[[str, dict[str, Any], Any], None] | None = None
76
+
77
+ self._shutdown_event = asyncio.Event()
78
+
79
+
80
+
81
+ def register_tool(self, tool: BaseTool) -> VoiceAgent:
82
+ """Fluent interface to register a tool with the agent."""
83
+ self.tools.register(tool)
84
+ return self
85
+
86
+ def stop(self) -> None:
87
+ """Signals the agent to stop its running loop."""
88
+ self._shutdown_event.set()
89
+
90
+ async def run_edge(self, session_id: str = "default") -> None:
91
+ """
92
+ Runs the full always-listening voice loop on edge hardware
93
+ (Raspberry Pi, Mac, Windows, Linux laptop).
94
+ """
95
+ if websockets is None:
96
+ raise RuntimeError("websockets is required. Install with: pip install websockets")
97
+
98
+ # 1. Resolve Audio Hardware Devices
99
+ in_dev = AudioDeviceManager.find_device_index(self.config.input_device, is_input=True)
100
+ out_dev = AudioDeviceManager.find_device_index(self.config.output_device, is_input=False)
101
+
102
+ print("\n" + "=" * 60)
103
+ print("🎙️ [VOICE AGENT INITIALIZED]")
104
+ print("=" * 60)
105
+ print(f" Model : {self.config.model}")
106
+ print(f" Voice : {self.config.voice}")
107
+ print(f" Mic Device : {'Default' if in_dev is None else f'Index {in_dev}'}")
108
+ print(f" Speaker Device : {'Default' if out_dev is None else f'Index {out_dev}'}")
109
+ print(f" Interrupt Thresh : {self.config.interrupt_rms_threshold}")
110
+ print(f" Noise Gate Thresh: {self.config.noise_gate_threshold}")
111
+ print("=" * 60 + "\n")
112
+
113
+ # 2. Audio Pipeline Setup
114
+ vad_config = VADConfig(
115
+ interrupt_rms_threshold=self.config.interrupt_rms_threshold,
116
+ ai_interrupt_threshold=self.config.ai_interrupt_threshold,
117
+ noise_gate_threshold=self.config.noise_gate_threshold,
118
+ hang_frames=self.config.hang_frames,
119
+ streak_trigger=self.config.vad_streak_trigger,
120
+ pre_buffer_max_frames=self.config.pre_buffer_max_frames,
121
+ )
122
+ vad = VoiceActivityDetector(vad_config)
123
+
124
+ # Share a single PyAudio instance across mic and speaker
125
+ pa: Any = None
126
+ if PYAUDIO_AVAILABLE and pyaudio is not None:
127
+ try:
128
+ pa = pyaudio.PyAudio()
129
+ except Exception as pa_err:
130
+ print(f"⚠️ [PyAudio Init Warning]: {pa_err}")
131
+
132
+ mic_stream = MicrophoneStream(
133
+ pa=pa,
134
+ device_index=in_dev,
135
+ capture_rate=self.config.mic_capture_rate,
136
+ target_rate=self.config.gemini_input_rate,
137
+ )
138
+
139
+ player = AudioPlayer(
140
+ pa=pa,
141
+ device_index=out_dev,
142
+ sample_rate=self.config.speaker_sample_rate,
143
+ )
144
+
145
+ media_player = MediaAudioPlayer(media_dir=self.config.media_directory)
146
+
147
+ ws_url = GeminiLiveProtocol.get_ws_url(
148
+ self.config.api_key,
149
+ base_url=self.config.ws_base_url or "wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",
150
+ )
151
+
152
+ is_reconnect = False
153
+
154
+ try:
155
+ while not self._shutdown_event.is_set():
156
+ try:
157
+ print(f"🔗 Connecting to Gemini Live ({self.config.model})...")
158
+ async with websockets.connect(
159
+ ws_url,
160
+ open_timeout=self.config.open_timeout,
161
+ close_timeout=self.config.close_timeout,
162
+ ping_interval=self.config.ping_interval,
163
+ max_size=None,
164
+ ) as gemini_ws:
165
+ # Build dynamic system instruction (base prompt + user memory + tool rules)
166
+ sys_instruction = await self.build_effective_system_instruction(session_id=session_id)
167
+
168
+ # Send handshake setup message
169
+ tools_schema = self.tools.to_gemini_tools_payload()
170
+ setup_payload = GeminiLiveProtocol.build_setup_message(
171
+ model=self.config.model,
172
+ system_instruction=sys_instruction,
173
+ voice_name=self.config.voice,
174
+ tools_declarations=tools_schema,
175
+ is_reconnect=is_reconnect,
176
+ )
177
+ await gemini_ws.send(json.dumps(setup_payload))
178
+
179
+ # Await setup confirmation
180
+ raw_setup = await asyncio.wait_for(gemini_ws.recv(), timeout=15.0)
181
+ setup_str = raw_setup.decode("utf-8") if isinstance(raw_setup, (bytes, bytearray)) else str(raw_setup)
182
+ setup_data = json.loads(setup_str)
183
+ if "setupComplete" in setup_data:
184
+ print("✅ [Gemini Live Connected & Ready!]")
185
+ else:
186
+ print(f"⚠️ [Unexpected Setup Response]: {setup_str[:200]}")
187
+
188
+ # Drain any mic frames buffered during connection
189
+ while not mic_stream.queue.empty():
190
+ try:
191
+ mic_stream.queue.get_nowait()
192
+ except Exception:
193
+ break
194
+
195
+ # Proactive greeting: trigger so the assistant speaks immediately on startup
196
+ if not is_reconnect and self.config.greeting_message:
197
+ greet_payload = {
198
+ "clientContent": {
199
+ "turns": [{"role": "user", "parts": [{"text": self.config.greeting_message}]}],
200
+ "turnComplete": True,
201
+ }
202
+ }
203
+ await gemini_ws.send(json.dumps(greet_payload))
204
+ print("🎙️ [Greeting Triggered] — Assistant is introducing itself.")
205
+
206
+ # Session state
207
+ ai_is_speaking = False
208
+ tool_is_executing = False
209
+ interrupted_at = 0.0
210
+ user_has_spoken = not is_reconnect
211
+ session_turn = 0
212
+ user_speaking_logged = False
213
+
214
+ # ── Task A: Mic -> Gemini ──────────────────────────────
215
+ async def mic_to_gemini() -> None:
216
+ nonlocal ai_is_speaking, interrupted_at, user_has_spoken, user_speaking_logged
217
+ while not self._shutdown_event.is_set():
218
+ pcm = mic_stream.get_chunk(block=False)
219
+ if pcm is None:
220
+ await asyncio.sleep(0.005)
221
+ continue
222
+
223
+ if tool_is_executing:
224
+ continue
225
+
226
+ rms = compute_rms(pcm)
227
+
228
+ # Check barge-in on media audio file
229
+ if media_player.is_playing():
230
+ if vad.check_barge_in(pcm, self.config.interrupt_rms_threshold):
231
+ print(f"\n⚡ [Interruption detected (RMS {int(rms)}) -> Stopping audio file]")
232
+ media_player.stop()
233
+ if self.on_interrupted:
234
+ self.on_interrupted()
235
+ continue
236
+
237
+ # Check barge-in on AI speech
238
+ if ai_is_speaking or player.is_playing():
239
+ if vad.check_barge_in(pcm, self.config.ai_interrupt_threshold):
240
+ print(f"\n⚡ [AI Interrupted (RMS {int(rms)}) -> Clearing speaker]")
241
+ player.clear()
242
+ media_player.stop()
243
+ ai_is_speaking = False
244
+ interrupted_at = time.time()
245
+ user_has_spoken = True
246
+ if self.on_interrupted:
247
+ self.on_interrupted()
248
+ else:
249
+ continue
250
+
251
+ # Noise gate and speech streaming
252
+ should_stream, frames = vad.process_chunk(pcm)
253
+ if should_stream:
254
+ if not user_speaking_logged and vad.gate_open:
255
+ print(f"\n🎤 [Voice detected: RMS {int(rms)}]", flush=True)
256
+ user_speaking_logged = True
257
+ user_has_spoken = True
258
+ for frame in frames:
259
+ try:
260
+ payload = GeminiLiveProtocol.encode_audio_chunk(frame)
261
+ await gemini_ws.send(payload)
262
+ except Exception:
263
+ break
264
+ else:
265
+ user_speaking_logged = False
266
+
267
+ # ── Task B: Gemini -> Speaker + Tools ──────────────────
268
+ async def gemini_to_speaker() -> None:
269
+ nonlocal ai_is_speaking, tool_is_executing, interrupted_at, session_turn
270
+ ai_text_parts: list[str] = []
271
+ pending_audio_url: str | None = None
272
+
273
+ async for raw_msg in gemini_ws:
274
+ if self._shutdown_event.is_set():
275
+ break
276
+
277
+ msg_str = raw_msg.decode("utf-8") if isinstance(raw_msg, (bytes, bytearray)) else str(raw_msg)
278
+ parsed = GeminiLiveProtocol.parse_message(msg_str)
279
+ if parsed.error:
280
+ print(f"⚠️ [Gemini Error]: {parsed.error}")
281
+ continue
282
+
283
+ if parsed.interrupted:
284
+ player.clear()
285
+ ai_is_speaking = False
286
+ interrupted_at = time.time()
287
+ ai_text_parts.clear()
288
+ continue
289
+
290
+ # Handle tool calls
291
+ if parsed.tool_calls:
292
+ tool_is_executing = True
293
+ try:
294
+ ctx = ToolExecutionContext(
295
+ session_id=session_id,
296
+ current_turn=session_turn,
297
+ )
298
+ fn_responses: list[dict[str, Any]] = []
299
+ for tc in parsed.tool_calls:
300
+ fn_name = tc.get("name", "")
301
+ fn_args = tc.get("args", {})
302
+ call_id = tc.get("id", "")
303
+
304
+ tool_res = await self.tools.dispatch(fn_name, fn_args, ctx)
305
+ if tool_res.queued_audio_url:
306
+ pending_audio_url = tool_res.queued_audio_url
307
+
308
+ fn_responses.append({
309
+ "response": {
310
+ "name": fn_name,
311
+ "content": tool_res.to_gemini_response_content(),
312
+ },
313
+ "id": call_id,
314
+ })
315
+ if self.on_tool_executed:
316
+ self.on_tool_executed(fn_name, fn_args, tool_res)
317
+
318
+ if fn_responses:
319
+ tool_payload = GeminiLiveProtocol.encode_tool_responses(fn_responses)
320
+ await gemini_ws.send(tool_payload)
321
+ finally:
322
+ tool_is_executing = False
323
+
324
+ # Process audio output
325
+ if parsed.audio_pcm_chunks:
326
+ if interrupted_at > 0.0 and (time.time() - interrupted_at) < 0.8:
327
+ continue
328
+ if is_reconnect and not user_has_spoken:
329
+ continue
330
+
331
+ ai_is_speaking = True
332
+ for chunk in parsed.audio_pcm_chunks:
333
+ player.feed(chunk)
334
+
335
+ if parsed.text_parts:
336
+ ai_text_parts.extend(parsed.text_parts)
337
+
338
+ if parsed.turn_complete:
339
+ ai_is_speaking = False
340
+ interrupted_at = 0.0
341
+ full_text = "".join(ai_text_parts).strip()
342
+ ai_text_parts.clear()
343
+ session_turn += 1
344
+
345
+ # Notify turn complete immediately
346
+ if self.on_turn_complete and full_text:
347
+ self.on_turn_complete(full_text)
348
+
349
+ # Record turn in memory and schedule entity extraction in background
350
+ if self.memory and full_text:
351
+ await self.memory.add_message(
352
+ session_id, role="assistant", content=full_text
353
+ )
354
+ if self.entity_extractor:
355
+ asyncio.create_task(
356
+ self.entity_extractor.extract_and_update(
357
+ session_id, self.memory
358
+ )
359
+ )
360
+
361
+ # Only wait for speaker if an external pre-recorded audio file is queued
362
+ if pending_audio_url:
363
+ while player.is_playing() and not self._shutdown_event.is_set():
364
+ await asyncio.sleep(0.04)
365
+ media_player.play(pending_audio_url)
366
+ pending_audio_url = None
367
+
368
+ if self.farewell_detector.is_farewell(full_text):
369
+ print("👋 [Session concluded by farewell]")
370
+ self.stop()
371
+ break
372
+
373
+ # Run both tasks concurrently
374
+ t_mic = asyncio.create_task(mic_to_gemini())
375
+ t_spk = asyncio.create_task(gemini_to_speaker())
376
+ done, pending = await asyncio.wait(
377
+ [t_mic, t_spk], return_when=asyncio.FIRST_COMPLETED
378
+ )
379
+ for task in pending:
380
+ task.cancel()
381
+ try:
382
+ await task
383
+ except (asyncio.CancelledError, Exception):
384
+ pass
385
+
386
+ for task in done:
387
+ err = task.exception()
388
+ if err:
389
+ raise err
390
+
391
+ except (asyncio.CancelledError, KeyboardInterrupt):
392
+ self._shutdown_event.set()
393
+ break
394
+ except Exception as exc:
395
+ if self._shutdown_event.is_set():
396
+ break
397
+ print(f"⚠️ [Session connection error]: {exc}")
398
+ print(f" Reconnecting in {self.config.reconnect_delay_seconds}s...")
399
+ is_reconnect = True
400
+ await asyncio.sleep(self.config.reconnect_delay_seconds)
401
+
402
+ finally:
403
+ mic_stream.close()
404
+ player.close()
405
+ media_player.close()
406
+ if pa is not None:
407
+ try:
408
+ pa.terminate()
409
+ except Exception:
410
+ pass
411
+ print("🛑 [Voice Agent Shutdown Complete]")
412
+
413
+ async def record_user_message(self, session_id: str, text: str) -> None:
414
+ """
415
+ Records an explicit user dialogue message into memory and triggers background extraction.
416
+ """
417
+ if self.memory and text:
418
+ await self.memory.add_message(session_id, role="user", content=text)
419
+ if self.entity_extractor:
420
+ asyncio.create_task(
421
+ self.entity_extractor.extract_and_update(session_id, self.memory)
422
+ )
423
+
424
+ async def get_user_context(self, session_id: str) -> str:
425
+ """
426
+ Returns the formatted user profile context prompt for dynamic prompt injection.
427
+ """
428
+ if self.memory:
429
+ return await self.memory.build_context_prompt(session_id)
430
+ return ""
431
+
432
+ async def build_effective_system_instruction(self, session_id: str = "default") -> str:
433
+ """
434
+ Dynamically composes the complete system instruction for Gemini Live by merging:
435
+ 1. Base system instruction from VoiceConfig
436
+ 2. Known user profile memory context from BaseMemoryStore
437
+ 3. Dynamic per-tool prompt rules and usage instructions from registered BaseTools
438
+ """
439
+ instruction = self.config.system_instruction
440
+
441
+ # 1. Inject known user profile context from memory
442
+ if self.memory:
443
+ user_context = await self.memory.build_context_prompt(session_id)
444
+ if user_context:
445
+ instruction = f"{instruction}\n\n{user_context}"
446
+
447
+ # 2. Inject active tool instructions from tool registry
448
+ tools_instruction = self.tools.build_tools_instruction()
449
+ if tools_instruction:
450
+ instruction = f"{instruction}\n\n{tools_instruction}"
451
+
452
+ return instruction
453
+
454
+
@@ -0,0 +1,20 @@
1
+ """
2
+ Audio processing and hardware I/O subsystem for Voice AI Framework.
3
+ """
4
+
5
+ from edgevoiceai.audio.device import AudioDeviceManager, AudioDeviceInfo
6
+ from edgevoiceai.audio.vad import VADConfig, VoiceActivityDetector, compute_rms
7
+ from edgevoiceai.audio.player import AudioPlayer
8
+ from edgevoiceai.audio.media import MediaAudioPlayer
9
+ from edgevoiceai.audio.stream import MicrophoneStream
10
+
11
+ __all__ = [
12
+ "AudioDeviceManager",
13
+ "AudioDeviceInfo",
14
+ "VADConfig",
15
+ "VoiceActivityDetector",
16
+ "compute_rms",
17
+ "AudioPlayer",
18
+ "MediaAudioPlayer",
19
+ "MicrophoneStream",
20
+ ]