Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
feat: Assistant doesn't interrupt itself when speaking
Clémence Lesné416afd583681
diff --git a/README.md b/README.mdindex e047a36..dfd44d7 100644--- a/README.md+++ b/README.md@@ -500,6 +500,7 @@ Conversation options are represented as features. They can be configured from Ap| `slow_llm_for_chat` | Whether to use the slow LLM for chat. | `bool` | false || `vad_cutoff_timeout_ms` | The cutoff timeout for voice activity detection in secs. | `int` | 600 || `vad_silence_timeout_ms` | The timeout for phone silence in secs. | `int` | 400 |+| `vad_threshold` | The threshold for voice activity detection. | `float` | 0.5 |### Use an OpenAI compatible model for the LLMdiff --git a/app/helpers/call_events.py b/app/helpers/call_events.pyindex e479022..4964d77 100644--- a/app/helpers/call_events.py+++ b/app/helpers/call_events.py@@ -168,8 +168,6 @@ async def on_call_disconnected(@tracer.start_as_current_span("on_audio_connected")async def on_audio_connected( # noqa: PLR0913- audio_bits_per_sample: int,- audio_channels: int,audio_in: asyncio.Queue[bytes],audio_out: asyncio.Queue[bytes | bool],audio_sample_rate: int,@@ -185,8 +183,6 @@ async def on_audio_connected( # noqa: PLR0913Starts the real-time conversation with the LLM."""await load_llm_chat(- audio_bits_per_sample=audio_bits_per_sample,- audio_channels=audio_channels,audio_in=audio_in,audio_out=audio_out,audio_sample_rate=audio_sample_rate,diff --git a/app/helpers/call_llm.py b/app/helpers/call_llm.pyindex 51f01c4..5199b78 100644--- a/app/helpers/call_llm.py+++ b/app/helpers/call_llm.py@@ -10,14 +10,9 @@ from azure.cognitiveservices.speech import (from azure.cognitiveservices.speech.audio import PushAudioInputStreamfrom azure.communication.callautomation.aio import CallAutomationClientfrom openai import APIError-from pydub import AudioSegment-from pydub.effects import (- high_pass_filter,- low_pass_filter,-)-from webrtcvad import Vadfrom app.helpers.call_utils import (+ EchoCancellationStream,handle_media,handle_realtime_tts,tts_sentence_split,@@ -55,9 +50,7 @@ _db = CONFIG.database.instance()# TODO: Refacto, this function is too long@tracer.start_as_current_span("call_load_llm_chat")-async def load_llm_chat( # noqa: PLR0913- audio_bits_per_sample: int,- audio_channels: int,+async def load_llm_chat( # noqa: PLR0913, PLR0915audio_in: asyncio.Queue[bytes],audio_out: asyncio.Queue[bytes | bool],audio_sample_rate: int,@@ -70,16 +63,56 @@ async def load_llm_chat( # noqa: PLR0913# Init language recognitionstt_buffer: list[str] = [] # Temporary buffer for recognitionstt_complete_gate = asyncio.Event() # Gate to wait for the recognition+ aec = EchoCancellationStream(+ sample_rate=audio_sample_rate,+ )+ audio_reference: asyncio.Queue[bytes] = asyncio.Queue()- def _stt_callback(text: str) -> None:+ async def _send_in_to_aec() -> None:"""- Store the recognition in the buffer.+ Send input audio to the echo cancellation."""- # Skip if no text- if not text:- return+ while True:+ in_chunck = await audio_in.get()+ audio_in.task_done()+ await aec.push_input(in_chunck)++ async def _send_out_to_aec() -> None:+ """+ Forward the TTS to the echo cancellation and output.+ """+ while True:+ out_chunck = await audio_reference.get()+ audio_reference.task_done()+ await asyncio.gather(+ # First, send the audio to the output+ audio_out.put(out_chunck),+ # Then, send the audio to the echo cancellation+ aec.push_reference(out_chunck),+ )- stt_buffer.append(text)+ def _partial_stt_callback(text: str) -> None:+ """+ Store the partial recognition in the buffer.+ """+ # Init buffer if empty+ if not stt_buffer:+ stt_buffer.append("")+ # Append the recognition+ stt_buffer[-1] += text+ logger.debug("Partial recognition: %s", stt_buffer)++ def _complete_stt_callback(text: str) -> None:+ """+ Store the recognition in the buffer.+ """+ # Init buffer if empty+ if not stt_buffer:+ stt_buffer.append("")+ # Store the recognition+ stt_buffer[-1] = text+ # Add a new buffer for the next partial recognition+ stt_buffer.append("")logger.debug("Complete recognition: %s", stt_buffer)# Open the recognition gate@@ -87,15 +120,14 @@ async def load_llm_chat( # noqa: PLR0913async with (use_stt_client(- audio_bits_per_sample=audio_bits_per_sample,- audio_channels=audio_channels,audio_sample_rate=audio_sample_rate,call=call,- callback=_stt_callback,+ complete_callback=_complete_stt_callback,+ partial_callback=_partial_stt_callback,) as stt_stream,use_tts_client(- audio=audio_out,call=call,+ out=audio_reference,) as tts_client,):# Build scheduler@@ -120,32 +152,32 @@ async def load_llm_chat( # noqa: PLR0913))- async def _clear_audio_callback() -> None:+ async def _stop_callback() -> None:"""Triggered when the audio buffer needs to be cleared."""+ # Close previous response now+ if last_response:+ await last_response.close(timeout=0)+# Stop TTS, clear the buffer and send a stop signaltts_client.stop_speaking_async()- while not audio_out.empty():- audio_out.get_nowait()- audio_out.task_done()- await audio_out.put(False)- # Close the recognition gate+ # Reset the recognition+ stt_buffer.clear()stt_complete_gate.clear()- # Close previous response if any- if last_response:- await scheduler.spawn(last_response.close(timeout=0))-- # Clear the recognition buffer- stt_buffer.clear()+ # Send a stop signal+ await audio_out.put(False)async def _commit_answer(tool_blacklist: set[str] | None = None) -> None:"""Process the response."""- # Store recognition task+ # Stop any previous response+ await _stop_callback()++ # Start chat tasknonlocal last_responselast_response = await scheduler.spawn(_continue_chat(@@ -159,21 +191,31 @@ async def load_llm_chat( # noqa: PLR0913))- # Wait for the response to be processed+ # Wait for its responseawait last_response.wait()- async def _response_callback() -> None:+ async def _response_callback(_retry: bool = False) -> None:"""Triggered when the audio buffer needs to be processed.++ If the recognition is empty, retry the recognition once. Otherwise, process the response."""- # Wait for the complete recognition- await stt_complete_gate.wait()+ # Wait the complete recognition for 50ms maximum+ try:+ await asyncio.wait_for(stt_complete_gate.wait(), timeout=0.05)+ except TimeoutError:+ passstt_text = " ".join(stt_buffer).strip()- # Skip if no partial recognition+ # Ignore empty recognitionif not stt_text:- return+ # Skip if already retries+ if _retry:+ return+ # Retry recognition, maybe the user was too fast or the recognition is temporarly slow+ await asyncio.sleep(0.2)+ return await _response_callback(_retry=True)# Add it to the call history and update last interactionlogger.info("Voice stored: %s", stt_buffer)@@ -211,16 +253,21 @@ async def load_llm_chat( # noqa: PLR0913{"end_call"},)- await _process_chat_audio(- bits_per_sample=audio_bits_per_sample,- call=call,- channels=audio_channels,- clear_audio_callback=_clear_audio_callback,- in_stream=audio_in,- out_stream=stt_stream,- response_callback=_response_callback,- sample_rate=audio_sample_rate,- timeout_callback=_timeout_callback,+ await asyncio.gather(+ # Start the echo cancellation+ aec.process_stream(),+ # Apply the echo cancellation+ _send_in_to_aec(),+ _send_out_to_aec(),+ # Detect VAD+ _process_audio_for_vad(+ call=call,+ stop_callback=_stop_callback,+ echo_cancellation=aec,+ out_stream=stt_stream,+ response_callback=_response_callback,+ timeout_callback=_timeout_callback,+ ),)@@ -598,38 +645,41 @@ async def _generate_chat_completion( # noqa: PLR0913, PLR0911, PLR0912, PLR0915# TODO: Refacto and simplify-async def _process_chat_audio( # noqa: PLR0913- bits_per_sample: int,+async def _process_audio_for_vad( # noqa: PLR0913call: CallStateModel,- channels: int,- clear_audio_callback: Callable[[], Awaitable[None]],- in_stream: asyncio.Queue[bytes],+ echo_cancellation: EchoCancellationStream,out_stream: PushAudioInputStream,response_callback: Callable[[], Awaitable[None]],- sample_rate: int,+ stop_callback: Callable[[], Awaitable[None]],timeout_callback: Callable[[], Awaitable[None]],) -> None:- clear_tts_task: asyncio.Task | None = None+ """+ Process voice activity and silence detection.++ Follows the following steps:++ - Detect voice activity and clear the TTS to let the user speak+ - Wait for silence and trigger the chat+ - Wait for longer silence and trigger the timeout+ """+ stop_task: asyncio.Task | None = Nonesilence_task: asyncio.Task | None = None- vad = Vad(- # Aggressiveness mode (0, 1, 2, or 3)- # Sets the VAD operating mode. A more aggressive (higher mode) VAD is more restrictive in reporting speech. Put in other words the probability of being speech when the VAD returns 1 is increased with increasing mode. As a consequence also the missed detection rate goes up.- mode=3,- )- async def _silence_callback() -> None:+ async def _wait_for_silence() -> None:"""- Flush the audio buffer if no audio is detected for a while and trigger the timeout if required.+ Run the chat after a silence.++ If the silence is too long, run the timeout."""# Wait before flushing- nonlocal clear_tts_task+ nonlocal stop_tasktimeout_ms = await vad_silence_timeout_ms()await asyncio.sleep(timeout_ms / 1000)- # Cancel the clear TTS task if any- if clear_tts_task:- clear_tts_task.cancel()- clear_tts_task = None+ # Cancel the clear TTS task+ if stop_task:+ stop_task.cancel()+ stop_task = None# Flush the audio bufferlogger.debug("Flushing audio buffer after %i ms", timeout_ms)@@ -661,11 +711,9 @@ async def _process_chat_audio( # noqa: PLR0913logger.info("Silence triggered after %i sec", timeout_sec)await timeout_callback()- async def _clear_tts_callback() -> None:+ async def _wait_for_stop() -> None:"""- Clear the TTS queue.-- Start is the index of the buffer where the TTS was triggered.+ Stop the TTS if user speaks for too long."""timeout_ms = await vad_cutoff_timeout_ms()@@ -675,55 +723,31 @@ async def _process_chat_audio( # noqa: PLR0913logger.debug("Canceling TTS after %i ms", timeout_ms)# Clear the queue- await clear_audio_callback()+ await stop_callback()- # Consumes audio streamwhile True:# Wait for the next audio packet- in_chunck = await in_stream.get()-- # Load audio- in_audio: AudioSegment = AudioSegment(- channels=channels,- data=in_chunck,- frame_rate=sample_rate,- sample_width=bits_per_sample // 8,- )-- # Apply high-pass and low-pass filters in a simple attempt to reduce noise- in_audio = high_pass_filter(seg=in_audio, cutoff=85)- in_audio = low_pass_filter(seg=in_audio, cutoff=3000)-- # Always add the audio to the buffer- assert isinstance(in_audio.raw_data, bytes)- out_stream.write(in_audio.raw_data)+ out_chunck, is_speech = await echo_cancellation.pull_audio()- # Confirm ASAP that the event is processed- in_stream.task_done()+ # Add audio to the buffer+ out_stream.write(out_chunck)- # Use WebRTC VAD algorithm to detect voice- in_empty = False- if not vad.is_speech(- buf=in_audio.raw_data,- sample_rate=in_audio.frame_rate,- ):- in_empty = True+ # If no speech, init the silence task+ if not is_speech:# Start timeout if not already startedif not silence_task:- silence_task = asyncio.create_task(_silence_callback())-- if in_empty:+ silence_task = asyncio.create_task(_wait_for_silence())# Continue to the next audio packetcontinue- # Voice detected, cancel the timeout if any+ # Voice detected, cancel the timeout taskif silence_task:silence_task.cancel()silence_task = None# Start the TTS clear task- if not clear_tts_task:- clear_tts_task = asyncio.create_task(_clear_tts_callback())+ if not stop_task:+ stop_task = asyncio.create_task(_wait_for_stop())def _tts_callback(diff --git a/app/helpers/call_utils.py b/app/helpers/call_utils.pyindex 766b5ce..67e0533 100644--- a/app/helpers/call_utils.py+++ b/app/helpers/call_utils.py@@ -5,11 +5,13 @@ from collections.abc import AsyncGenerator, Awaitable, Callable, Generatorfrom contextlib import asynccontextmanager, contextmanager, suppressfrom enum import Enum+import numpy as npfrom aiojobs import Job, Schedulerfrom azure.cognitiveservices.speech import (AudioConfig,SpeechConfig,SpeechRecognizer,+ SpeechSynthesisOutputFormat,SpeechSynthesizer,)from azure.cognitiveservices.speech.audio import (@@ -34,9 +36,11 @@ from azure.communication.callautomation.aio import (CallConnectionClient,)from azure.core.exceptions import HttpResponseError, ResourceNotFoundError+from noisereduce import reduce_noisefrom app.helpers.cache import async_lru_cachefrom app.helpers.config import CONFIG+from app.helpers.features import vad_thresholdfrom app.helpers.identity import tokenfrom app.helpers.logging import loggerfrom app.models.call import CallStateModel@@ -70,13 +74,24 @@ class TtsCallback(PushAudioOutputStreamCallback):Callback for Azure Speech Synthesizer to push audio data to a queue."""- def __init__(self, queue: asyncio.Queue[bytes | bool]):+ def __init__(self, queue: asyncio.Queue[bytes]):self.queue = queuedef write(self, audio_buffer: memoryview) -> int:+ """+ Write audio data to the queue.+ """self.queue.put_nowait(audio_buffer.tobytes())return audio_buffer.nbytes+ def close(self) -> None:+ """+ Close the callback.+ """+ while not self.queue.empty():+ self.queue.get_nowait()+ self.queue.task_done()+class ContextEnum(str, Enum):"""@@ -523,11 +538,15 @@ async def _use_call_client(@asynccontextmanagerasync def use_tts_client(- audio: asyncio.Queue[bytes | bool],call: CallStateModel,+ out: asyncio.Queue[bytes],) -> AsyncGenerator[SpeechSynthesizer, None]:"""Use a text-to-speech client for a call.++ Output format is in PCM 16-bit, 16 kHz, 1 channel.++ Yields a client to push audio data to the queue. Once the context is exited, the client will stop."""# Get AAD tokenaad_token = await (await token("https://cognitiveservices.azure.com/.default"))()@@ -536,19 +555,21 @@ async def use_tts_client(# TODO: Use v2 endpoint (https://learn.microsoft.com/en-us/azure/ai-services/speech-service/how-to-lower-speech-synthesis-latency?pivots=programming-language-python#how-to-use-text-streaming) but seems compatible with AAD auth? Found nothing in the docs (https://github.com/Azure-Samples/cognitive-services-speech-sdk/blob/e392c9ca09d44ebd65081e7cb44593a2b16cd5a7/samples/python/web/avatar/app.py#L137).config = SpeechConfig(endpoint=f"wss://{CONFIG.cognitive_service.region}.tts.speech.microsoft.com/cognitiveservices/websocket/v1",+ speech_recognition_language=call.lang.short_code,)config.authorization_token = (f"aad#{CONFIG.cognitive_service.resource_id}#{aad_token}")config.speech_synthesis_voice_name = call.lang.voice+ config.set_speech_synthesis_output_format(+ SpeechSynthesisOutputFormat.Raw16Khz16BitMonoPcm+ )if call.lang.custom_voice_endpoint_id:config.endpoint_id = call.lang.custom_voice_endpoint_id# TODO: How to close the client?client = SpeechSynthesizer(speech_config=config,- audio_config=AudioOutputConfig(- stream=PushAudioOutputStream(TtsCallback(audio))- ),+ audio_config=AudioOutputConfig(stream=PushAudioOutputStream(TtsCallback(out))),)# Connect events@@ -561,15 +582,16 @@ async def use_tts_client(@asynccontextmanagerasync def use_stt_client(- audio_bits_per_sample: int,- audio_channels: int,audio_sample_rate: int,call: CallStateModel,- callback: Callable[[str], None],+ complete_callback: Callable[[str], None],+ partial_callback: Callable[[str], None],) -> AsyncGenerator[PushAudioInputStream, None]:"""Use a speech-to-text client for a call.+ Input format is in PCM 16-bit, 16 kHz, 1 channel.+Yields a stream to push audio data to the client. Once the context is exited, the client will stop."""# Get AAD token@@ -577,9 +599,10 @@ async def use_stt_client(# Create clientstream = PushAudioInputStream(+ # PCM 16-bit, 1 channelstream_format=AudioStreamFormat(- bits_per_sample=audio_bits_per_sample,- channels=audio_channels,+ bits_per_sample=16,+ channels=1,samples_per_second=audio_sample_rate,),)@@ -592,11 +615,18 @@ async def use_stt_client(),)- # Connect events- client.recognized.connect(lambda e: callback(e.result.text))+ # TSS events+ client.recognized.connect(+ lambda e: complete_callback(e.result.text) if e.result.text else None+ )+ client.recognizing.connect(+ lambda e: partial_callback(e.result.text) if e.result.text else None+ )++ # Debugging events+ client.canceled.connect(lambda event: logger.warning("STT cancelled: %s", event))client.session_started.connect(lambda _: logger.debug("STT started"))client.session_stopped.connect(lambda _: logger.debug("STT stopped"))- client.canceled.connect(lambda event: logger.warning("STT cancelled: %s", event))try:# Start STT@@ -606,3 +636,184 @@ async def use_stt_client(finally:# Stop STTclient.stop_continuous_recognition_async()+++class EchoCancellationStream:+ """+ Real-time audio stream with echo cancellation.++ Input and output formats are in PCM 16-bit, 16 kHz, 1 channel.+ """++ _chunk_size: int+ _input_queue: asyncio.Queue[bytes] = asyncio.Queue()+ _output_queue: asyncio.Queue[tuple[bytes, bool]] = asyncio.Queue()+ _packet_duration_ms: int+ _packet_size: int+ _reference_queue: asyncio.Queue[bytes] = asyncio.Queue()+ _sample_rate: int++ def __init__(+ self,+ sample_rate: int,+ max_delay_ms: int = 200,+ packet_duration_ms: int = 20,+ ):+ self._packet_duration_ms = packet_duration_ms+ self._sample_rate = sample_rate++ max_delay_samples = int(max_delay_ms / 1000 * self._sample_rate)+ self._bot_voice_buffer = np.zeros(max_delay_samples, dtype=np.float32)++ self._chunk_size = int(self._sample_rate * self._packet_duration_ms / 1000)+ self._packet_size = self._chunk_size * 2 # Each sample is 2 bytes (PCM 16-bit)++ def _pcm_to_float(self, pcm: bytes) -> np.ndarray:+ """+ Convert PCM 16-bit to float (-1.0 to 1.0).+ """+ return (+ np.frombuffer(+ buffer=pcm,+ dtype=np.int16,+ ).astype(np.float32)+ / 32768.0+ )++ def _float_to_pcm(self, floats: np.ndarray) -> bytes:+ """+ Convert float (-1.0 to 1.0) to PCM 16-bit.+ """+ pcm = (floats * 32767).clip(-32768, 32767).astype(np.int16)+ return pcm.tobytes()++ def _update_input_buffer(self, voice: np.ndarray) -> None:+ """+ Update the rolling buffer for the input voice.+ """+ buffer_length = len(self._bot_voice_buffer)+ reference_length = len(voice)++ if reference_length >= buffer_length:+ # If the reference is longer than the buffer, keep the most recent samples+ self._bot_voice_buffer = voice[-buffer_length:]+ else:+ # Append new samples and keep the buffer size fixed+ self._bot_voice_buffer = np.roll(self._bot_voice_buffer, -reference_length)+ self._bot_voice_buffer[-reference_length:] = voice++ async def _rms_speech_detection(self, voice: np.ndarray) -> bool:+ """+ Simple speech detection based on RMS (acoustic pressure).++ Returns True if speech is detected, False otherwise.+ """+ # Calculate Root Mean Square (RMS)+ rms = np.sqrt(np.mean(voice**2))+ # Get VAD threshold, divide by 10 to more usability from user side, as RMS is in range 0-1 and a detection of 0.1 is a good maximum threshold+ threshold = await vad_threshold() / 10+ return rms >= threshold++ async def _process_one(self, input_pcm: bytes) -> None:+ """+ Process one audio chunk with echo cancellation.+ """+ # Use silence as the reference if none is available+ if self._reference_queue.empty():+ reference_pcm = b"\x00" * self._packet_size+ else:+ reference_pcm = await self._reference_queue.get()+ self._reference_queue.task_done()++ # Convert PCM to float for processing+ input_signal = self._pcm_to_float(input_pcm)+ reference_signal = self._pcm_to_float(reference_pcm)++ # Update the input buffer with the reference signal+ self._update_input_buffer(reference_signal)++ # Apply noise reduction+ reduced_signal = reduce_noise(+ # Input signal+ clip_noise_stationary=False,+ sr=self._sample_rate,+ y=input_signal,+ # Performance+ n_fft=self._chunk_size,+ # Since the reference signal is already noise-reduced, we can assume it's stationary+ stationary=True,+ y_noise=self._bot_voice_buffer,+ # Output quality+ prop_decrease=0.75, # Reduce noise by 75%+ )++ # Perform VAD test+ input_speaking = await self._rms_speech_detection(reduced_signal)++ # Convert processed float signal back to PCM+ processed_pcm = self._float_to_pcm(reduced_signal)++ # Add processed PCM and metadata to the output queue+ await self._output_queue.put((processed_pcm, input_speaking))++ async def process_stream(self) -> None:+ """+ Process the audio stream in real-time.+ """+ async with Scheduler(+ limit=5, # Allow 5 concurrent tasks+ ) as scheduler:+ while True:+ # Fetch input audio+ input_pcm = await self._input_queue.get()+ self._input_queue.task_done()++ # Queue the processing+ await scheduler.spawn(+ asyncio.wait_for(+ self._process_one(input_pcm),+ timeout=self._packet_duration_ms+ / 1000+ * 5, # Allow temporary high latency+ )+ )++ async def push_input(self, audio_data: bytes) -> None:+ """+ Push PCM input audio into the input queue.+ """+ if len(audio_data) != self._packet_size:+ raise ValueError(+ f"Expected packet size {self._packet_size} bytes, got {len(audio_data)} bytes."+ )+ await self._input_queue.put(audio_data)++ async def push_reference(self, audio_data: bytes) -> None:+ """+ Push PCM reference audio into the reference queue.++ The reference audio is used for echo cancellation.+ """+ # Extract packets and pad them if necessary+ buffer_pointer = 0+ while buffer_pointer < len(audio_data):+ chunk = audio_data[: self._packet_size].ljust(self._packet_size, b"\x00")+ await self._reference_queue.put(chunk)+ buffer_pointer += self._packet_size++ async def pull_audio(self) -> tuple[bytes, bool]:+ """+ Pull processed PCM audio and metadata from the output queue.++ Returns a tuple with the echo-cancelled PCM audio and a boolean flag indicating if the user was speaking.+ """+ # return await self._output_queue.get()+ try:+ return await asyncio.wait_for(+ fut=self._output_queue.get(),+ timeout=self._packet_duration_ms+ / 1000+ * 1.5, # Allow temporary small latency+ )+ except TimeoutError:+ return b"\x00" * self._packet_size, False # Silence PCM chunk and no speechdiff --git a/app/helpers/features.py b/app/helpers/features.pyindex cd9cd3a..392f773 100644--- a/app/helpers/features.py+++ b/app/helpers/features.py@@ -18,42 +18,103 @@ T = TypeVar("T", bool, int, float, str)async def answer_hard_timeout_sec() -> int:- return await _get(key="answer_hard_timeout_sec", type_res=int) or 180+ return await _default(+ default=180,+ key="answer_hard_timeout_sec",+ type_res=int,+ )async def answer_soft_timeout_sec() -> int:- return await _get(key="answer_soft_timeout_sec", type_res=int) or 120+ return await _default(+ default=120,+ key="answer_soft_timeout_sec",+ type_res=int,+ )async def callback_timeout_hour() -> int:- return await _get(key="callback_timeout_hour", type_res=int) or 24+ return await _default(+ default=24,+ key="callback_timeout_hour",+ type_res=int,+ )async def phone_silence_timeout_sec() -> int:- return await _get(key="phone_silence_timeout_sec", type_res=int) or 20+ return await _default(+ default=20,+ key="phone_silence_timeout_sec",+ type_res=int,+ )+++async def vad_threshold() -> float:+ return await _default(+ default=0.5,+ key="vad_threshold",+ type_res=float,+ )async def vad_silence_timeout_ms() -> int:- return await _get(key="vad_silence_timeout_ms", type_res=int) or 400+ return await _default(+ default=400,+ key="vad_silence_timeout_ms",+ type_res=int,+ )async def vad_cutoff_timeout_ms() -> int:- return await _get(key="vad_cutoff_timeout_ms", type_res=int) or 600+ return await _default(+ default=600,+ key="vad_cutoff_timeout_ms",+ type_res=int,+ )async def recording_enabled() -> bool:- return await _get(key="recording_enabled", type_res=bool) or False+ return await _default(+ default=False,+ key="recording_enabled",+ type_res=bool,+ )async def slow_llm_for_chat() -> bool:- return await _get(key="slow_llm_for_chat", type_res=bool) or True+ return await _default(+ default=True,+ key="slow_llm_for_chat",+ type_res=bool,+ )async def recognition_retry_max() -> int:- return await _get(key="recognition_retry_max", type_res=int) or 3+ return await _default(+ default=3,+ key="recognition_retry_max",+ type_res=int,+ )-async def _get(key: str, type_res: type[T]) -> T | None:+async def _default(+ default: T,+ key: str,+ type_res: type[T],+) -> T:+ """+ Get a setting from the App Configuration service with a default value.+ """+ return (await _get(key=key, type_res=type_res)) or default+++async def _get(+ key: str,+ type_res: type[T],+) -> T | None:+ """+ Get a setting from the App Configuration service.+ """# Try cachecache_key = _cache_key(key)cached = await _cache.get(cache_key)@@ -99,10 +160,18 @@ async def _use_client() -> AzureAppConfigurationClient:def _cache_key(key: str) -> str:+ """+ Generate a cache key for a setting.+ """return f"{__name__}-{key}"def _parse(value: str, type_res: type[T]) -> T | None:+ """+ Parse a setting value to a type.++ Supported types: bool, int, float, str.+ """with suppress(ValueError):if type_res is bool:return cast(T, value.lower() == "true")diff --git a/app/main.py b/app/main.pyindex fd3b2b8..0ffdaf4 100644--- a/app/main.py+++ b/app/main.py@@ -612,6 +612,7 @@ async def communicationservices_wss_post(with suppress(WebSocketDisconnect):while True:audio_data = await audio_out.get()+ audio_out.task_done()# Send audioif isinstance(audio_data, bytes):await websocket.send_json(@@ -630,7 +631,6 @@ async def communicationservices_wss_post("stopAudio": {},})- audio_out.task_done()async with get_scheduler() as scheduler:await asyncio.gather(@@ -641,8 +641,6 @@ async def communicationservices_wss_post(# Process audio# TODO: Dynamically set the audio formaton_audio_connected(- audio_bits_per_sample=16,- audio_channels=1,audio_in=audio_in,audio_out=audio_out,audio_sample_rate=16000,diff --git a/cicd/bicep/app.bicep b/cicd/bicep/app.bicepindex 37c7e42..16e60eb 100644--- a/cicd/bicep/app.bicep+++ b/cicd/bicep/app.bicep@@ -909,6 +909,7 @@ resource configValues 'Microsoft.AppConfiguration/configurationStores/keyValues@slow_llm_for_chat: falsevad_cutoff_timeout_ms: 600vad_silence_timeout_ms: 400+ vad_threshold: '0.5'}): {parent: configStorename: item.keydiff --git a/pyproject.toml b/pyproject.tomlindex bd1d2a5..7fd75e1 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -26,6 +26,7 @@ dependencies = ["jinja2~=3.1", # Template engine, used for prompts and web views"json-repair~=0.30", # Repair JSON files from LLM"mistune~=3.0", # Markdown parser for web views+ "noisereduce~=3.0", # Noise reduction"openai~=1.52", # OpenAI client"opentelemetry-instrumentation-aiohttp-client~=0.0a0", # OpenTelemetry instrumentation for aiohttp client"opentelemetry-instrumentation-httpx~=0.0a0", # OpenTelemetry instrumentation for HTTPX@@ -36,7 +37,6 @@ dependencies = ["pydantic-extra-types~=2.9", # Extra types for Pydantic"pydantic-settings~=2.6", # Application configuration management with Pydantic"pydantic[email]~=2.9", # Data serialization and validation, plus email validation- "pydub~=0.25", # Audio processing with FFmpeg"pyjwt~=2.9", # Secure inbound calls from Communication Services"python-dotenv~=1.0", # Load environment variables from .env file"python-multipart==0.*", # Form parsing@@ -49,7 +49,6 @@ dependencies = ["twilio~=9.3", # Twilio SDK, used for SMS"typing-extensions~=4.12", # Typing extensions for Python 3.6+"uvicorn[standard]~=0.32", # Application middleware- "webrtcvad~=2.0", # Voice activity detection][project.optional-dependencies]