dv-pipecat-ai 0.0.85.dev7__py3-none-any.whl → 0.0.85.dev699__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.

Potentially problematic release.


This version of dv-pipecat-ai might be problematic. Click here for more details.

Files changed (158) hide show
  1. {dv_pipecat_ai-0.0.85.dev7.dist-info → dv_pipecat_ai-0.0.85.dev699.dist-info}/METADATA +78 -117
  2. {dv_pipecat_ai-0.0.85.dev7.dist-info → dv_pipecat_ai-0.0.85.dev699.dist-info}/RECORD +158 -122
  3. pipecat/adapters/base_llm_adapter.py +38 -1
  4. pipecat/adapters/services/anthropic_adapter.py +9 -14
  5. pipecat/adapters/services/aws_nova_sonic_adapter.py +5 -0
  6. pipecat/adapters/services/bedrock_adapter.py +236 -13
  7. pipecat/adapters/services/gemini_adapter.py +12 -8
  8. pipecat/adapters/services/open_ai_adapter.py +19 -7
  9. pipecat/adapters/services/open_ai_realtime_adapter.py +5 -0
  10. pipecat/audio/filters/krisp_viva_filter.py +193 -0
  11. pipecat/audio/filters/noisereduce_filter.py +15 -0
  12. pipecat/audio/turn/base_turn_analyzer.py +9 -1
  13. pipecat/audio/turn/smart_turn/base_smart_turn.py +14 -8
  14. pipecat/audio/turn/smart_turn/data/__init__.py +0 -0
  15. pipecat/audio/turn/smart_turn/data/smart-turn-v3.0.onnx +0 -0
  16. pipecat/audio/turn/smart_turn/http_smart_turn.py +6 -2
  17. pipecat/audio/turn/smart_turn/local_smart_turn.py +1 -1
  18. pipecat/audio/turn/smart_turn/local_smart_turn_v2.py +1 -1
  19. pipecat/audio/turn/smart_turn/local_smart_turn_v3.py +124 -0
  20. pipecat/audio/vad/data/README.md +10 -0
  21. pipecat/audio/vad/vad_analyzer.py +13 -1
  22. pipecat/extensions/voicemail/voicemail_detector.py +5 -5
  23. pipecat/frames/frames.py +120 -87
  24. pipecat/observers/loggers/debug_log_observer.py +3 -3
  25. pipecat/observers/loggers/llm_log_observer.py +7 -3
  26. pipecat/observers/loggers/user_bot_latency_log_observer.py +22 -10
  27. pipecat/pipeline/runner.py +12 -4
  28. pipecat/pipeline/service_switcher.py +64 -36
  29. pipecat/pipeline/task.py +85 -24
  30. pipecat/processors/aggregators/dtmf_aggregator.py +28 -22
  31. pipecat/processors/aggregators/{gated_openai_llm_context.py → gated_llm_context.py} +9 -9
  32. pipecat/processors/aggregators/gated_open_ai_llm_context.py +12 -0
  33. pipecat/processors/aggregators/llm_response.py +6 -7
  34. pipecat/processors/aggregators/llm_response_universal.py +19 -15
  35. pipecat/processors/aggregators/user_response.py +6 -6
  36. pipecat/processors/aggregators/vision_image_frame.py +24 -2
  37. pipecat/processors/audio/audio_buffer_processor.py +43 -8
  38. pipecat/processors/filters/stt_mute_filter.py +2 -0
  39. pipecat/processors/frame_processor.py +103 -17
  40. pipecat/processors/frameworks/langchain.py +8 -2
  41. pipecat/processors/frameworks/rtvi.py +209 -68
  42. pipecat/processors/frameworks/strands_agents.py +170 -0
  43. pipecat/processors/logger.py +2 -2
  44. pipecat/processors/transcript_processor.py +4 -4
  45. pipecat/processors/user_idle_processor.py +3 -6
  46. pipecat/runner/run.py +270 -50
  47. pipecat/runner/types.py +2 -0
  48. pipecat/runner/utils.py +51 -10
  49. pipecat/serializers/exotel.py +5 -5
  50. pipecat/serializers/livekit.py +20 -0
  51. pipecat/serializers/plivo.py +6 -9
  52. pipecat/serializers/protobuf.py +6 -5
  53. pipecat/serializers/telnyx.py +2 -2
  54. pipecat/serializers/twilio.py +43 -23
  55. pipecat/services/ai_service.py +2 -6
  56. pipecat/services/anthropic/llm.py +2 -25
  57. pipecat/services/asyncai/tts.py +2 -3
  58. pipecat/services/aws/__init__.py +1 -0
  59. pipecat/services/aws/llm.py +122 -97
  60. pipecat/services/aws/nova_sonic/__init__.py +0 -0
  61. pipecat/services/aws/nova_sonic/context.py +367 -0
  62. pipecat/services/aws/nova_sonic/frames.py +25 -0
  63. pipecat/services/aws/nova_sonic/llm.py +1155 -0
  64. pipecat/services/aws/stt.py +1 -3
  65. pipecat/services/aws_nova_sonic/__init__.py +19 -1
  66. pipecat/services/aws_nova_sonic/aws.py +11 -1151
  67. pipecat/services/aws_nova_sonic/context.py +13 -355
  68. pipecat/services/aws_nova_sonic/frames.py +13 -17
  69. pipecat/services/azure/realtime/__init__.py +0 -0
  70. pipecat/services/azure/realtime/llm.py +65 -0
  71. pipecat/services/azure/stt.py +15 -0
  72. pipecat/services/cartesia/tts.py +2 -2
  73. pipecat/services/deepgram/__init__.py +1 -0
  74. pipecat/services/deepgram/flux/__init__.py +0 -0
  75. pipecat/services/deepgram/flux/stt.py +636 -0
  76. pipecat/services/elevenlabs/__init__.py +2 -1
  77. pipecat/services/elevenlabs/stt.py +254 -276
  78. pipecat/services/elevenlabs/tts.py +5 -5
  79. pipecat/services/fish/tts.py +2 -2
  80. pipecat/services/gemini_multimodal_live/events.py +38 -524
  81. pipecat/services/gemini_multimodal_live/file_api.py +23 -173
  82. pipecat/services/gemini_multimodal_live/gemini.py +41 -1403
  83. pipecat/services/gladia/stt.py +56 -72
  84. pipecat/services/google/__init__.py +1 -0
  85. pipecat/services/google/gemini_live/__init__.py +3 -0
  86. pipecat/services/google/gemini_live/file_api.py +189 -0
  87. pipecat/services/google/gemini_live/llm.py +1582 -0
  88. pipecat/services/google/gemini_live/llm_vertex.py +184 -0
  89. pipecat/services/google/llm.py +15 -11
  90. pipecat/services/google/llm_openai.py +3 -3
  91. pipecat/services/google/llm_vertex.py +86 -16
  92. pipecat/services/google/tts.py +7 -3
  93. pipecat/services/heygen/api.py +2 -0
  94. pipecat/services/heygen/client.py +8 -4
  95. pipecat/services/heygen/video.py +2 -0
  96. pipecat/services/hume/__init__.py +5 -0
  97. pipecat/services/hume/tts.py +220 -0
  98. pipecat/services/inworld/tts.py +6 -6
  99. pipecat/services/llm_service.py +15 -5
  100. pipecat/services/lmnt/tts.py +2 -2
  101. pipecat/services/mcp_service.py +4 -2
  102. pipecat/services/mem0/memory.py +6 -5
  103. pipecat/services/mistral/llm.py +29 -8
  104. pipecat/services/moondream/vision.py +42 -16
  105. pipecat/services/neuphonic/tts.py +2 -2
  106. pipecat/services/openai/__init__.py +1 -0
  107. pipecat/services/openai/base_llm.py +27 -20
  108. pipecat/services/openai/realtime/__init__.py +0 -0
  109. pipecat/services/openai/realtime/context.py +272 -0
  110. pipecat/services/openai/realtime/events.py +1106 -0
  111. pipecat/services/openai/realtime/frames.py +37 -0
  112. pipecat/services/openai/realtime/llm.py +829 -0
  113. pipecat/services/openai/tts.py +16 -8
  114. pipecat/services/openai_realtime/__init__.py +27 -0
  115. pipecat/services/openai_realtime/azure.py +21 -0
  116. pipecat/services/openai_realtime/context.py +21 -0
  117. pipecat/services/openai_realtime/events.py +21 -0
  118. pipecat/services/openai_realtime/frames.py +21 -0
  119. pipecat/services/openai_realtime_beta/azure.py +16 -0
  120. pipecat/services/openai_realtime_beta/openai.py +17 -5
  121. pipecat/services/playht/tts.py +31 -4
  122. pipecat/services/rime/tts.py +3 -4
  123. pipecat/services/salesforce/__init__.py +9 -0
  124. pipecat/services/salesforce/llm.py +465 -0
  125. pipecat/services/sarvam/tts.py +2 -6
  126. pipecat/services/simli/video.py +2 -2
  127. pipecat/services/speechmatics/stt.py +1 -7
  128. pipecat/services/stt_service.py +34 -0
  129. pipecat/services/tavus/video.py +2 -2
  130. pipecat/services/tts_service.py +9 -9
  131. pipecat/services/vision_service.py +7 -6
  132. pipecat/tests/utils.py +4 -4
  133. pipecat/transcriptions/language.py +41 -1
  134. pipecat/transports/base_input.py +17 -42
  135. pipecat/transports/base_output.py +42 -26
  136. pipecat/transports/daily/transport.py +199 -26
  137. pipecat/transports/heygen/__init__.py +0 -0
  138. pipecat/transports/heygen/transport.py +381 -0
  139. pipecat/transports/livekit/transport.py +228 -63
  140. pipecat/transports/local/audio.py +6 -1
  141. pipecat/transports/local/tk.py +11 -2
  142. pipecat/transports/network/fastapi_websocket.py +1 -1
  143. pipecat/transports/smallwebrtc/connection.py +98 -19
  144. pipecat/transports/smallwebrtc/request_handler.py +204 -0
  145. pipecat/transports/smallwebrtc/transport.py +65 -23
  146. pipecat/transports/tavus/transport.py +23 -12
  147. pipecat/transports/websocket/client.py +41 -5
  148. pipecat/transports/websocket/fastapi.py +21 -11
  149. pipecat/transports/websocket/server.py +14 -7
  150. pipecat/transports/whatsapp/api.py +8 -0
  151. pipecat/transports/whatsapp/client.py +47 -0
  152. pipecat/utils/base_object.py +54 -22
  153. pipecat/utils/string.py +12 -1
  154. pipecat/utils/tracing/service_decorators.py +21 -21
  155. {dv_pipecat_ai-0.0.85.dev7.dist-info → dv_pipecat_ai-0.0.85.dev699.dist-info}/WHEEL +0 -0
  156. {dv_pipecat_ai-0.0.85.dev7.dist-info → dv_pipecat_ai-0.0.85.dev699.dist-info}/licenses/LICENSE +0 -0
  157. {dv_pipecat_ai-0.0.85.dev7.dist-info → dv_pipecat_ai-0.0.85.dev699.dist-info}/top_level.txt +0 -0
  158. /pipecat/services/{aws_nova_sonic → aws/nova_sonic}/ready.wav +0 -0
