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

ux: Repeat asking lang if not selected

Clémence Lesnéf0062f2a6213
diff --git a/function_app.py b/function_app.py
index e4e8033..25dd3cf 100644
--- a/function_app.py
+++ b/function_app.py
@@ -30,10 +30,10 @@ from helpers.call_events import (
on_new_call,
on_play_completed,
on_play_error,
+ on_recognize_timeout_error,
+ on_recognize_unknown_error,
on_sms_received,
on_speech_recognized,
- on_speech_timeout_error,
- on_speech_unknown_error,
on_transfer_completed,
on_transfer_error,
)
@@ -487,19 +487,22 @@ async def _communicationservices_event_worker(
): # Speech recognition failed
result_information = event.data["resultInformation"]
error_code: int = result_information["subCode"]
-
+ error_message: str = result_information["message"]
+ logger.debug(
+ f"Speech recognition failed with error code {error_code}: {error_message}"
+ )
# Error codes:
# 8510 = Action failed, initial silence timeout reached
# 8532 = Action failed, inter-digit silence timeout reached
# See: https://github.com/MicrosoftDocs/azure-docs/blob/main/articles/communication-services/how-tos/call-automation/recognize-action.md#event-codes
if error_code in (8510, 8532): # Timeout retry
- await on_speech_timeout_error(
+ await on_recognize_timeout_error(
call=call,
client=automation_client,
contexts=operation_contexts,
)
else: # Unknown error
- await on_speech_unknown_error(
+ await on_recognize_unknown_error(
call=call,
client=automation_client,
error_code=error_code,
diff --git a/helpers/call_events.py b/helpers/call_events.py
index 00860e0..836a5ec 100644
--- a/helpers/call_events.py
+++ b/helpers/call_events.py
@@ -76,7 +76,7 @@ async def on_call_connected(
call: CallStateModel,
client: CallAutomationClient,
) -> None:
- logger.info("Call connected")
+ logger.info("Call connected, asking for language")
call.voice_recognition_retry = 0 # Reset recognition retry counter
call.messages.append(
MessageModel(
@@ -136,38 +136,74 @@ async def on_speech_recognized(
) # All in parallel to lower the answer latency
[email protected]_as_current_span("on_speech_timeout_error")
-async def on_speech_timeout_error(
[email protected]_as_current_span("on_recognize_timeout_error")
+async def on_recognize_timeout_error(
call: CallStateModel,
client: CallAutomationClient,
contexts: Optional[list[CallContextEnum]],
) -> None:
- if not (contexts and CallContextEnum.LAST_CHUNK in contexts):
+ if (
+ contexts and CallContextEnum.IVR_LANG_SELECT in contexts
+ ): # Retry IVR recognition
+ if call.voice_recognition_retry < CONFIG.workflow.max_voice_recognition_retry:
+ call.voice_recognition_retry += 1
+ logger.info(
+ f"Timeout, retrying language selection ({call.voice_recognition_retry}/{CONFIG.workflow.max_voice_recognition_retry})"
+ )
+ await _handle_ivr_language(call=call, client=client)
+ else: # IVR retries are exhausted, end call
+ logger.info("Timeout, ending call")
+ await _handle_goodbye(
+ call=call,
+ client=client,
+ )
+ return
+
+ if not (
+ contexts and CallContextEnum.LAST_CHUNK in contexts
+ ): # Not the last chunk, ignore
logger.debug("Ignoring timeout if bot is still speaking")
return
- res_context = None
- if call.voice_recognition_retry < 10:
+ if (
+ call.voice_recognition_retry < CONFIG.workflow.max_voice_recognition_retry
+ ): # Retry voice recognition
call.voice_recognition_retry += 1
- timeout_error = True # Should re-trigger an error or the LLM
- text = await CONFIG.prompts.tts.timeout_silence(call)
- else:
- timeout_error = False # Shouldn't trigger anything, as call is ending
- res_context = CallContextEnum.GOODBYE
- text = await CONFIG.prompts.tts.goodbye(call)
+ logger.info(
+ f"Timeout, retrying voice recognition ({call.voice_recognition_retry}/{CONFIG.workflow.max_voice_recognition_retry})"
+ )
+ await handle_recognize_text(
+ call=call,
+ client=client,
+ store=False, # Do not store timeout prompt as it perturbs the LLM and makes it hallucinate
+ text=await CONFIG.prompts.tts.timeout_silence(call),
+ timeout_error=True, # Should re-trigger an error or the LLM
+ )
+
+ else: # Voice retries are exhausted, end call
+ logger.info("Timeout, ending call")
+ await _handle_goodbye(
+ call=call,
+ client=client,
+ )
+
+async def _handle_goodbye(
+ call: CallStateModel,
+ client: CallAutomationClient,
+) -> None:
await handle_recognize_text(
call=call,
client=client,
- context=res_context,
+ context=CallContextEnum.GOODBYE,
store=False, # Do not store timeout prompt as it perturbs the LLM and makes it hallucinate
- text=text,
- timeout_error=timeout_error,
+ text=await CONFIG.prompts.tts.goodbye(call),
+ timeout_error=False,
)
[email protected]_as_current_span("on_speech_unknown_error")
-async def on_speech_unknown_error(
[email protected]_as_current_span("on_recognize_unknown_error")
+async def on_recognize_unknown_error(
call: CallStateModel,
client: CallAutomationClient,
error_code: int,
@@ -512,7 +548,8 @@ async def _handle_ivr_language(
)
await handle_recognize_ivr(
call=call,
- client=client,
choices=choices,
+ client=client,
+ context=CallContextEnum.IVR_LANG_SELECT,
text=await CONFIG.prompts.tts.ivr_language(call),
)
diff --git a/helpers/call_utils.py b/helpers/call_utils.py
index 6d27f9c..4695c5f 100644
--- a/helpers/call_utils.py
+++ b/helpers/call_utils.py
@@ -41,6 +41,7 @@ class ContextEnum(str, Enum):
CONNECT_AGENT = "connect_agent" # Transfer to agent
GOODBYE = "goodbye" # Hang up
+ IVR_LANG_SELECT = "ivr_lang_select" # IVR language selection
LAST_CHUNK = "last_chunk" # Last chunk of text
TRANSFER_FAILED = "transfer_failed" # Transfer failed
@@ -277,10 +278,11 @@ def _audio_from_text(
async def handle_recognize_ivr(
- client: CallAutomationClient,
call: CallStateModel,
- text: str,
choices: list[RecognitionChoice],
+ client: CallAutomationClient,
+ text: str,
+ context: Optional[ContextEnum] = None,
) -> None:
"""
Recognize an IVR response after playing a text.
@@ -294,9 +296,9 @@ async def handle_recognize_ivr(
async with _use_call_client(client, call.voice_id) as call_client:
await call_client.start_recognizing_media(
choices=choices,
- end_silence_timeout=20,
input_type=RecognizeInputType.CHOICES,
interrupt_prompt=True,
+ operation_context=json.dumps([context]) if context else None,
play_prompt=_audio_from_text(
call=call,
style=MessageStyleEnum.NONE,
diff --git a/helpers/config_models/workflow.py b/helpers/config_models/workflow.py
index 5159cda..7633cfc 100644
--- a/helpers/config_models/workflow.py
+++ b/helpers/config_models/workflow.py
@@ -131,6 +131,7 @@ class WorkflowModel(BaseModel):
initiate: WorkflowInitiateModel
intelligence_hard_timeout_sec: int = 180 # 3 minutes
intelligence_soft_timeout_sec: int = 30 # 30 seconds
+ max_voice_recognition_retry: int = 3
def _fields_to_pydantic(name: str, fields: list[ClaimFieldModel]) -> type[BaseModel]:
diff --git a/models/call.py b/models/call.py
index e58122a..97da075 100644
--- a/models/call.py
+++ b/models/call.py
@@ -80,7 +80,7 @@ class CallStateModel(CallGetModel):
lang_short_code: Optional[str] = Field(default=None)
voice_recognition_retry: int = Field(
default=0,
- validation_alias="recognition_retry", # Compatibility with v1
+ serialization_alias="recognition_retry", # Compatibility with v1
)
@computed_field