Skip to content

Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!

Python

feat: Close call is no sound for a repeated time

Clémence Lesné56bef1b836a6
diff --git a/README.md b/README.md
index cb3c75d..4b13cd5 100644
--- a/README.md
+++ b/README.md
@@ -627,6 +627,7 @@ Conversation options are represented as features. They can be configured from Ap
| `answer_hard_timeout_sec` | The hard timeout for the bot answer in seconds. | `int` | 180 |
| `answer_soft_timeout_sec` | The soft timeout for the bot answer in seconds. | `int` | 30 |
| `callback_timeout_hour` | The timeout for a callback in hours. | `int` | 3 |
+| `phone_silence_timeout_sec` | The timeout for phone silence in seconds. | `int` | 10 |
| `recognition_retry_max` | The maximum number of retries for voice recognition. | `int` | 2 |
| `recording_enabled` | Whether call recording is enabled. | `bool` | false |
| `slow_llm_for_chat` | Whether to use the slow LLM for chat. | `bool` | false |
diff --git a/app/helpers/call_events.py b/app/helpers/call_events.py
index 9b27c87..c7738ca 100644
--- a/app/helpers/call_events.py
+++ b/app/helpers/call_events.py
@@ -172,12 +172,10 @@ async def on_recognize_error(
client: CallAutomationClient,
contexts: set[CallContextEnum] | None,
) -> None:
- if (
- contexts and CallContextEnum.IVR_LANG_SELECT in contexts
- ): # Retry IVR recognition
+ # Retry IVR recognition
+ if contexts and CallContextEnum.IVR_LANG_SELECT in contexts:
span_attribute(CallAttributes.CALL_CHANNEL, "ivr")
if call.recognition_retry < await recognition_retry_max():
- call.recognition_retry += 1
logger.info(
"Timeout, retrying language selection (%s/%s)",
call.recognition_retry,
@@ -195,9 +193,8 @@ async def on_recognize_error(
)
return
- if (
- call.recognition_retry >= await recognition_retry_max()
- ): # Voice retries are exhausted, end call
+ # Voice retries are exhausted, end call
+ if call.recognition_retry >= await recognition_retry_max():
logger.info("Timeout, ending call")
await _handle_goodbye(
call=call,
@@ -205,6 +202,17 @@ async def on_recognize_error(
)
return
+ # Increment the recognition retry counter
+ call.recognition_retry += 1
+
+ # Play a timeout prompt
+ await handle_play_text(
+ call=call,
+ client=client,
+ style=MessageStyleEnum.NONE,
+ text=await CONFIG.prompts.tts.timeout_silence(call),
+ )
+
async def _handle_goodbye(
call: CallStateModel,
diff --git a/app/helpers/call_llm.py b/app/helpers/call_llm.py
index bedb1cd..5ef3418 100644
--- a/app/helpers/call_llm.py
+++ b/app/helpers/call_llm.py
@@ -28,6 +28,7 @@ from app.helpers.config import CONFIG
from app.helpers.features import (
answer_hard_timeout_sec,
answer_soft_timeout_sec,
+ phone_silence_timeout_sec,
vad_cutoff_timeout_ms,
vad_silence_timeout_ms,
)
@@ -118,6 +119,20 @@ async def load_llm_chat( # noqa: PLR0913
last_response: aiojobs.Job | None = None
async with aiojobs.Scheduler() as scheduler:
+ async def _timeout_callback() -> None:
+ from app.helpers.call_events import on_recognize_error
+
+ logger.info("Phone silence timeout triggered")
+
+ # Execute business logic
+ await scheduler.spawn(
+ on_recognize_error(
+ call=call,
+ client=automation_client,
+ contexts=None,
+ )
+ )
+
async def _clear_audio_callback() -> None:
# Let 500ms to the TTS to be cleared
if last_response:
@@ -179,12 +194,13 @@ async def load_llm_chat( # noqa: PLR0913
out_stream=recognizer_stream,
response_callback=_response_callback,
sample_rate=audio_sample_rate,
+ timeout_callback=_timeout_callback,
)
# TODO: Refacto, this function is too long (and remove PLR0912/PLR0915 ignore)
@tracer.start_as_current_span("call_load_out_answer")
-async def _out_answer( # noqa: PLR0913, PLR0915
+async def _out_answer( # noqa: PLR0915
call: CallStateModel,
client: CallAutomationClient,
post_callback: Callable[[CallStateModel], Awaitable[None]],
@@ -356,7 +372,7 @@ async def _out_answer( # noqa: PLR0913, PLR0915
# TODO: Refacto, this function is too long
@tracer.start_as_current_span("call_execute_llm_chat")
-async def _execute_llm_chat( # noqa: PLR0913, PLR0911, PLR0912, PLR0915
+async def _execute_llm_chat( # noqa: PLR0911, PLR0912, PLR0915
call: CallStateModel,
client: CallAutomationClient,
post_callback: Callable[[CallStateModel], Awaitable[None]],
@@ -542,44 +558,75 @@ async def _in_audio( # noqa: PLR0913
out_stream: PushAudioInputStream,
response_callback: Callable[[], Awaitable[None]],
sample_rate: int,
+ timeout_callback: Callable[[], Awaitable[None]],
) -> None:
clear_tts_task: asyncio.Task | None = None
- flush_task: asyncio.Task | None = None
+ no_voice_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 _timeout_callback() -> None:
+ """
+ Alert the user that the call is about to be cut off.
+ """
+ timeout_sec = await phone_silence_timeout_sec()
+
+ while True:
+ logger.debug(
+ "Wait foor %i sec before cutting off the call",
+ timeout_sec,
+ )
+
+ # Wait for the timeout
+ await asyncio.sleep(timeout_sec)
+
+ logger.info("Phone silence timeout triggered")
+
+ # Execute the callback
+ await timeout_callback()
+
async def _flush_callback() -> None:
"""
Flush the audio buffer if no audio is detected for a while.
"""
nonlocal clear_tts_task
+ timeout_ms = await vad_silence_timeout_ms()
+
# Wait for the timeout
- await asyncio.sleep(await vad_silence_timeout_ms() / 1000)
+ await asyncio.sleep(timeout_ms / 1000)
# Cancel the TTS clear task if any
if clear_tts_task:
clear_tts_task.cancel()
clear_tts_task = None
- logger.debug("Timeout triggered, flushing audio buffer")
+ logger.debug("Flushing audio buffer after %i ms", timeout_ms)
# Commit the buffer
await response_callback()
+ async def _no_voice_callback() -> None:
+ await asyncio.gather(
+ _flush_callback(),
+ _timeout_callback(),
+ )
+
async def _clear_tts_callback() -> None:
"""
Clear the TTS queue.
Start is the index of the buffer where the TTS was triggered.
"""
+ timeout_ms = await vad_cutoff_timeout_ms()
+
# Wait before clearing the TTS queue
- await asyncio.sleep(await vad_cutoff_timeout_ms() / 1000)
+ await asyncio.sleep(timeout_ms / 1000)
- logger.debug("Voice detected, cancelling TTS")
+ logger.debug("Canceling TTS after %i ms", timeout_ms)
# Clear the queue
await clear_audio_callback()
@@ -615,18 +662,18 @@ async def _in_audio( # noqa: PLR0913
sample_rate=in_audio.frame_rate,
):
in_empty = True
- # Start timeout if not already started and VAD already triggered
- if not flush_task:
- flush_task = asyncio.create_task(_flush_callback())
+ # Start timeout if not already started
+ if not no_voice_task:
+ no_voice_task = asyncio.create_task(_no_voice_callback())
if in_empty:
# Continue to the next audio packet
continue
- # Voice detected, cancel the flush task if any
- if flush_task:
- flush_task.cancel()
- flush_task = None
+ # Voice detected, cancel the timeout if any
+ if no_voice_task:
+ no_voice_task.cancel()
+ no_voice_task = None
# Start the TTS clear task
if not clear_tts_task:
diff --git a/app/helpers/features.py b/app/helpers/features.py
index 755c22e..6342f5d 100644
--- a/app/helpers/features.py
+++ b/app/helpers/features.py
@@ -28,6 +28,10 @@ async def callback_timeout_hour() -> int:
return await _get(key="callback_timeout_hour", type_res=int) or 24
+async def phone_silence_timeout_sec() -> int:
+ return await _get(key="phone_silence_timeout_sec", type_res=int) or 10
+
+
async def vad_silence_timeout_ms() -> int:
return await _get(key="vad_silence_timeout_ms", type_res=int) or 400
diff --git a/cicd/bicep/app.bicep b/cicd/bicep/app.bicep
index 7cf3abd..f7b666f 100644
--- a/cicd/bicep/app.bicep
+++ b/cicd/bicep/app.bicep
@@ -902,6 +902,7 @@ resource configValues 'Microsoft.AppConfiguration/configurationStores/keyValues@
answer_hard_timeout_sec: 180
answer_soft_timeout_sec: 30
callback_timeout_hour: 3
+ phone_silence_timeout_sec: 10
recognition_retry_max: 2
recording_enabled: false
slow_llm_for_chat: false