@@ -0,0 +1,1155 @@
1
+ #
2
+ # Copyright (c) 2024–2025, Daily
3
+ #
4
+ # SPDX-License-Identifier: BSD 2-Clause License
5
+ #
6
+
7
+ """AWS Nova Sonic LLM service implementation for Pipecat AI framework.
8
+
9
+ This module provides a speech-to-speech LLM service using AWS Nova Sonic, which supports
10
+ bidirectional audio streaming, text generation, and function calling capabilities.
11
+ """
12
+
13
+ import asyncio
14
+ import base64
15
+ import json
16
+ import time
17
+ import uuid
18
+ import wave
19
+ from dataclasses import dataclass
20
+ from enum import Enum
21
+ from importlib.resources import files
22
+ from typing import Any, List, Optional
23
+
24
+ from loguru import logger
25
+ from pydantic import BaseModel, Field
26
+
27
+ from pipecat.adapters.schemas.tools_schema import ToolsSchema
28
+ from pipecat.adapters.services.aws_nova_sonic_adapter import AWSNovaSonicLLMAdapter
29
+ from pipecat.frames.frames import (
30
+ BotStoppedSpeakingFrame,
31
+ CancelFrame,
32
+ EndFrame,
33
+ Frame,
34
+ FunctionCallFromLLM,
35
+ InputAudioRawFrame,
36
+ InterimTranscriptionFrame,
37
+ LLMContextFrame,
38
+ LLMFullResponseEndFrame,
39
+ LLMFullResponseStartFrame,
40
+ LLMTextFrame,
41
+ StartFrame,
42
+ TranscriptionFrame,
43
+ TTSAudioRawFrame,
44
+ TTSStartedFrame,
45
+ TTSStoppedFrame,
46
+ TTSTextFrame,
47
+ )
48
+ from pipecat.processors.aggregators.llm_response import (
49
+ LLMAssistantAggregatorParams,
50
+ LLMUserAggregatorParams,
51
+ )
52
+ from pipecat.processors.aggregators.openai_llm_context import (
53
+ OpenAILLMContext,
54
+ OpenAILLMContextFrame,
55
+ )
56
+ from pipecat.processors.frame_processor import FrameDirection
57
+ from pipecat.services.aws.nova_sonic.context import (
58
+ AWSNovaSonicAssistantContextAggregator,
59
+ AWSNovaSonicContextAggregatorPair,
60
+ AWSNovaSonicLLMContext,
61
+ AWSNovaSonicUserContextAggregator,
62
+ Role,
63
+ )
64
+ from pipecat.services.aws.nova_sonic.frames import AWSNovaSonicFunctionCallResultFrame
65
+ from pipecat.services.llm_service import LLMService
66
+ from pipecat.utils.time import time_now_iso8601
67
+
68
+ try:
69
+ from aws_sdk_bedrock_runtime.client import (
70
+ BedrockRuntimeClient,
71
+ InvokeModelWithBidirectionalStreamOperationInput,
72
+ )
73
+ from aws_sdk_bedrock_runtime.config import Config
74
+ from aws_sdk_bedrock_runtime.models import (
75
+ BidirectionalInputPayloadPart,
76
+ InvokeModelWithBidirectionalStreamInput,
77
+ InvokeModelWithBidirectionalStreamInputChunk,
78
+ InvokeModelWithBidirectionalStreamOperationOutput,
79
+ InvokeModelWithBidirectionalStreamOutput,
80
+ )
81
+ from smithy_aws_core.auth.sigv4 import SigV4AuthScheme
82
+ from smithy_aws_core.identity.static import StaticCredentialsResolver
83
+ from smithy_core.aio.eventstream import DuplexEventStream
84
+ except ModuleNotFoundError as e:
85
+ logger.error(f"Exception: {e}")
86
+ logger.error(
87
+ "In order to use AWS services, you need to `pip install pipecat-ai[aws-nova-sonic]`."
88
+ )
89
+ raise Exception(f"Missing module: {e}")
90
+
91
+
92
+ class AWSNovaSonicUnhandledFunctionException(Exception):
93
+ """Exception raised when the LLM attempts to call an unregistered function."""
94
+
95
+ pass
96
+
97
+
98
+ class ContentType(Enum):
99
+ """Content types supported by AWS Nova Sonic.
100
+
101
+ Parameters:
102
+ AUDIO: Audio content type.
103
+ TEXT: Text content type.
104
+ TOOL: Tool content type.
105
+ """
106
+
107
+ AUDIO = "AUDIO"
108
+ TEXT = "TEXT"
109
+ TOOL = "TOOL"
110
+
111
+
112
+ class TextStage(Enum):
113
+ """Text generation stages in AWS Nova Sonic responses.
114
+
115
+ Parameters:
116
+ FINAL: Final text that has been fully generated.
117
+ SPECULATIVE: Speculative text that is still being generated.
118
+ """
119
+
120
+ FINAL = "FINAL" # what has been said
121
+ SPECULATIVE = "SPECULATIVE" # what's planned to be said
122
+
123
+
124
+ @dataclass
125
+ class CurrentContent:
126
+ """Represents content currently being received from AWS Nova Sonic.
127
+
128
+ Parameters:
129
+ type: The type of content (audio, text, or tool).
130
+ role: The role generating the content (user, assistant, etc.).
131
+ text_stage: The stage of text generation (final or speculative).
132
+ text_content: The actual text content if applicable.
133
+ """
134
+
135
+ type: ContentType
136
+ role: Role
137
+ text_stage: TextStage # None if not text
138
+ text_content: str # starts as None, then fills in if text
139
+
140
+ def __str__(self):
141
+ """String representation of the current content."""
142
+ return (
143
+ f"CurrentContent(\n"
144
+ f" type={self.type.name},\n"
145
+ f" role={self.role.name},\n"
146
+ f" text_stage={self.text_stage.name if self.text_stage else 'None'}\n"
147
+ f")"
148
+ )
149
+
150
+
151
+ class Params(BaseModel):
152
+ """Configuration parameters for AWS Nova Sonic.
153
+
154
+ Parameters:
155
+ input_sample_rate: Audio input sample rate in Hz.
156
+ input_sample_size: Audio input sample size in bits.
157
+ input_channel_count: Number of input audio channels.
158
+ output_sample_rate: Audio output sample rate in Hz.
159
+ output_sample_size: Audio output sample size in bits.
160
+ output_channel_count: Number of output audio channels.
161
+ max_tokens: Maximum number of tokens to generate.
162
+ top_p: Nucleus sampling parameter.
163
+ temperature: Sampling temperature for text generation.
164
+ """
165
+
166
+ # Audio input
167
+ input_sample_rate: Optional[int] = Field(default=16000)
168
+ input_sample_size: Optional[int] = Field(default=16)
169
+ input_channel_count: Optional[int] = Field(default=1)
170
+
171
+ # Audio output
172
+ output_sample_rate: Optional[int] = Field(default=24000)
173
+ output_sample_size: Optional[int] = Field(default=16)
174
+ output_channel_count: Optional[int] = Field(default=1)
175
+
176
+ # Inference
177
+ max_tokens: Optional[int] = Field(default=1024)
178
+ top_p: Optional[float] = Field(default=0.9)
179
+ temperature: Optional[float] = Field(default=0.7)
180
+
181
+
182
+ class AWSNovaSonicLLMService(LLMService):
183
+ """AWS Nova Sonic speech-to-speech LLM service.
184
+
185
+ Provides bidirectional audio streaming, real-time transcription, text generation,
186
+ and function calling capabilities using AWS Nova Sonic model.
187
+ """
188
+
189
+ # Override the default adapter to use the AWSNovaSonicLLMAdapter one
190
+ adapter_class = AWSNovaSonicLLMAdapter
191
+
192
+ def __init__(
193
+ self,
194
+ *,
195
+ secret_access_key: str,
196
+ access_key_id: str,
197
+ session_token: Optional[str] = None,
198
+ region: str,
199
+ model: str = "amazon.nova-sonic-v1:0",
200
+ voice_id: str = "matthew", # matthew, tiffany, amy
201
+ params: Optional[Params] = None,
202
+ system_instruction: Optional[str] = None,
203
+ tools: Optional[ToolsSchema] = None,
204
+ send_transcription_frames: bool = True,
205
+ **kwargs,
206
+ ):
207
+ """Initializes the AWS Nova Sonic LLM service.
208
+
209
+ Args:
210
+ secret_access_key: AWS secret access key for authentication.
211
+ access_key_id: AWS access key ID for authentication.
212
+ session_token: AWS session token for authentication.
213
+ region: AWS region where the service is hosted.
214
+ model: Model identifier. Defaults to "amazon.nova-sonic-v1:0".
215
+ voice_id: Voice ID for speech synthesis. Options: matthew, tiffany, amy.
216
+ params: Model parameters for audio configuration and inference.
217
+ system_instruction: System-level instruction for the model.
218
+ tools: Available tools/functions for the model to use.
219
+ send_transcription_frames: Whether to emit transcription frames.
220
+ **kwargs: Additional arguments passed to the parent LLMService.
221
+ """
222
+ super().__init__(**kwargs)
223
+ self._secret_access_key = secret_access_key
224
+ self._access_key_id = access_key_id
225
+ self._session_token = session_token
226
+ self._region = region
227
+ self._model = model
228
+ self._client: Optional[BedrockRuntimeClient] = None
229
+ self._voice_id = voice_id
230
+ self._params = params or Params()
231
+ self._system_instruction = system_instruction
232
+ self._tools = tools
233
+ self._send_transcription_frames = send_transcription_frames
234
+ self._context: Optional[AWSNovaSonicLLMContext] = None
235
+ self._stream: Optional[
236
+ DuplexEventStream[
237
+ InvokeModelWithBidirectionalStreamInput,
238
+ InvokeModelWithBidirectionalStreamOutput,
239
+ InvokeModelWithBidirectionalStreamOperationOutput,
240
+ ]
241
+ ] = None
242
+ self._receive_task: Optional[asyncio.Task] = None
243
+ self._prompt_name: Optional[str] = None
244
+ self._input_audio_content_name: Optional[str] = None
245
+ self._content_being_received: Optional[CurrentContent] = None
246
+ self._assistant_is_responding = False
247
+ self._ready_to_send_context = False
248
+ self._handling_bot_stopped_speaking = False
249
+ self._triggering_assistant_response = False
250
+ self._disconnecting = False
251
+ self._connected_time: Optional[float] = None
252
+ self._wants_connection = False
253
+
254
+ file_path = files("pipecat.services.aws.nova_sonic").joinpath("ready.wav")
255
+ with wave.open(file_path.open("rb"), "rb") as wav_file:
256
+ self._assistant_response_trigger_audio = wav_file.readframes(wav_file.getnframes())
257
+
258
+ #
259
+ # standard AIService frame handling
260
+ #
261
+
262
+ async def start(self, frame: StartFrame):
263
+ """Start the service and initiate connection to AWS Nova Sonic.
264
+
265
+ Args:
266
+ frame: The start frame triggering service initialization.
267
+ """
268
+ await super().start(frame)
269
+ self._wants_connection = True
270
+ await self._start_connecting()
271
+
272
+ async def stop(self, frame: EndFrame):
273
+ """Stop the service and close connections.
274
+
275
+ Args:
276
+ frame: The end frame triggering service shutdown.
277
+ """
278
+ await super().stop(frame)
279
+ self._wants_connection = False
280
+ await self._disconnect()
281
+
282
+ async def cancel(self, frame: CancelFrame):
283
+ """Cancel the service and close connections.
284
+
285
+ Args:
286
+ frame: The cancel frame triggering service cancellation.
287
+ """
288
+ await super().cancel(frame)
289
+ self._wants_connection = False
290
+ await self._disconnect()
291
+
292
+ #
293
+ # conversation resetting
294
+ #
295
+
296
+ async def reset_conversation(self):
297
+ """Reset the conversation state while preserving context.
298
+
299
+ Handles bot stopped speaking event, disconnects from the service,
300
+ and reconnects with the preserved context.
301
+ """
302
+ logger.debug("Resetting conversation")
303
+ await self._handle_bot_stopped_speaking(delay_to_catch_trailing_assistant_text=False)
304
+
305
+ # Carry over previous context through disconnect
306
+ context = self._context
307
+ await self._disconnect()
308
+ self._context = context
309
+
310
+ await self._start_connecting()
311
+
312
+ #
313
+ # frame processing
314
+ #
315
+
316
+ async def process_frame(self, frame: Frame, direction: FrameDirection):
317
+ """Process incoming frames and handle service-specific logic.
318
+
319
+ Args:
320
+ frame: The frame to process.
321
+ direction: The direction the frame is traveling.
322
+ """
323
+ await super().process_frame(frame, direction)
324
+
325
+ if isinstance(frame, OpenAILLMContextFrame):
326
+ await self._handle_context(frame.context)
327
+ elif isinstance(frame, LLMContextFrame):
328
+ raise NotImplementedError(
329
+ "Universal LLMContext is not yet supported for AWS Nova Sonic."
330
+ )
331
+ elif isinstance(frame, InputAudioRawFrame):
332
+ await self._handle_input_audio_frame(frame)
333
+ elif isinstance(frame, BotStoppedSpeakingFrame):
334
+ await self._handle_bot_stopped_speaking(delay_to_catch_trailing_assistant_text=True)
335
+ elif isinstance(frame, AWSNovaSonicFunctionCallResultFrame):
336
+ await self._handle_function_call_result(frame)
337
+
338
+ await self.push_frame(frame, direction)
339
+
340
+ async def _handle_context(self, context: OpenAILLMContext):
341
+ if not self._context:
342
+ # We got our initial context - try to finish connecting
343
+ self._context = AWSNovaSonicLLMContext.upgrade_to_nova_sonic(
344
+ context, self._system_instruction
345
+ )
346
+ await self._finish_connecting_if_context_available()
347
+
348
+ async def _handle_input_audio_frame(self, frame: InputAudioRawFrame):
349
+ # Wait until we're done sending the assistant response trigger audio before sending audio
350
+ # from the user's mic
351
+ if self._triggering_assistant_response:
352
+ return
353
+
354
+ await self._send_user_audio_event(frame.audio)
355
+
356
+ async def _handle_bot_stopped_speaking(self, delay_to_catch_trailing_assistant_text: bool):
357
+ # Protect against back-to-back BotStoppedSpeaking calls, which I've observed
358
+ if self._handling_bot_stopped_speaking:
359
+ return
360
+ self._handling_bot_stopped_speaking = True
361
+
362
+ async def finalize_assistant_response():
363
+ if self._assistant_is_responding:
364
+ # Consider the assistant finished with their response (possibly after a short delay,
365
+ # to allow for any trailing FINAL assistant text block to come in that need to make
366
+ # it into context).
367
+ #
368
+ # TODO: ideally we could base this solely on the LLM output events, but I couldn't
369
+ # figure out a reliable way to determine when we've gotten our last FINAL text block
370
+ # after the LLM is done talking.
371
+ #
372
+ # First I looked at stopReason, but it doesn't seem like the last FINAL text block
373
+ # is reliably marked END_TURN (sometimes the *first* one is, but not the last...
374
+ # bug?)
375
+ #
376
+ # Then I considered schemes where we tally or match up SPECULATIVE text blocks with
377
+ # FINAL text blocks to know how many or which FINAL blocks to expect, but user
378
+ # interruptions throw a wrench in these schemes: depending on the exact timing of
379
+ # the interruption, we should or shouldn't expect some FINAL blocks.
380
+ if delay_to_catch_trailing_assistant_text:
381
+ # This delay length is a balancing act between "catching" trailing assistant
382
+ # text that is quite delayed but not waiting so long that user text comes in
383
+ # first and results in a bit of context message order scrambling.
384
+ await asyncio.sleep(1.25)
385
+ self._assistant_is_responding = False
386
+ await self._report_assistant_response_ended()
387
+
388
+ self._handling_bot_stopped_speaking = False
389
+
390
+ # Finalize the assistant response, either now or after a delay
391
+ if delay_to_catch_trailing_assistant_text:
392
+ self.create_task(finalize_assistant_response())
393
+ else:
394
+ await finalize_assistant_response()
395
+
396
+ async def _handle_function_call_result(self, frame: AWSNovaSonicFunctionCallResultFrame):
397
+ result = frame.result_frame
398
+ await self._send_tool_result(tool_call_id=result.tool_call_id, result=result.result)
399
+
400
+ #
401
+ # LLM communication: lifecycle
402
+ #
403
+
404
+ async def _start_connecting(self):
405
+ try:
406
+ logger.info("Connecting...")
407
+
408
+ if self._client:
409
+ # Here we assume that if we have a client we are connected or connecting
410
+ return
411
+
412
+ # Set IDs for the connection
413
+ self._prompt_name = str(uuid.uuid4())
414
+ self._input_audio_content_name = str(uuid.uuid4())
415
+
416
+ # Create the client
417
+ self._client = self._create_client()
418
+
419
+ # Start the bidirectional stream
420
+ self._stream = await self._client.invoke_model_with_bidirectional_stream(
421
+ InvokeModelWithBidirectionalStreamOperationInput(model_id=self._model)
422
+ )
423
+
424
+ # Send session start event
425
+ await self._send_session_start_event()
426
+
427
+ # Finish connecting
428
+ self._ready_to_send_context = True
429
+ await self._finish_connecting_if_context_available()
430
+ except Exception as e:
431
+ logger.error(f"{self} initialization error: {e}")
432
+ await self._disconnect()
433
+
434
+ async def _finish_connecting_if_context_available(self):
435
+ # We can only finish connecting once we've gotten our initial context and we're ready to
436
+ # send it
437
+ if not (self._context and self._ready_to_send_context):
438
+ return
439
+
440
+ logger.info("Finishing connecting (setting up session)...")
441
+
442
+ # Read context
443
+ history = self._context.get_messages_for_initializing_history()
444
+
445
+ # Send prompt start event, specifying tools.
446
+ # Tools from context take priority over self._tools.
447
+ tools = (
448
+ self._context.tools
449
+ if self._context.tools
450
+ else self.get_llm_adapter().from_standard_tools(self._tools)
451
+ )
452
+ logger.debug(f"Using tools: {tools}")
453
+ await self._send_prompt_start_event(tools)
454
+
455
+ # Send system instruction.
456
+ # Instruction from context takes priority over self._system_instruction.
457
+ # (NOTE: this prioritizing occurred automatically behind the scenes: the context was
458
+ # initialized with self._system_instruction and then updated itself from its messages when
459
+ # get_messages_for_initializing_history() was called).
460
+ logger.debug(f"Using system instruction: {history.system_instruction}")
461
+ if history.system_instruction:
462
+ await self._send_text_event(text=history.system_instruction, role=Role.SYSTEM)
463
+
464
+ # Send conversation history
465
+ for message in history.messages:
466
+ await self._send_text_event(text=message.text, role=message.role)
467
+
468
+ # Start audio input
469
+ await self._send_audio_input_start_event()
470
+
471
+ # Start receiving events
472
+ self._receive_task = self.create_task(self._receive_task_handler())
473
+
474
+ # Record finished connecting time (must be done before sending assistant response trigger)
475
+ self._connected_time = time.time()
476
+
477
+ logger.info("Finished connecting")
478
+
479
+ # If we need to, send assistant response trigger (depends on self._connected_time)
480
+ if self._triggering_assistant_response:
481
+ await self._send_assistant_response_trigger()
482
+
483
+ async def _disconnect(self):
484
+ try:
485
+ logger.info("Disconnecting...")
486
+
487
+ # NOTE: see explanation of HACK, below
488
+ self._disconnecting = True
489
+
490
+ # Clean up client
491
+ if self._client:
492
+ await self._send_session_end_events()
493
+ self._client = None
494
+
495
+ # Clean up stream
496
+ if self._stream:
497
+ await self._stream.input_stream.close()
498
+ self._stream = None
499
+
500
+ # NOTE: see explanation of HACK, below
501
+ await asyncio.sleep(1)
502
+
503
+ # Clean up receive task
504
+ # HACK: we should ideally be able to cancel the receive task before stopping the input
505
+ # stream, above (meaning we wouldn't need self._disconnecting). But for some reason if
506
+ # we don't close the input stream and wait a second first, we're getting an error a lot
507
+ # like this one: https://github.com/awslabs/amazon-transcribe-streaming-sdk/issues/61.
508
+ if self._receive_task:
509
+ await self.cancel_task(self._receive_task, timeout=1.0)
510
+ self._receive_task = None
511
+
512
+ # Reset remaining connection-specific state
513
+ self._prompt_name = None
514
+ self._input_audio_content_name = None
515
+ self._content_being_received = None
516
+ self._assistant_is_responding = False
517
+ self._ready_to_send_context = False
518
+ self._handling_bot_stopped_speaking = False
519
+ self._triggering_assistant_response = False
520
+ self._disconnecting = False
521
+ self._connected_time = None
522
+
523
+ logger.info("Finished disconnecting")
524
+ except Exception as e:
525
+ logger.error(f"{self} error disconnecting: {e}")
526
+
527
+ def _create_client(self) -> BedrockRuntimeClient:
528
+ config = Config(
529
+ endpoint_uri=f"https://bedrock-runtime.{self._region}.amazonaws.com",
530
+ region=self._region,
531
+ aws_access_key_id=self._access_key_id,
532
+ aws_secret_access_key=self._secret_access_key,
533
+ aws_session_token=self._session_token,
534
+ aws_credentials_identity_resolver=StaticCredentialsResolver(),
535
+ auth_schemes={"aws.auth#sigv4": SigV4AuthScheme(service="bedrock")},
536
+ )
537
+ return BedrockRuntimeClient(config=config)
538
+
539
+ #
540
+ # LLM communication: input events (pipecat -> LLM)
541
+ #
542
+
543
+ async def _send_session_start_event(self):
544
+ session_start = f"""
545
+ {{
546
+ "event": {{
547
+ "sessionStart": {{
548
+ "inferenceConfiguration": {{
549
+ "maxTokens": {self._params.max_tokens},
550
+ "topP": {self._params.top_p},
551
+ "temperature": {self._params.temperature}
552
+ }}
553
+ }}
554
+ }}
555
+ }}
556
+ """
557
+ await self._send_client_event(session_start)
558
+
559
+ async def _send_prompt_start_event(self, tools: List[Any]):
560
+ if not self._prompt_name:
561
+ return
562
+
563
+ tools_config = (
564
+ f""",
565
+ "toolUseOutputConfiguration": {{
566
+ "mediaType": "application/json"
567
+ }},
568
+ "toolConfiguration": {{
569
+ "tools": {json.dumps(tools)}
570
+ }}
571
+ """
572
+ if tools
573
+ else ""
574
+ )
575
+
576
+ prompt_start = f'''
577
+ {{
578
+ "event": {{
579
+ "promptStart": {{
580
+ "promptName": "{self._prompt_name}",
581
+ "textOutputConfiguration": {{
582
+ "mediaType": "text/plain"
583
+ }},
584
+ "audioOutputConfiguration": {{
585
+ "mediaType": "audio/lpcm",
586
+ "sampleRateHertz": {self._params.output_sample_rate},
587
+ "sampleSizeBits": {self._params.output_sample_size},
588
+ "channelCount": {self._params.output_channel_count},
589
+ "voiceId": "{self._voice_id}",
590
+ "encoding": "base64",
591
+ "audioType": "SPEECH"
592
+ }}{tools_config}
593
+ }}
594
+ }}
595
+ }}
596
+ '''
597
+ await self._send_client_event(prompt_start)
598
+
599
+ async def _send_audio_input_start_event(self):
600
+ if not self._prompt_name:
601
+ return
602
+
603
+ audio_content_start = f'''
604
+ {{
605
+ "event": {{
606
+ "contentStart": {{
607
+ "promptName": "{self._prompt_name}",
608
+ "contentName": "{self._input_audio_content_name}",
609
+ "type": "AUDIO",
610
+ "interactive": true,
611
+ "role": "USER",
612
+ "audioInputConfiguration": {{
613
+ "mediaType": "audio/lpcm",
614
+ "sampleRateHertz": {self._params.input_sample_rate},
615
+ "sampleSizeBits": {self._params.input_sample_size},
616
+ "channelCount": {self._params.input_channel_count},
617
+ "audioType": "SPEECH",
618
+ "encoding": "base64"
619
+ }}
620
+ }}
621
+ }}
622
+ }}
623
+ '''
624
+ await self._send_client_event(audio_content_start)
625
+
626
+ async def _send_text_event(self, text: str, role: Role):
627
+ if not self._stream or not self._prompt_name or not text:
628
+ return
629
+
630
+ content_name = str(uuid.uuid4())
631
+
632
+ text_content_start = f'''
633
+ {{
634
+ "event": {{
635
+ "contentStart": {{
636
+ "promptName": "{self._prompt_name}",
637
+ "contentName": "{content_name}",
638
+ "type": "TEXT",
639
+ "interactive": true,
640
+ "role": "{role.value}",
641
+ "textInputConfiguration": {{
642
+ "mediaType": "text/plain"
643
+ }}
644
+ }}
645
+ }}
646
+ }}
647
+ '''
648
+ await self._send_client_event(text_content_start)
649
+
650
+ escaped_text = json.dumps(text) # includes quotes
651
+ text_input = f'''
652
+ {{
653
+ "event": {{
654
+ "textInput": {{
655
+ "promptName": "{self._prompt_name}",
656
+ "contentName": "{content_name}",
657
+ "content": {escaped_text}
658
+ }}
659
+ }}
660
+ }}
661
+ '''
662
+ await self._send_client_event(text_input)
663
+
664
+ text_content_end = f'''
665
+ {{
666
+ "event": {{
667
+ "contentEnd": {{
668
+ "promptName": "{self._prompt_name}",
669
+ "contentName": "{content_name}"
670
+ }}
671
+ }}
672
+ }}
673
+ '''
674
+ await self._send_client_event(text_content_end)
675
+
676
+ async def _send_user_audio_event(self, audio: bytes):
677
+ if not self._stream:
678
+ return
679
+
680
+ blob = base64.b64encode(audio)
681
+ audio_event = f'''
682
+ {{
683
+ "event": {{
684
+ "audioInput": {{
685
+ "promptName": "{self._prompt_name}",
686
+ "contentName": "{self._input_audio_content_name}",
687
+ "content": "{blob.decode("utf-8")}"
688
+ }}
689
+ }}
690
+ }}
691
+ '''
692
+ await self._send_client_event(audio_event)
693
+
694
+ async def _send_session_end_events(self):
695
+ if not self._stream or not self._prompt_name:
696
+ return
697
+
698
+ prompt_end = f'''
699
+ {{
700
+ "event": {{
701
+ "promptEnd": {{
702
+ "promptName": "{self._prompt_name}"
703
+ }}
704
+ }}
705
+ }}
706
+ '''
707
+ await self._send_client_event(prompt_end)
708
+
709
+ session_end = """
710
+ {
711
+ "event": {
712
+ "sessionEnd": {}
713
+ }
714
+ }
715
+ """
716
+ await self._send_client_event(session_end)
717
+
718
+ async def _send_tool_result(self, tool_call_id, result):
719
+ if not self._stream or not self._prompt_name:
720
+ return
721
+
722
+ content_name = str(uuid.uuid4())
723
+
724
+ result_content_start = f'''
725
+ {{
726
+ "event": {{
727
+ "contentStart": {{
728
+ "promptName": "{self._prompt_name}",
729
+ "contentName": "{content_name}",
730
+ "interactive": false,
731
+ "type": "TOOL",
732
+ "role": "TOOL",
733
+ "toolResultInputConfiguration": {{
734
+ "toolUseId": "{tool_call_id}",
735
+ "type": "TEXT",
736
+ "textInputConfiguration": {{
737
+ "mediaType": "text/plain"
738
+ }}
739
+ }}
740
+ }}
741
+ }}
742
+ }}
743
+ '''
744
+ await self._send_client_event(result_content_start)
745
+
746
+ result_content = json.dumps(
747
+ {
748
+ "event": {
749
+ "toolResult": {
750
+ "promptName": self._prompt_name,
751
+ "contentName": content_name,
752
+ "content": json.dumps(result) if isinstance(result, dict) else result,
753
+ }
754
+ }
755
+ }
756
+ )
757
+ await self._send_client_event(result_content)
758
+
759
+ result_content_end = f"""
760
+ {{
761
+ "event": {{
762
+ "contentEnd": {{
763
+ "promptName": "{self._prompt_name}",
764
+ "contentName": "{content_name}"
765
+ }}
766
+ }}
767
+ }}
768
+ """
769
+ await self._send_client_event(result_content_end)
770
+
771
+ async def _send_client_event(self, event_json: str):
772
+ if not self._stream: # should never happen
773
+ return
774
+
775
+ event = InvokeModelWithBidirectionalStreamInputChunk(
776
+ value=BidirectionalInputPayloadPart(bytes_=event_json.encode("utf-8"))
777
+ )
778
+ await self._stream.input_stream.send(event)
779
+
780
+ #
781
+ # LLM communication: output events (LLM -> pipecat)
782
+ #
783
+
784
+ # Receive events for the session.
785
+ # A few different kinds of content can be delivered:
786
+ # - Transcription of user audio
787
+ # - Tool use
788
+ # - Text preview of planned response speech before audio delivered
789
+ # - User interruption notification
790
+ # - Text of response speech that whose audio was actually delivered
791
+ # - Audio of response speech
792
+ # Each piece of content is wrapped by "contentStart" and "contentEnd" events. The content is
793
+ # delivered sequentially: one piece of content will end before another starts.
794
+ # The overall completion is wrapped by "completionStart" and "completionEnd" events.
795
+ async def _receive_task_handler(self):
796
+ try:
797
+ while self._stream and not self._disconnecting:
798
+ output = await self._stream.await_output()
799
+ result = await output[1].receive()
800
+
801
+ if result.value and result.value.bytes_:
802
+ response_data = result.value.bytes_.decode("utf-8")
803
+ json_data = json.loads(response_data)
804
+
805
+ if "event" in json_data:
806
+ event_json = json_data["event"]
807
+ if "completionStart" in event_json:
808
+ # Handle the LLM completion starting
809
+ await self._handle_completion_start_event(event_json)
810
+ elif "contentStart" in event_json:
811
+ # Handle a piece of content starting
812
+ await self._handle_content_start_event(event_json)
813
+ elif "textOutput" in event_json:
814
+ # Handle text output content
815
+ await self._handle_text_output_event(event_json)
816
+ elif "audioOutput" in event_json:
817
+ # Handle audio output content
818
+ await self._handle_audio_output_event(event_json)
819
+ elif "toolUse" in event_json:
820
+ # Handle tool use
821
+ await self._handle_tool_use_event(event_json)
822
+ elif "contentEnd" in event_json:
823
+ # Handle a piece of content ending
824
+ await self._handle_content_end_event(event_json)
825
+ elif "completionEnd" in event_json:
826
+ # Handle the LLM completion ending
827
+ await self._handle_completion_end_event(event_json)
828
+ except Exception as e:
829
+ logger.error(f"{self} error processing responses: {e}")
830
+ if self._wants_connection:
831
+ await self.reset_conversation()
832
+
833
+ async def _handle_completion_start_event(self, event_json):
834
+ pass
835
+
836
+ async def _handle_content_start_event(self, event_json):
837
+ content_start = event_json["contentStart"]
838
+ type = content_start["type"]
839
+ role = content_start["role"]
840
+ generation_stage = None
841
+ if "additionalModelFields" in content_start:
842
+ additional_model_fields = json.loads(content_start["additionalModelFields"])
843
+ generation_stage = additional_model_fields.get("generationStage")
844
+
845
+ # Bookkeeping: track current content being received
846
+ content = CurrentContent(
847
+ type=ContentType(type),
848
+ role=Role(role),
849
+ text_stage=TextStage(generation_stage) if generation_stage else None,
850
+ text_content=None,
851
+ )
852
+ self._content_being_received = content
853
+
854
+ if content.role == Role.ASSISTANT:
855
+ if content.type == ContentType.AUDIO:
856
+ # Note that an assistant response can comprise of multiple audio blocks
857
+ if not self._assistant_is_responding:
858
+ # The assistant has started responding.
859
+ self._assistant_is_responding = True
860
+ await self._report_user_transcription_ended() # Consider user turn over
861
+ await self._report_assistant_response_started()
862
+
863
+ async def _handle_text_output_event(self, event_json):
864
+ if not self._content_being_received: # should never happen
865
+ return
866
+ content = self._content_being_received
867
+
868
+ text_content = event_json["textOutput"]["content"]
869
+
870
+ # Bookkeeping: augment the current content being received with text
871
+ # Assumption: only one text content per content block
872
+ content.text_content = text_content
873
+
874
+ async def _handle_audio_output_event(self, event_json):
875
+ if not self._content_being_received: # should never happen
876
+ return
877
+
878
+ # Get audio
879
+ audio_content = event_json["audioOutput"]["content"]
880
+
881
+ # Push audio frame
882
+ audio = base64.b64decode(audio_content)
883
+ frame = TTSAudioRawFrame(
884
+ audio=audio,
885
+ sample_rate=self._params.output_sample_rate,
886
+ num_channels=self._params.output_channel_count,
887
+ )
888
+ await self.push_frame(frame)
889
+
890
+ async def _handle_tool_use_event(self, event_json):
891
+ if not self._content_being_received or not self._context: # should never happen
892
+ return
893
+
894
+ # Consider user turn over
895
+ await self._report_user_transcription_ended()
896
+
897
+ # Get tool use details
898
+ tool_use = event_json["toolUse"]
899
+ function_name = tool_use["toolName"]
900
+ tool_call_id = tool_use["toolUseId"]
901
+ arguments = json.loads(tool_use["content"])
902
+
903
+ # Call tool function
904
+ if self.has_function(function_name):
905
+ if function_name in self._functions.keys() or None in self._functions.keys():
906
+ function_calls_llm = [
907
+ FunctionCallFromLLM(
908
+ context=self._context,
909
+ tool_call_id=tool_call_id,
910
+ function_name=function_name,
911
+ arguments=arguments,
912
+ )
913
+ ]
914
+
915
+ await self.run_function_calls(function_calls_llm)
916
+ else:
917
+ raise AWSNovaSonicUnhandledFunctionException(
918
+ f"The LLM tried to call a function named '{function_name}', but there isn't a callback registered for that function."
919
+ )
920
+
921
+ async def _handle_content_end_event(self, event_json):
922
+ if not self._content_being_received: # should never happen
923
+ return
924
+ content = self._content_being_received
925
+
926
+ content_end = event_json["contentEnd"]
927
+ stop_reason = content_end["stopReason"]
928
+
929
+ # Bookkeeping: clear current content being received
930
+ self._content_being_received = None
931
+
932
+ if content.role == Role.ASSISTANT:
933
+ if content.type == ContentType.TEXT:
934
+ # Ignore non-final text, and the "interrupted" message (which isn't meaningful text)
935
+ if content.text_stage == TextStage.FINAL and stop_reason != "INTERRUPTED":
936
+ if self._assistant_is_responding:
937
+ # Text added to the ongoing assistant response
938
+ await self._report_assistant_response_text_added(content.text_content)
939
+ elif content.role == Role.USER:
940
+ if content.type == ContentType.TEXT:
941
+ if content.text_stage == TextStage.FINAL:
942
+ # User transcription text added
943
+ await self._report_user_transcription_text_added(content.text_content)
944
+
945
+ async def _handle_completion_end_event(self, event_json):
946
+ pass
947
+
948
+ #
949
+ # assistant response reporting
950
+ #
951
+ # 1. Started
952
+ # 2. Text added
953
+ # 3. Ended
954
+ #
955
+
956
+ async def _report_assistant_response_started(self):
957
+ logger.debug("Assistant response started")
958
+
959
+ # Report that the assistant has started their response.
960
+ await self.push_frame(LLMFullResponseStartFrame())
961
+
962
+ # Report that equivalent of TTS (this is a speech-to-speech model) started
963
+ await self.push_frame(TTSStartedFrame())
964
+
965
+ async def _report_assistant_response_text_added(self, text):
966
+ if not self._context: # should never happen
967
+ return
968
+
969
+ logger.debug(f"Assistant response text added: {text}")
970
+
971
+ # Report some text added to the ongoing assistant response
972
+ await self.push_frame(LLMTextFrame(text))
973
+
974
+ # Report some text added to the *equivalent* of TTS (this is a speech-to-speech model)
975
+ await self.push_frame(TTSTextFrame(text))
976
+
977
+ # TODO: this is a (hopefully temporary) HACK. Here we directly manipulate the context rather
978
+ # than relying on the frames pushed to the assistant context aggregator. The pattern of
979
+ # receiving full-sentence text after the assistant has spoken does not easily fit with the
980
+ # Pipecat expectation of chunks of text streaming in while the assistant is speaking.
981
+ # Interruption handling was especially challenging. Rather than spend days trying to fit a
982
+ # square peg in a round hole, I decided on this hack for the time being. We can most cleanly
983
+ # abandon this hack if/when AWS Nova Sonic implements streaming smaller text chunks
984
+ # interspersed with audio. Note that when we move away from this hack, we need to make sure
985
+ # that on an interruption we avoid sending LLMFullResponseEndFrame, which gets the
986
+ # LLMAssistantContextAggregator into a bad state.
987
+ self._context.buffer_assistant_text(text)
988
+
989
+ async def _report_assistant_response_ended(self):
990
+ if not self._context: # should never happen
991
+ return
992
+
993
+ logger.debug("Assistant response ended")
994
+
995
+ # Report that the assistant has finished their response.
996
+ await self.push_frame(LLMFullResponseEndFrame())
997
+
998
+ # Report that equivalent of TTS (this is a speech-to-speech model) stopped.
999
+ await self.push_frame(TTSStoppedFrame())
1000
+
1001
+ # For an explanation of this hack, see _report_assistant_response_text_added.
1002
+ self._context.flush_aggregated_assistant_text()
1003
+
1004
+ #
1005
+ # user transcription reporting
1006
+ #
1007
+ # 1. Text added
1008
+ # 2. Ended
1009
+ #
1010
+ # Note: "started" does not need to be reported
1011
+ #
1012
+
1013
+ async def _report_user_transcription_text_added(self, text):
1014
+ if not self._context: # should never happen
1015
+ return
1016
+
1017
+ logger.debug(f"User transcription text added: {text}")
1018
+
1019
+ # Manually add new user transcription text to context.
1020
+ # We can't rely on the user context aggregator to do this since it's upstream from the LLM.
1021
+ self._context.buffer_user_text(text)
1022
+
1023
+ # Report that some new user transcription text is available.
1024
+ if self._send_transcription_frames:
1025
+ await self.push_frame(
1026
+ InterimTranscriptionFrame(text=text, user_id="", timestamp=time_now_iso8601())
1027
+ )
1028
+
1029
+ async def _report_user_transcription_ended(self):
1030
+ if not self._context: # should never happen
1031
+ return
1032
+
1033
+ # Manually add user transcription to context (if any has been buffered).
1034
+ # We can't rely on the user context aggregator to do this since it's upstream from the LLM.
1035
+ transcription = self._context.flush_aggregated_user_text()
1036
+
1037
+ if not transcription:
1038
+ return
1039
+
1040
+ logger.debug(f"User transcription ended")
1041
+
1042
+ if self._send_transcription_frames:
1043
+ await self.push_frame(
1044
+ TranscriptionFrame(text=transcription, user_id="", timestamp=time_now_iso8601())
1045
+ )
1046
+
1047
+ #
1048
+ # context
1049
+ #
1050
+
1051
+ def create_context_aggregator(
1052
+ self,
1053
+ context: OpenAILLMContext,
1054
+ *,
1055
+ user_params: LLMUserAggregatorParams = LLMUserAggregatorParams(),
1056
+ assistant_params: LLMAssistantAggregatorParams = LLMAssistantAggregatorParams(),
1057
+ ) -> AWSNovaSonicContextAggregatorPair:
1058
+ """Create context aggregator pair for managing conversation context.
1059
+
1060
+ Args:
1061
+ context: The OpenAI LLM context to upgrade.
1062
+ user_params: Parameters for the user context aggregator.
1063
+ assistant_params: Parameters for the assistant context aggregator.
1064
+
1065
+ Returns:
1066
+ A pair of user and assistant context aggregators.
1067
+ """
1068
+ context.set_llm_adapter(self.get_llm_adapter())
1069
+
1070
+ user = AWSNovaSonicUserContextAggregator(context=context, params=user_params)
1071
+ assistant = AWSNovaSonicAssistantContextAggregator(context=context, params=assistant_params)
1072
+
1073
+ return AWSNovaSonicContextAggregatorPair(user, assistant)
1074
+
1075
+ #
1076
+ # assistant response trigger (HACK)
1077
+ #
1078
+
1079
+ # Class variable
1080
+ AWAIT_TRIGGER_ASSISTANT_RESPONSE_INSTRUCTION = (
1081
+ "Start speaking when you hear the user say 'ready', but don't consider that 'ready' to be "
1082
+ "a meaningful part of the conversation other than as a trigger for you to start speaking."
1083
+ )
1084
+
1085
+ async def trigger_assistant_response(self):
1086
+ """Trigger an assistant response by sending audio cue.
1087
+
1088
+ Sends a pre-recorded "ready" audio trigger to prompt the assistant
1089
+ to start speaking. This is useful for controlling conversation flow.
1090
+
1091
+ Returns:
1092
+ False if already triggering a response, True otherwise.
1093
+ """
1094
+ if self._triggering_assistant_response:
1095
+ return False
1096
+
1097
+ self._triggering_assistant_response = True
1098
+
1099
+ # Send the trigger audio, if we're fully connected and set up
1100
+ if self._connected_time:
1101
+ await self._send_assistant_response_trigger()
1102
+
1103
+ async def _send_assistant_response_trigger(self):
1104
+ if not self._connected_time:
1105
+ # should never happen
1106
+ return
1107
+
1108
+ try:
1109
+ logger.debug("Sending assistant response trigger...")
1110
+
1111
+ chunk_duration = 0.02 # what we might get from InputAudioRawFrame
1112
+ chunk_size = int(
1113
+ chunk_duration
1114
+ * self._params.input_sample_rate
1115
+ * self._params.input_channel_count
1116
+ * (self._params.input_sample_size / 8)
1117
+ ) # e.g. 0.02 seconds of 16-bit (2-byte) PCM mono audio at 16kHz is 640 bytes
1118
+
1119
+ # Lead with a bit of blank audio, if needed.
1120
+ # It seems like the LLM can't quite "hear" the first little bit of audio sent on a
1121
+ # connection.
1122
+ current_time = time.time()
1123
+ max_blank_audio_duration = 0.5
1124
+ blank_audio_duration = (
1125
+ max_blank_audio_duration - (current_time - self._connected_time)
1126
+ if self._connected_time is not None
1127
+ and (current_time - self._connected_time) < max_blank_audio_duration
1128
+ else None
1129
+ )
1130
+ if blank_audio_duration:
1131
+ logger.debug(
1132
+ f"Leading assistant response trigger with {blank_audio_duration}s of blank audio"
1133
+ )
1134
+ blank_audio_chunk = b"\x00" * chunk_size
1135
+ num_chunks = int(blank_audio_duration / chunk_duration)
1136
+ for _ in range(num_chunks):
1137
+ await self._send_user_audio_event(blank_audio_chunk)
1138
+ await asyncio.sleep(chunk_duration)
1139
+
1140
+ # Send trigger audio
1141
+ # NOTE: this audio *will* be transcribed and eventually make it into the context. That's OK:
1142
+ # if we ever need to seed this service again with context it would make sense to include it
1143
+ # since the instruction (i.e. the "wait for the trigger" instruction) will be part of the
1144
+ # context as well.
1145
+ audio_chunks = [
1146
+ self._assistant_response_trigger_audio[i : i + chunk_size]
1147
+ for i in range(0, len(self._assistant_response_trigger_audio), chunk_size)
1148
+ ]
1149
+ for chunk in audio_chunks:
1150
+ await self._send_user_audio_event(chunk)
1151
+ await asyncio.sleep(chunk_duration)
1152
+ finally:
1153
+ # We need to clean up in case sending the trigger was cancelled, e.g. in the case of a user interruption.
1154
+ # (An asyncio.CancelledError would be raised in that case.)
1155
+ self._triggering_assistant_response = False