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

perf: Use realtime TTS to lower answer latency

Clémence Lesnée2c772831689
diff --git a/README.md b/README.md
index caf97b1..82c817a 100644
--- a/README.md
+++ b/README.md
@@ -188,28 +188,29 @@ graph LR
redis[("Cache<br>(Redis)")]
search[("RAG<br>(AI Search)")]
sounds[("Sounds<br>(Azure Storage)")]
- sst["Speech-to-Text<br>(Cognitive Services)"]
+ sst["Speech-to-text<br>(Cognitive Services)"]
translation["Translation<br>(Cognitive Services)"]
- tts["Text-to-Speech<br>(Cognitive Services)"]
+ tts["Text-to-speech<br>(Cognitive Services)"]
end
- app -- Respond with text --> communication_services
- app -- Ask for translation --> translation
- app -- Ask to transfer --> communication_services
- app -- Few-shot training --> search
+ app -- Translate static TTS --> translation
+ app -- Sezarch RAG data --> search
app -- Generate completion --> gpt
+ gpt -. Answer with completion .-> app
+ app -- Generate voice --> tts
+ tts -. Answer with voice .-> app
app -- Get cached data --> redis
app -- Save conversation --> db
- app -- Send SMS report --> communication_services
+ app -- Transform voice --> sst
+ sst -. Answer with text .-> app
+ app <-. Exchange audio .-> communication_services
app -. Watch .-> queues
- communication_services -- Generate voice --> tts
communication_services -- Load sound --> sounds
communication_services -- Notifies --> eventgrid
- communication_services -- Send SMS --> user
communication_services -- Transfer to --> agent
- communication_services -- Transform voice --> sst
- communication_services -. Send voice .-> user
+ communication_services <-. Exchange audio .-> agent
+ communication_services <-. Exchange audio .-> user
eventgrid -- Push to --> queues
@@ -694,7 +695,7 @@ prompts:
The delay mainly come from two things:
-- The fact that Azure Communication Services is sequential in the way it forwards the audio (it technically foarwards only the text, not the audio, and once the entire audio is transformed, after waited for a specified blank time)
+- Voice in and voice out are processed by Azure AI Speech, both are implemented in streaming mode but voice is not directly streamed to the LLM
- The LLM, more specifically the delay between API call and first sentence infered, can be long (as the sentences are sent one by one once they are made avalable), even longer if it hallucinate and returns empty answers (it happens regularly, and the applicatoipn retries the call)
From now, the only impactful thing you can do is the LLM part. This can be acheieve by a PTU on Azure or using a less smart model like `gpt-4o-mini` (selected by default on the latest versions). With a PTU on Azure OpenAI, you can divide by 2 the latency in some case.
diff --git a/app/helpers/call_events.py b/app/helpers/call_events.py
index ea1e414..cde56e4 100644
--- a/app/helpers/call_events.py
+++ b/app/helpers/call_events.py
@@ -2,6 +2,10 @@ import asyncio
from collections.abc import Awaitable, Callable
from datetime import UTC, datetime
+from aiojobs import Scheduler
+from azure.cognitiveservices.speech import (
+ SpeechSynthesizer,
+)
from azure.communication.callautomation import (
AzureBlobContainerRecordingStorage,
DtmfTone,
@@ -21,10 +25,10 @@ from pydantic import ValidationError
from app.helpers.call_llm import load_llm_chat
from app.helpers.call_utils import (
ContextEnum as CallContextEnum,
+ handle_automation_tts,
handle_hangup,
- handle_play_text,
+ handle_realtime_tts,
handle_recognize_ivr,
- handle_transfer,
start_audio_streaming,
)
from app.helpers.config import CONFIG
@@ -66,6 +70,7 @@ async def on_new_call(
streaming_options = MediaStreamingOptions(
audio_channel_type=MediaStreamingAudioChannelType.UNMIXED,
content_type=MediaStreamingContentType.AUDIO,
+ enable_bidirectional=True,
start_media_streaming=False,
transport_type=MediaStreamingTransportType.WEBSOCKET,
transport_url=wss_url,
@@ -102,6 +107,8 @@ async def on_new_call(
async def on_call_connected(
call: CallStateModel,
client: CallAutomationClient,
+ post_callback: Callable[[CallStateModel], Awaitable[None]],
+ scheduler: Scheduler,
server_call_id: str,
) -> None:
"""
@@ -111,37 +118,43 @@ async def on_call_connected(
"""
logger.info("Call connected, asking for language")
- # Add define the call as in progress
- async with _db.call_transac(call):
- call.in_progress = True
- call.recognition_retry = 0
- call.messages.append(
- MessageModel(
- action=MessageActionEnum.CALL,
- content="",
- persona=MessagePersonaEnum.HUMAN,
- )
- )
-
# Execute business logic
await asyncio.gather(
_handle_ivr_language(
call=call,
client=client,
+ post_callback=post_callback,
+ scheduler=scheduler,
), # First, every time a call is answered, confirm the language
_handle_recording(
call=call,
client=client,
server_call_id=server_call_id,
- ), # Third, start recording the call
+ ), # Second, start recording the call
)
+ # Add define the call as in progress
+ async with _db.call_transac(
+ call=call,
+ scheduler=scheduler,
+ ):
+ call.in_progress = True
+ call.recognition_retry = 0
+ call.messages.append(
+ MessageModel(
+ action=MessageActionEnum.CALL,
+ content="",
+ persona=MessagePersonaEnum.HUMAN,
+ )
+ )
+
@tracer.start_as_current_span("on_call_disconnected")
async def on_call_disconnected(
call: CallStateModel,
client: CallAutomationClient,
post_callback: Callable[[CallStateModel], Awaitable[None]],
+ scheduler: Scheduler,
) -> None:
"""
Callback for when the call is disconnected.
@@ -149,10 +162,11 @@ async def on_call_disconnected(
Hangs up the call and stores the final message.
"""
logger.info("Call disconnected")
- await _handle_hangup(
+ await hangup_now(
call=call,
client=client,
post_callback=post_callback,
+ scheduler=scheduler,
)
@@ -160,111 +174,179 @@ async def on_call_disconnected(
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,
- audio_stream: asyncio.Queue[bytes],
call: CallStateModel,
client: CallAutomationClient,
post_callback: Callable[[CallStateModel], Awaitable[None]],
training_callback: Callable[[CallStateModel], Awaitable[None]],
+ scheduler: Scheduler,
) -> None:
"""
Callback for when the audio stream is connected.
+
+ Starts 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,
- audio_stream=audio_stream,
automation_client=client,
call=call,
post_callback=post_callback,
+ scheduler=scheduler,
training_callback=training_callback,
)
[email protected]_as_current_span("on_recognize_timeout_error")
-async def on_recognize_error(
[email protected]_as_current_span("on_automation_recognize_error")
+async def on_automation_recognize_error(
call: CallStateModel,
client: CallAutomationClient,
contexts: set[CallContextEnum] | None,
post_callback: Callable[[CallStateModel], Awaitable[None]],
+ scheduler: Scheduler,
) -> None:
+ """
+ Callback for when an automation recognition fails.
+
+ If the call should continue, increments the recognition retry counter and plays a timeout prompt. Else, hangs up the call.
+ """
+ if not await _pre_recognize_error(
+ call=call,
+ scheduler=scheduler,
+ ):
+ # Play TTS
+ await handle_automation_tts(
+ call=call,
+ client=client,
+ context=CallContextEnum.GOODBYE,
+ post_callback=post_callback,
+ scheduler=scheduler,
+ store=False, # Do not store timeout prompt as it perturbs the LLM and makes it hallucinate
+ text=await CONFIG.prompts.tts.goodbye(call),
+ )
+ return
+
+ # There are no retries with Call Automation SDK out of IVR recognition, as voice in-call is managed with raw audio in the LLM stack
+ if not contexts or CallContextEnum.IVR_LANG_SELECT not in contexts:
+ logger.warning("Unknown context %s, no action taken", contexts)
+
+ # Enrich span
+ span_attribute(CallAttributes.CALL_CHANNEL, "ivr")
+
# Retry IVR recognition
- if contexts and CallContextEnum.IVR_LANG_SELECT in contexts:
- # Enrich span
- span_attribute(CallAttributes.CALL_CHANNEL, "ivr")
-
- # Retry IVR recognition
- if call.recognition_retry < await recognition_retry_max():
- logger.info(
- "Timeout, retrying language selection (%s/%s)",
- call.recognition_retry,
- await recognition_retry_max(),
- )
- await _handle_ivr_language(
- call=call,
- client=client,
- )
+ logger.info(
+ "Timeout, retrying language selection (%s/%s)",
+ call.recognition_retry,
+ await recognition_retry_max(),
+ )
+ await _handle_ivr_language(
+ call=call,
+ client=client,
+ post_callback=post_callback,
+ scheduler=scheduler,
+ )
- # IVR retries are exhausted, end call
- else:
- logger.info("Timeout, ending call")
- await _handle_goodbye(
- call=call,
- client=client,
- post_callback=post_callback,
- )
- return
[email protected]_as_current_span("on_realtime_recognize_error")
+async def on_realtime_recognize_error(
+ call: CallStateModel,
+ client: CallAutomationClient,
+ post_callback: Callable[[CallStateModel], Awaitable[None]],
+ scheduler: Scheduler,
+ tts_client: SpeechSynthesizer,
+) -> None:
+ """
+ Callback for when a real-time recognition fails.
- # Voice retries are exhausted, end call
- if call.recognition_retry >= await recognition_retry_max():
- logger.info("Timeout, ending call")
- await _handle_goodbye(
+ If the call should continue, increments the recognition retry counter and plays a timeout prompt. Else, hangs up the call.
+ """
+ if not await _pre_recognize_error(
+ call=call,
+ scheduler=scheduler,
+ ):
+ await hangup_realtime_now(
call=call,
client=client,
post_callback=post_callback,
+ scheduler=scheduler,
+ tts_client=tts_client,
)
return
- # Increment the recognition retry counter
- async with _db.call_transac(call):
- call.recognition_retry += 1
-
# Play a timeout prompt
- await handle_play_text(
+ await handle_realtime_tts(
call=call,
- client=client,
- style=MessageStyleEnum.NONE,
+ scheduler=scheduler,
+ store=False,
text=await CONFIG.prompts.tts.timeout_silence(call),
+ tts_client=tts_client,
)
-async def _handle_goodbye(
+async def hangup_realtime_now(
call: CallStateModel,
client: CallAutomationClient,
post_callback: Callable[[CallStateModel], Awaitable[None]],
+ scheduler: Scheduler,
+ tts_client: SpeechSynthesizer,
) -> None:
- res = await handle_play_text(
+ """
+ Hangup the call and play a goodbye.
+ """
+ # Play TTS
+ await handle_realtime_tts(
call=call,
- client=client,
- context=CallContextEnum.GOODBYE,
+ scheduler=scheduler,
store=False, # Do not store timeout prompt as it perturbs the LLM and makes it hallucinate
text=await CONFIG.prompts.tts.goodbye(call),
+ tts_client=tts_client,
+ )
+ # TODO: Hack to avoid the call to close before TTS is played
+ await asyncio.sleep(10)
+ # Hangup
+ await hangup_now(
+ call=call,
+ client=client,
+ post_callback=post_callback,
+ scheduler=scheduler,
)
- if not res:
- logger.info("Failed to play goodbye prompt, ending call now")
- await _handle_hangup(
- call=call,
- client=client,
- post_callback=post_callback,
- )
+
+async def _pre_recognize_error(
+ call: CallStateModel,
+ scheduler: Scheduler,
+) -> bool:
+ """
+ Handle pre-recognition errors.
+
+ Tests if the call should continue after a recognition error. If yes, increments the recognition retry counter.
+
+ Returns True if the call should continue, False if it should end.
+ """
+ # Voice retries are exhausted, end call
+ if call.recognition_retry >= await recognition_retry_max():
+ logger.info("Timeout, ending call")
+ return False
+
+ # Increment the recognition retry counter
+ async with _db.call_transac(
+ call=call,
+ scheduler=scheduler,
+ ):
+ call.recognition_retry += 1
+
+ return True
@tracer.start_as_current_span("on_play_started")
async def on_play_started(
call: CallStateModel,
+ scheduler: Scheduler,
) -> None:
"""
Callback for when a media play action starts.
@@ -277,16 +359,20 @@ async def on_play_started(
span_attribute(CallAttributes.CALL_CHANNEL, "voice")
# Update last interaction
- async with _db.call_transac(call):
+ async with _db.call_transac(
+ call=call,
+ scheduler=scheduler,
+ ):
call.last_interaction_at = datetime.now(UTC)
@tracer.start_as_current_span("on_play_completed")
-async def on_play_completed(
+async def on_automation_play_completed(
call: CallStateModel,
client: CallAutomationClient,
contexts: set[CallContextEnum] | None,
post_callback: Callable[[CallStateModel], Awaitable[None]],
+ scheduler: Scheduler,
) -> None:
"""
Callback for when a media play action completes.
@@ -299,7 +385,10 @@ async def on_play_completed(
span_attribute(CallAttributes.CALL_CHANNEL, "voice")
# Update last interaction
- async with _db.call_transac(call):
+ async with _db.call_transac(
+ call=call,
+ scheduler=scheduler,
+ ):
call.last_interaction_at = datetime.now(UTC)
# Skip if no context data
@@ -312,20 +401,20 @@ async def on_play_completed(
or CallContextEnum.GOODBYE in contexts
):
logger.info("Ending call")
- await _handle_hangup(
+ await hangup_now(
call=call,
client=client,
post_callback=post_callback,
+ scheduler=scheduler,
)
return
- # Call transfer context
- if CallContextEnum.CONNECT_AGENT in contexts:
- logger.info("Initiating transfer call initiated")
- await handle_transfer(
+ # Start real-time
+ if CallContextEnum.START_REALTIME in contexts:
+ logger.info("Starting real-time")
+ await start_audio_streaming(
call=call,
client=client,
- target=call.initiate.agent_phone_number,
)
return
@@ -370,9 +459,13 @@ async def on_ivr_recognized(
call: CallStateModel,
client: CallAutomationClient,
label: str,
+ post_callback: Callable[[CallStateModel], Awaitable[None]],
+ scheduler: Scheduler,
) -> None:
"""
Callback for when an IVR recognition is successful.
+
+ Updates the call language and starts the real-time conversation with the LLM.
"""
logger.info("IVR recognized: %s", label)
@@ -391,42 +484,36 @@ async def on_ivr_recognized(
return
logger.info("Setting call language to %s", lang)
- async with _db.call_transac(call):
+ async with _db.call_transac(
+ call=call,
+ scheduler=scheduler,
+ ):
call.lang = lang.short_code
call.recognition_retry = 0
- if len(call.messages) <= 1: # First call, or only the call action
- await asyncio.gather(
- handle_play_text(
- call=call,
- client=client,
- text=await CONFIG.prompts.tts.hello(call),
- ), # First, greet the userwith the next message
- start_audio_streaming(
- call=call,
- client=client,
- ), # Second, the conversation with the LLM should start
- ) # All in parallel to lower the response latency
-
- else: # Returning call
- await asyncio.gather(
- handle_play_text(
- call=call,
- client=client,
- style=MessageStyleEnum.CHEERFUL,
- text=await CONFIG.prompts.tts.welcome_back(call),
- ), # First, welcome back the user
- start_audio_streaming(
- call=call,
- client=client,
- ), # Second, the conversation with the LLM should start
+ # First call
+ if len(call.messages) <= 1:
+ # Greet the userwith the next message
+ await handle_automation_tts(
+ call=call,
+ client=client,
+ context=CallContextEnum.START_REALTIME,
+ post_callback=post_callback,
+ scheduler=scheduler,
+ text=await CONFIG.prompts.tts.hello(call),
)
+ return
-
[email protected]_as_current_span("on_transfer_completed")
-async def on_transfer_completed() -> None:
- logger.info("Call transfer accepted event")
- # TODO: Is there anything to do here?
+ # Welcome back the user
+ await handle_automation_tts(
+ call=call,
+ client=client,
+ context=CallContextEnum.START_REALTIME,
+ post_callback=post_callback,
+ scheduler=scheduler,
+ style=MessageStyleEnum.CHEERFUL,
+ text=await CONFIG.prompts.tts.welcome_back(call),
+ )
@tracer.start_as_current_span("on_transfer_error")
@@ -434,6 +521,8 @@ async def on_transfer_error(
call: CallStateModel,
client: CallAutomationClient,
error_code: int,
+ post_callback: Callable[[CallStateModel], Awaitable[None]],
+ scheduler: Scheduler,
) -> None:
"""
Callback for when a call transfer fails.
@@ -441,10 +530,12 @@ async def on_transfer_error(
Logs the error and plays a TTS message to the user.
"""
logger.info("Error during call transfer, subCode %s", error_code)
- await handle_play_text(
+ await handle_automation_tts(
call=call,
client=client,
context=CallContextEnum.TRANSFER_FAILED,
+ post_callback=post_callback,
+ scheduler=scheduler,
text=await CONFIG.prompts.tts.calltransfer_failure(call),
)
@@ -453,6 +544,7 @@ async def on_transfer_error(
async def on_sms_received(
call: CallStateModel,
message: str,
+ scheduler: Scheduler,
) -> bool:
"""
Callback for when an SMS is received.
@@ -466,7 +558,10 @@ async def on_sms_received(
span_attribute(CallAttributes.CALL_MESSAGE, message)
# Add the SMS to the call history
- async with _db.call_transac(call):
+ async with _db.call_transac(
+ call=call,
+ scheduler=scheduler,
+ ):
call.messages.append(
MessageModel(
action=MessageActionEnum.SMS,
@@ -492,53 +587,72 @@ async def on_sms_received(
return True
-async def _handle_hangup(
+async def hangup_now(
call: CallStateModel,
client: CallAutomationClient,
post_callback: Callable[[CallStateModel], Awaitable[None]],
+ scheduler: Scheduler,
) -> None:
- await handle_hangup(client=client, call=call)
+ """
+ Hangup the call and store the final message.
+ """
- async with _db.call_transac(call):
- call.in_progress = False
- call.messages.append(
- MessageModel(
- action=MessageActionEnum.HANGUP,
- content="",
- persona=MessagePersonaEnum.HUMAN,
+ async def _store(call: CallStateModel) -> None:
+ async with _db.call_transac(
+ call=call,
+ scheduler=scheduler,
+ ):
+ call.in_progress = False
+ call.messages.append(
+ MessageModel(
+ action=MessageActionEnum.HANGUP,
+ content="",
+ persona=MessagePersonaEnum.HUMAN,
+ )
)
- )
- await post_callback(call)
+ await asyncio.gather(
+ handle_hangup(client=client, call=call),
+ _store(call),
+ post_callback(call),
+ )
async def on_end_call(
call: CallStateModel,
+ scheduler: Scheduler,
) -> None:
"""
Callback for when a call ends.
Generates post-call intelligence if the call had interactions.
"""
- if (
- len(call.messages) >= 3 # noqa: PLR2004
- and call.messages[-3].action == MessageActionEnum.CALL
- and call.messages[-2].persona == MessagePersonaEnum.ASSISTANT
- and call.messages[-1].action == MessageActionEnum.HANGUP
- ):
+ if not call.had_interaction():
logger.info(
"Call ended before any interaction, skipping post-call intelligence"
)
return
await asyncio.gather(
- _intelligence_next(call),
- _intelligence_sms(call),
- _intelligence_synthesis(call),
+ _intelligence_next(
+ call=call,
+ scheduler=scheduler,
+ ),
+ _intelligence_sms(
+ call=call,
+ scheduler=scheduler,
+ ),
+ _intelligence_synthesis(
+ call=call,
+ scheduler=scheduler,
+ ),
)
-async def _intelligence_sms(call: CallStateModel) -> None:
+async def _intelligence_sms(
+ call: CallStateModel,
+ scheduler: Scheduler,
+) -> None:
"""
Send an SMS report to the customer.
"""
@@ -575,7 +689,10 @@ async def _intelligence_sms(call: CallStateModel) -> None:
success = True
if success:
- async with _db.call_transac(call):
+ async with _db.call_transac(
+ call=call,
+ scheduler=scheduler,
+ ):
call.messages.append(
MessageModel(
action=MessageActionEnum.SMS,
@@ -585,7 +702,10 @@ async def _intelligence_sms(call: CallStateModel) -> None:
)
-async def _intelligence_synthesis(call: CallStateModel) -> None:
+async def _intelligence_synthesis(
+ call: CallStateModel,
+ scheduler: Scheduler,
+) -> None:
"""
Synthesize the call and store it to the model.
"""
@@ -612,11 +732,17 @@ async def _intelligence_synthesis(call: CallStateModel) -> None:
return
logger.info("Synthesis: %s", model)
- async with _db.call_transac(call):
+ async with _db.call_transac(
+ call=call,
+ scheduler=scheduler,
+ ):
call.synthesis = model
-async def _intelligence_next(call: CallStateModel) -> None:
+async def _intelligence_next(
+ call: CallStateModel,
+ scheduler: Scheduler,
+) -> None:
"""
Generate next action for the call.
"""
@@ -643,13 +769,18 @@ async def _intelligence_next(call: CallStateModel) -> None:
return
logger.info("Next action: %s", model)
- async with _db.call_transac(call):
+ async with _db.call_transac(
+ call=call,
+ scheduler=scheduler,
+ ):
call.next = model
async def _handle_ivr_language(
call: CallStateModel,
client: CallAutomationClient,
+ post_callback: Callable[[CallStateModel], Awaitable[None]],
+ scheduler: Scheduler,
) -> None:
"""
Handle IVR language selection.
@@ -664,6 +795,8 @@ async def _handle_ivr_language(
call=call,
client=client,
label=short_code,
+ post_callback=post_callback,
+ scheduler=scheduler,
)
return
diff --git a/app/helpers/call_llm.py b/app/helpers/call_llm.py
index fef9c4d..292e746 100644
--- a/app/helpers/call_llm.py
+++ b/app/helpers/call_llm.py
@@ -3,13 +3,11 @@ from collections.abc import Awaitable, Callable
from datetime import UTC, datetime, timedelta
from functools import wraps
-import aiojobs
+from aiojobs import Job, Scheduler
from azure.cognitiveservices.speech import (
- AudioConfig,
- SpeechConfig,
- SpeechRecognizer,
+ SpeechSynthesizer,
)
-from azure.cognitiveservices.speech.audio import AudioStreamFormat, PushAudioInputStream
+from azure.cognitiveservices.speech.audio import PushAudioInputStream
from azure.communication.callautomation.aio import CallAutomationClient
from openai import APIError
from pydub import AudioSegment
@@ -20,10 +18,11 @@ from pydub.effects import (
from webrtcvad import Vad
from app.helpers.call_utils import (
- handle_clear_queue,
handle_media,
- handle_play_text,
+ handle_realtime_tts,
tts_sentence_split,
+ use_stt_client,
+ use_tts_client,
)
from app.helpers.config import CONFIG
from app.helpers.features import (
@@ -33,7 +32,6 @@ from app.helpers.features import (
vad_cutoff_timeout_ms,
vad_silence_timeout_ms,
)
-from app.helpers.identity import token
from app.helpers.llm_tools import DefaultPlugin
from app.helpers.llm_worker import (
MaximumTokensReachedError,
@@ -61,122 +59,106 @@ _db = CONFIG.database.instance()
async def load_llm_chat( # 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,
- audio_stream: asyncio.Queue[bytes],
automation_client: CallAutomationClient,
call: CallStateModel,
post_callback: Callable[[CallStateModel], Awaitable[None]],
+ scheduler: Scheduler,
training_callback: Callable[[CallStateModel], Awaitable[None]],
) -> None:
# Init language recognition
- speech_token = await (await token("https://cognitiveservices.azure.com/.default"))()
- recognizer_buffer: list[str] = []
- recognizer_complete_gate = asyncio.Event()
- recognizer_stream = PushAudioInputStream(
- stream_format=AudioStreamFormat(
- bits_per_sample=audio_bits_per_sample,
- channels=audio_channels,
- samples_per_second=audio_sample_rate,
- ),
- )
- recognizer_config = SpeechConfig(
- auth_token=f"aad#{CONFIG.cognitive_service.resource_id}#{speech_token}",
- region=CONFIG.cognitive_service.region,
- )
- # recognizer_config.set_property(PropertyId.Speech_LogFilename, f"speech-{uuid4()}.log")
- recognizer_client = SpeechRecognizer(
- audio_config=AudioConfig(stream=recognizer_stream),
- language=call.lang.short_code,
- speech_config=recognizer_config,
- )
+ stt_buffer: list[str] = []
+ stt_complete_gate = asyncio.Event()
- def _handle_complete_recognition(text: str) -> None:
+ def _stt_callback(text: str) -> None:
# Skip if no text
if not text:
return
- recognizer_buffer.append(text)
- logger.debug("Complete recognition: %s", recognizer_buffer)
+ stt_buffer.append(text)
+ logger.debug("Complete recognition: %s", stt_buffer)
# Open the recognition gate
- recognizer_complete_gate.set()
-
- # Register callback and start recognition
- recognizer_client.recognized.connect(
- lambda e: _handle_complete_recognition(e.result.text)
- )
- recognizer_client.session_started.connect(
- lambda _: logger.debug("Recognition started")
- )
- recognizer_client.session_stopped.connect(
- lambda _: logger.debug("Recognition stopped")
- )
- recognizer_client.canceled.connect(
- lambda event: logger.warning("Recognition cancelled: %s", event)
- )
- recognizer_client.start_continuous_recognition_async()
+ stt_complete_gate.set()
- # Build scheduler
- last_response: aiojobs.Job | None = None
- async with aiojobs.Scheduler() as scheduler:
+ async 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,
+ ) as stt_stream,
+ use_tts_client(
+ audio=audio_out,
+ call=call,
+ ) as tts_client,
+ ):
+ # Build scheduler
+ last_response: Job | None = None
async def _timeout_callback() -> None:
- from app.helpers.call_events import on_recognize_error
+ from app.helpers.call_events import on_realtime_recognize_error
logger.info("Phone silence timeout triggered")
# Execute business logic
await scheduler.spawn(
- on_recognize_error(
+ on_realtime_recognize_error(
call=call,
client=automation_client,
- contexts=None,
post_callback=post_callback,
+ scheduler=scheduler,
+ tts_client=tts_client,
)
)
async def _clear_audio_callback() -> None:
- # Let 500ms to the TTS to be cleared
- if last_response:
- await scheduler.spawn(last_response.close(timeout=0.5))
+ # Stop TTS, clear the buffer and send a stop signal
+ tts_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
- recognizer_complete_gate.clear()
+ stt_complete_gate.clear()
- # Clear the recognition buffer
- recognizer_buffer.clear()
+ # Close previous response if any
+ if last_response:
+ await scheduler.spawn(last_response.close(timeout=0))
- # Clear the TTS queue
- await scheduler.spawn(
- handle_clear_queue(
- call=call,
- client=automation_client,
- )
- )
+ # Clear the recognition buffer
+ stt_buffer.clear()
async def _response_callback() -> None:
# Wait for the complete recognition
- await recognizer_complete_gate.wait()
+ await stt_complete_gate.wait()
- recognizer_text = " ".join(recognizer_buffer).strip()
+ stt_text = " ".join(stt_buffer).strip()
# Skip if no partial recognition
- if not recognizer_text:
+ if not stt_text:
return
# Add it to the call history and update last interaction
- logger.info("Voice stored: %s", recognizer_buffer)
- async with _db.call_transac(call):
+ logger.info("Voice stored: %s", stt_buffer)
+ async with _db.call_transac(
+ call=call,
+ scheduler=scheduler,
+ ):
call.last_interaction_at = datetime.now(UTC)
call.messages.append(
MessageModel(
- content=recognizer_text,
+ content=stt_text,
persona=MessagePersonaEnum.HUMAN,
)
)
# Clear the recognition buffer
- recognizer_buffer.clear()
+ stt_buffer.clear()
# Store recognitio task
nonlocal last_response
@@ -187,6 +169,7 @@ async def load_llm_chat( # noqa: PLR0913
post_callback=post_callback,
scheduler=scheduler,
training_callback=training_callback,
+ tts_client=tts_client,
)
)
@@ -198,8 +181,8 @@ async def load_llm_chat( # noqa: PLR0913
call=call,
channels=audio_channels,
clear_audio_callback=_clear_audio_callback,
- in_stream=audio_stream,
- out_stream=recognizer_stream,
+ in_stream=audio_in,
+ out_stream=stt_stream,
response_callback=_response_callback,
sample_rate=audio_sample_rate,
timeout_callback=_timeout_callback,
@@ -208,12 +191,13 @@ async def load_llm_chat( # noqa: PLR0913
# 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: PLR0915
+async def _out_answer( # noqa: PLR0915, PLR0913
call: CallStateModel,
client: CallAutomationClient,
post_callback: Callable[[CallStateModel], Awaitable[None]],
- scheduler: aiojobs.Scheduler,
+ scheduler: Scheduler,
training_callback: Callable[[CallStateModel], Awaitable[None]],
+ tts_client: SpeechSynthesizer,
_iterations_remaining: int = 3,
) -> CallStateModel:
"""
@@ -228,7 +212,10 @@ async def _out_answer( # noqa: PLR0915
span_attribute(CallAttributes.CALL_MESSAGE, call.messages[-1].content)
# Reset recognition retry counter
- async with _db.call_transac(call):
+ async with _db.call_transac(
+ call=call,
+ scheduler=scheduler,
+ ):
call.recognition_retry = 0
# By default, play the loading sound
@@ -244,11 +231,12 @@ async def _out_answer( # noqa: PLR0915
play_loading_sound = False
# Play the TTS
await scheduler.spawn(
- handle_play_text(
+ handle_realtime_tts(
call=call,
- client=client,
+ scheduler=scheduler,
style=style,
text=text,
+ tts_client=tts_client,
)
)
@@ -260,6 +248,7 @@ async def _out_answer( # noqa: PLR0915
post_callback=post_callback,
scheduler=scheduler,
tts_callback=_tts_callback,
+ tts_client=tts_client,
use_tools=_iterations_remaining > 0,
)
)
@@ -324,11 +313,12 @@ async def _out_answer( # noqa: PLR0915
soft_timeout_triggered = True
# Never store the error message in the call history, it has caused hallucinations in the LLM
await scheduler.spawn(
- handle_play_text(
+ handle_realtime_tts(
call=call,
- client=client,
+ scheduler=scheduler,
store=False,
text=await CONFIG.prompts.tts.timeout_loading(call),
+ tts_client=tts_client,
)
)
@@ -350,15 +340,18 @@ async def _out_answer( # noqa: PLR0915
# TODO: Remove last message
logger.exception("Error loading intelligence")
- if is_error: # Error during chat
- if not continue_chat or _iterations_remaining < 1: # Maximum retries reached
+ # Error during chat
+ if is_error:
+ # Maximum retries reached
+ if not continue_chat or _iterations_remaining < 1:
logger.warning("Maximum retries reached, stopping chat")
content = await CONFIG.prompts.tts.error(call)
# Speak the error
await _tts_callback(content, MessageStyleEnum.NONE)
# Never store the error message in the call history, it has caused hallucinations in the LLM
- else: # Retry chat after an error
+ # Retry chat after an error
+ else:
logger.info("Retrying chat, %s remaining", _iterations_remaining - 1)
return await _out_answer(
call=call,
@@ -366,9 +359,12 @@ async def _out_answer( # noqa: PLR0915
post_callback=post_callback,
scheduler=scheduler,
training_callback=training_callback,
+ tts_client=tts_client,
_iterations_remaining=_iterations_remaining - 1,
)
- elif continue_chat and _iterations_remaining > 0: # Contiue chat
+
+ # Contiue chat
+ elif continue_chat and _iterations_remaining > 0:
logger.info("Continuing chat, %s remaining", _iterations_remaining - 1)
return await _out_answer(
call=call,
@@ -376,6 +372,7 @@ async def _out_answer( # noqa: PLR0915
post_callback=post_callback,
scheduler=scheduler,
training_callback=training_callback,
+ tts_client=tts_client,
_iterations_remaining=_iterations_remaining - 1,
) # Recursive chat (like for for retry or tools)
@@ -391,8 +388,9 @@ async def _execute_llm_chat( # noqa: PLR0913, PLR0911, PLR0912, PLR0915
call: CallStateModel,
client: CallAutomationClient,
post_callback: Callable[[CallStateModel], Awaitable[None]],
- scheduler: aiojobs.Scheduler,
+ scheduler: Scheduler,
tts_callback: Callable[[str, MessageStyleEnum], Awaitable[None]],
+ tts_client: SpeechSynthesizer,
use_tools: bool,
) -> tuple[bool, bool, CallStateModel]:
"""
@@ -433,19 +431,14 @@ async def _execute_llm_chat( # noqa: PLR0913, PLR0911, PLR0912, PLR0915
trainings=trainings,
)
- # Initialize TTS callbacks
- tts_callback = _tts_callback(
- automation_client=client,
- call=call,
- scheduler=scheduler,
- )
-
# Build plugins
plugins = DefaultPlugin(
call=call,
client=client,
post_callback=post_callback,
+ scheduler=scheduler,
tts_callback=_plugin_tts_callback,
+ tts_client=tts_client,
)
tools = []
@@ -480,14 +473,19 @@ async def _execute_llm_chat( # noqa: PLR0913, PLR0911, PLR0912, PLR0915
):
content_buffer_pointer += length
await _content_callback(sentence)
- except MaximumTokensReachedError: # Retry on maximum tokens reached
+
+ # Retry on maximum tokens reached
+ except MaximumTokensReachedError:
logger.warning("Maximum tokens reached for this completion, retry asked")
maximum_tokens_reached = True
- except APIError as e: # Retry on API error
+ # Retry on API error
+ except APIError as e:
logger.warning("OpenAI API call error: %s", e)
return True, True, call # Error, retry
- except SafetyCheckError as e: # Last user message is trash, remove it
+ # Last user message is trash, remove it
+ except SafetyCheckError as e:
logger.warning("Safety Check error: %s", e)
+ # Remove last user message
if last_message := next(
(
call
@@ -496,7 +494,7 @@ async def _execute_llm_chat( # noqa: PLR0913, PLR0911, PLR0912, PLR0915
and call.action in [MessageAction.SMS, MessageAction.TALK]
),
None,
- ): # Remove last user message
+ ):
call.messages.remove(last_message)
return True, False, call # Error, no retry
@@ -535,7 +533,10 @@ async def _execute_llm_chat( # noqa: PLR0913, PLR0911, PLR0912, PLR0915
call = plugins.call # Update call model if object reference changed
# Store message
- async with _db.call_transac(call):
+ async with _db.call_transac(
+ call=call,
+ scheduler=scheduler,
+ ):
call.messages.append(
MessageModel(
content="", # Content has already been stored within the TTS callback
@@ -545,13 +546,14 @@ async def _execute_llm_chat( # noqa: PLR0913, PLR0911, PLR0912, PLR0915
)
)
- if tool_calls: # Recusive call if needed
+ # Recusive call if needed
+ if tool_calls:
return False, True, call
-
- if maximum_tokens_reached: # Retry if maximum tokens reached
+ # Retry if maximum tokens reached
+ if maximum_tokens_reached:
return False, True, call # TODO: Should we notify an error?
-
- return False, False, call # No error, no retry
+ # No error, no retry
+ return False, False, call
# TODO: Refacto and simplify
@@ -647,9 +649,6 @@ async def _in_audio( # noqa: PLR0913
sample_width=bits_per_sample // 8,
)
- # Confirm ASAP that the event is processed
- in_stream.task_done()
-
# 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)
@@ -658,6 +657,9 @@ async def _in_audio( # noqa: PLR0913
assert isinstance(in_audio.raw_data, bytes)
out_stream.write(in_audio.raw_data)
+ # Confirm ASAP that the event is processed
+ in_stream.task_done()
+
# Use WebRTC VAD algorithm to detect voice
in_empty = False
if not vad.is_speech(
@@ -684,9 +686,9 @@ async def _in_audio( # noqa: PLR0913
def _tts_callback(
- automation_client: CallAutomationClient,
call: CallStateModel,
- scheduler: aiojobs.Scheduler,
+ scheduler: Scheduler,
+ tts_client: SpeechSynthesizer,
) -> Callable[[str, MessageStyleEnum], Awaitable[None]]:
"""
Send back the TTS to the user.
@@ -703,11 +705,12 @@ def _tts_callback(
# Play the TTS
await scheduler.spawn(
- handle_play_text(
+ handle_realtime_tts(
call=call,
- client=automation_client,
+ scheduler=scheduler,
style=style,
text=text,
+ tts_client=tts_client,
)
)
diff --git a/app/helpers/call_utils.py b/app/helpers/call_utils.py
index 88aff7c..131322e 100644
--- a/app/helpers/call_utils.py
+++ b/app/helpers/call_utils.py
@@ -1,9 +1,24 @@
+import asyncio
import json
import re
-from collections.abc import AsyncGenerator, Generator
+from collections.abc import AsyncGenerator, Awaitable, Callable, Generator
from contextlib import asynccontextmanager, contextmanager, suppress
from enum import Enum
+from aiojobs import Job, Scheduler
+from azure.cognitiveservices.speech import (
+ AudioConfig,
+ SpeechConfig,
+ SpeechRecognizer,
+ SpeechSynthesizer,
+)
+from azure.cognitiveservices.speech.audio import (
+ AudioOutputConfig,
+ AudioStreamFormat,
+ PushAudioInputStream,
+ PushAudioOutputStream,
+ PushAudioOutputStreamCallback,
+)
from azure.communication.callautomation import (
FileSource,
PhoneNumberIdentifier,
@@ -21,6 +36,7 @@ from azure.communication.callautomation.aio import (
from azure.core.exceptions import HttpResponseError, ResourceNotFoundError
from app.helpers.config import CONFIG
+from app.helpers.identity import token
from app.helpers.logging import logger
from app.models.call import CallStateModel
from app.models.message import (
@@ -48,6 +64,19 @@ class CallHangupException(Exception):
pass
+class TtsCallback(PushAudioOutputStreamCallback):
+ """
+ Callback for Azure Speech Synthesizer to push audio data to a queue.
+ """
+
+ def __init__(self, queue: asyncio.Queue[bytes | bool]):
+ self.queue = queue
+
+ def write(self, audio_buffer: memoryview) -> int:
+ self.queue.put_nowait(audio_buffer.tobytes())
+ return audio_buffer.nbytes
+
+
class ContextEnum(str, Enum):
"""
Enum for call context.
@@ -55,9 +84,9 @@ class ContextEnum(str, Enum):
Used to track the operation context of a call in Azure Communication Services.
"""
- CONNECT_AGENT = "connect_agent" # Transfer to agent
GOODBYE = "goodbye" # Hang up
IVR_LANG_SELECT = "ivr_lang_select" # IVR language selection
+ START_REALTIME = "start_realtime" # Start realtime call
TRANSFER_FAILED = "transfer_failed" # Transfer failed
@@ -99,43 +128,6 @@ def tts_sentence_split(
)
-async def _handle_play_text(
- call: CallStateModel,
- client: CallAutomationClient,
- context: ContextEnum | None,
- style: MessageStyleEnum,
- text: str,
-) -> bool:
- """
- Play a text to a call participant.
-
- If `context` is provided, it will be used to track the operation.
-
- Returns `True` if the text was played, `False` otherwise.
- """
- logger.info("Playing TTS: %s", text)
- try:
- assert call.voice_id, "Voice ID is required to control the call"
- async with _use_call_client(client, call.voice_id) as call_client:
- await call_client.play_media(
- operation_context=_context_serializer({context}),
- play_source=_audio_from_text(
- call=call,
- style=style,
- text=text,
- ),
- )
- return True
- except ResourceNotFoundError:
- logger.debug("Call hung up before playing")
- except HttpResponseError as e:
- if "call already terminated" in e.message.lower():
- logger.debug("Call hung up before playing")
- else:
- raise e
- return False
-
-
async def handle_media(
client: CallAutomationClient,
call: CallStateModel,
@@ -156,68 +148,155 @@ async def handle_media(
)
-async def handle_play_text( # noqa: PLR0913
+async def handle_automation_tts( # noqa: PLR0913
call: CallStateModel,
client: CallAutomationClient,
+ post_callback: Callable[[CallStateModel], Awaitable[None]],
+ scheduler: Scheduler,
text: str,
context: ContextEnum | None = None,
store: bool = True,
style: MessageStyleEnum = MessageStyleEnum.NONE,
-) -> bool:
+) -> None:
"""
Play a text to a call participant.
If `store` is `True`, the text will be stored in the call messages.
- Returns `True` if the text was played, `False` otherwise.
+ If the call hangs up, the call will be ended.
"""
- # Split text in chunks
- chunks = await _chunk_before_tts(
- call=call,
- store=store,
- style=style,
- text=text,
- )
+ assert call.voice_id, "Voice ID is required to control the call"
# Play each chunk
- for chunk in chunks:
- res = await _handle_play_text(
- call=call,
- client=client,
- context=context,
- style=style,
- text=chunk,
+ jobs: list[Job] = []
+ chunks = _chunk_for_tts(text)
+ async with _use_call_client(client, call.voice_id) as call_client:
+ jobs += [
+ await scheduler.spawn(
+ _automation_play_text(
+ call_client=call_client,
+ call=call,
+ context=context,
+ style=style,
+ text=chunk,
+ )
+ )
+ for chunk in chunks
+ ]
+
+ # Wait for all jobs to finish and catch hangup
+ for job in jobs:
+ try:
+ await job.wait()
+ except CallHangupException:
+ from app.helpers.call_events import hangup_now
+
+ logger.info("Failed to play prompt, ending call now")
+ await hangup_now(
+ call=call,
+ client=client,
+ post_callback=post_callback,
+ scheduler=scheduler,
+ )
+ return
+
+ if store:
+ await scheduler.spawn(
+ _store_assistant_message(
+ call=call,
+ style=style,
+ text=text,
+ scheduler=scheduler,
+ )
)
- if not res:
- return False
- return True
-async def handle_clear_queue(
- client: CallAutomationClient,
+async def _automation_play_text(
+ call_client: CallConnectionClient,
call: CallStateModel,
+ context: ContextEnum | None,
+ style: MessageStyleEnum,
+ text: str,
) -> None:
"""
- Clear the media queue of a call.
+ Play a text to a call participant.
+
+ If `context` is provided, it will be used to track the operation. Can raise a `CallHangupException` if the call is hung up.
+
+ Returns `True` if the text was played, `False` otherwise.
"""
- try:
- assert call.voice_id, "Voice ID is required for recognizing media"
- async with _use_call_client(client, call.voice_id) as call_client:
- await call_client.cancel_all_media_operations()
- except ResourceNotFoundError:
- logger.debug("Call hung up before playing")
- except HttpResponseError as e:
- if "call already terminated" in e.message.lower():
- logger.debug("Call hung up before playing")
- else:
- raise e
+ logger.info("Playing TTS: %s", text)
+ with _detect_hangup():
+ assert call.voice_id, "Voice ID is required to control the call"
+ await call_client.play_media(
+ operation_context=_context_serializer({context}),
+ play_source=_ssml_from_text(
+ call=call,
+ style=style,
+ text=text,
+ ),
+ )
-async def _chunk_before_tts(
+async def handle_realtime_tts( # noqa: PLR0913
call: CallStateModel,
- style: MessageStyleEnum,
+ scheduler: Scheduler,
text: str,
+ tts_client: SpeechSynthesizer,
store: bool = True,
+ style: MessageStyleEnum = MessageStyleEnum.NONE,
+) -> None:
+ """
+ Play a text to the realtime TTS.
+
+ If `store` is `True`, the text will be stored in the call messages.
+ """
+ # Play each chunk
+ chunks = _chunk_for_tts(text)
+ for chunk in chunks:
+ tts_client.speak_ssml_async(
+ _ssml_from_text(
+ call=call,
+ style=style,
+ text=chunk,
+ ).ssml_text
+ )
+
+ if store:
+ await scheduler.spawn(
+ _store_assistant_message(
+ call=call,
+ style=style,
+ text=text,
+ scheduler=scheduler,
+ )
+ )
+
+
+async def _store_assistant_message(
+ call: CallStateModel,
+ style: MessageStyleEnum,
+ text: str,
+ scheduler: Scheduler,
+) -> None:
+ """
+ Store an assistant message in the call history.
+ """
+ async with _db.call_transac(
+ call=call,
+ scheduler=scheduler,
+ ):
+ call.messages.append(
+ MessageModel(
+ content=text,
+ persona=MessagePersonaEnum.ASSISTANT,
+ style=style,
+ )
+ )
+
+
+def _chunk_for_tts(
+ text: str,
) -> list[str]:
"""
Split a text in chunks and store them in the call messages.
@@ -228,17 +307,6 @@ async def _chunk_before_tts(
text = re.sub(_TTS_SANITIZER_R, " ", text) # Remove unwanted characters
text = re.sub(r"\s+", " ", text) # Remove multiple spaces
- # Store text in call messages
- if store:
- async with _db.call_transac(call):
- call.messages.append(
- MessageModel(
- content=text,
- persona=MessagePersonaEnum.ASSISTANT,
- style=style,
- )
- )
-
# Split text in chunks, separated by sentence
chunks = []
chunk = ""
@@ -260,7 +328,7 @@ async def _chunk_before_tts(
return chunks
-def _audio_from_text(
+def _ssml_from_text(
call: CallStateModel,
style: MessageStyleEnum,
text: str,
@@ -317,7 +385,7 @@ async def handle_recognize_ivr(
input_type=RecognizeInputType.CHOICES,
interrupt_prompt=True,
operation_context=_context_serializer({context}),
- play_prompt=_audio_from_text(
+ play_prompt=_ssml_from_text(
call=call,
style=MessageStyleEnum.NONE,
text=text,
@@ -446,3 +514,90 @@ async def _use_call_client(
"""
# Client already been created in the call client, never close it from here
yield client.get_call_connection(call_connection_id=voice_id)
+
+
+@asynccontextmanager
+async def use_tts_client(
+ audio: asyncio.Queue[bytes | bool],
+ call: CallStateModel,
+) -> AsyncGenerator[SpeechSynthesizer, None]:
+ """
+ Use a text-to-speech client for a call.
+ """
+ # Get AAD token
+ aad_token = await (await token("https://cognitiveservices.azure.com/.default"))()
+
+ # Create real-time 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",
+ )
+ config.authorization_token = (
+ f"aad#{CONFIG.cognitive_service.resource_id}#{aad_token}"
+ )
+ config.speech_synthesis_voice_name = call.lang.voice
+ 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))
+ ),
+ )
+
+ # Connect events
+ client.synthesis_started.connect(lambda _: logger.debug("TTS started"))
+ client.synthesis_completed.connect(lambda _: logger.debug("TTS completed"))
+
+ # Return
+ yield client
+
+
+@asynccontextmanager
+async def use_stt_client(
+ audio_bits_per_sample: int,
+ audio_channels: int,
+ audio_sample_rate: int,
+ call: CallStateModel,
+ callback: Callable[[str], None],
+) -> AsyncGenerator[PushAudioInputStream, None]:
+ """
+ Use a speech-to-text client for a call.
+
+ Yields a stream to push audio data to the client. Once the context is exited, the client will stop.
+ """
+ # Get AAD token
+ aad_token = await (await token("https://cognitiveservices.azure.com/.default"))()
+
+ # Create client
+ stream = PushAudioInputStream(
+ stream_format=AudioStreamFormat(
+ bits_per_sample=audio_bits_per_sample,
+ channels=audio_channels,
+ samples_per_second=audio_sample_rate,
+ ),
+ )
+ client = SpeechRecognizer(
+ audio_config=AudioConfig(stream=stream),
+ language=call.lang.short_code,
+ speech_config=SpeechConfig(
+ auth_token=f"aad#{CONFIG.cognitive_service.resource_id}#{aad_token}",
+ region=CONFIG.cognitive_service.region,
+ ),
+ )
+
+ # Connect events
+ client.recognized.connect(lambda e: callback(e.result.text))
+ 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
+ client.start_continuous_recognition_async()
+ # Return
+ yield stream
+ finally:
+ # Stop STT
+ client.stop_continuous_recognition_async()
diff --git a/app/helpers/llm_tools.py b/app/helpers/llm_tools.py
index 9d6c007..e034461 100644
--- a/app/helpers/llm_tools.py
+++ b/app/helpers/llm_tools.py
@@ -1,12 +1,13 @@
import asyncio
-from collections.abc import Awaitable, Callable
from html import escape
from typing import Annotated, Literal, TypedDict
-from azure.communication.callautomation.aio import CallAutomationClient
from pydantic import ValidationError
-from app.helpers.call_utils import ContextEnum as CallContextEnum, handle_play_text
+from app.helpers.call_utils import (
+ handle_realtime_tts,
+ handle_transfer,
+)
from app.helpers.config import CONFIG
from app.helpers.llm_utils import AbstractPlugin
from app.helpers.logging import logger
@@ -29,22 +30,6 @@ class UpdateClaimDict(TypedDict):
class DefaultPlugin(AbstractPlugin):
- client: CallAutomationClient
- post_callback: Callable[[CallStateModel], Awaitable[None]]
- tts_callback: Callable[[str], Awaitable[None]]
-
- def __init__(
- self,
- call: CallStateModel,
- client: CallAutomationClient,
- post_callback: Callable[[CallStateModel], Awaitable[None]],
- tts_callback: Callable[[str], Awaitable[None]],
- ):
- super().__init__(call)
- self.client = client
- self.post_callback = post_callback
- self.tts_callback = tts_callback
-
async def end_call(self) -> str:
"""
Use this if the customer said they want to end the call.
@@ -61,11 +46,14 @@ class DefaultPlugin(AbstractPlugin):
- All participants are satisfied and agree to end the call
- Customer said "bye bye"
"""
- await handle_play_text(
+ from app.helpers.call_events import hangup_realtime_now
+
+ await hangup_realtime_now(
call=self.call,
client=self.client,
- context=CallContextEnum.GOODBYE,
- text=await CONFIG.prompts.tts.goodbye(self.call),
+ post_callback=self.post_callback,
+ scheduler=self.scheduler,
+ tts_client=self.tts_client,
)
return "Call ended"
@@ -296,11 +284,18 @@ class DefaultPlugin(AbstractPlugin):
- No more information available and customer insists
- Not satisfied with the answers
"""
- await handle_play_text(
+ # Play TTS
+ await handle_realtime_tts(
call=self.call,
- client=self.client,
- context=CallContextEnum.CONNECT_AGENT,
+ scheduler=self.scheduler,
text=await CONFIG.prompts.tts.end_call_to_connect_agent(self.call),
+ tts_client=self.tts_client,
+ )
+ # Transfer
+ await handle_transfer(
+ call=self.call,
+ client=self.client,
+ target=self.call.initiate.agent_phone_number,
)
return "Transferring to human agent"
@@ -564,10 +559,11 @@ class DefaultPlugin(AbstractPlugin):
- Customer made a mistake in the language selection
- Trouble understanding the voice in the current language
"""
+ # Check if lang is available
if not any(
lang == available.short_code
for available in self.call.initiate.lang.availables
- ): # Check if lang is available
+ ):
return f"Language {lang} not available"
# Update lang
diff --git a/app/helpers/llm_utils.py b/app/helpers/llm_utils.py
index d26e3f7..fb7def5 100644
--- a/app/helpers/llm_utils.py
+++ b/app/helpers/llm_utils.py
@@ -5,11 +5,16 @@ See: https://github.com/microsoft/autogen/blob/2750391f847b7168d842dfcb815ac37bd
import asyncio
import inspect
-from collections.abc import Callable
+from collections.abc import Awaitable, Callable
from inspect import getmembers, isfunction
from textwrap import dedent
from typing import Annotated, Any, ForwardRef, TypeVar
+from aiojobs import Scheduler
+from azure.cognitiveservices.speech import (
+ SpeechSynthesizer,
+)
+from azure.communication.callautomation.aio import CallAutomationClient
from jinja2 import Environment
from openai.types.chat import ChatCompletionToolParam
from openai.types.shared_params.function_definition import FunctionDefinition
@@ -39,12 +44,27 @@ class Parameters(BaseModel):
class AbstractPlugin:
call: CallStateModel
+ client: CallAutomationClient
+ post_callback: Callable[[CallStateModel], Awaitable[None]]
+ scheduler: Scheduler
+ tts_callback: Callable[[str], Awaitable[None]]
+ tts_client: SpeechSynthesizer
- def __init__(
+ def __init__( # noqa: PLR0913
self,
call: CallStateModel,
+ client: CallAutomationClient,
+ post_callback: Callable[[CallStateModel], Awaitable[None]],
+ scheduler: Scheduler,
+ tts_callback: Callable[[str], Awaitable[None]],
+ tts_client: SpeechSynthesizer,
):
self.call = call
+ self.client = client
+ self.post_callback = post_callback
+ self.scheduler = scheduler
+ self.tts_callback = tts_callback
+ self.tts_client = tts_client
async def to_openai(self) -> list[ChatCompletionToolParam]:
return await asyncio.gather(
diff --git a/app/main.py b/app/main.py
index e711918..5332366 100644
--- a/app/main.py
+++ b/app/main.py
@@ -1,6 +1,6 @@
import asyncio
import json
-from base64 import b64decode
+from base64 import b64decode, b64encode
from contextlib import asynccontextmanager, suppress
from datetime import timedelta
from http import HTTPStatus
@@ -11,6 +11,7 @@ from uuid import UUID
import jwt
import mistune
+from aiojobs import Scheduler
from azure.communication.callautomation import (
MediaStreamingAudioChannelType,
MediaStreamingContentType,
@@ -29,6 +30,7 @@ from fastapi import (
Request,
Response,
WebSocket,
+ WebSocketDisconnect,
)
from fastapi.exceptions import RequestValidationError, ValidationException
from fastapi.responses import HTMLResponse, JSONResponse
@@ -42,17 +44,16 @@ from twilio.twiml.messaging_response import MessagingResponse
from app.helpers.cache import async_lru_cache
from app.helpers.call_events import (
on_audio_connected,
+ on_automation_play_completed,
+ on_automation_recognize_error,
on_call_connected,
on_call_disconnected,
on_end_call,
on_ivr_recognized,
on_new_call,
- on_play_completed,
on_play_error,
on_play_started,
- on_recognize_error,
on_sms_received,
- on_transfer_completed,
on_transfer_error,
)
from app.helpers.call_utils import ContextEnum as CallContextEnum
@@ -89,7 +90,6 @@ _jinja.filters["markdown"] = lambda x: (
) # pyright: ignore
# Azure Communication Services
-_automation_client: CallAutomationClient | None = None
_source_caller = PhoneNumberIdentifier(CONFIG.communication_services.phone_number)
logger.info("Using phone number %s", CONFIG.communication_services.phone_number)
_communication_services_jwks_client = jwt.PyJWKClient(
@@ -491,10 +491,12 @@ async def sms_event(
span_attribute(CallAttributes.CALL_ID, str(call.call_id))
# Execute business logic
- await on_sms_received(
- call=call,
- message=message,
- )
+ async with Scheduler() as scheduler:
+ await on_sms_received(
+ call=call,
+ message=message,
+ scheduler=scheduler,
+ )
async def _communicationservices_validate_jwt(
@@ -576,46 +578,79 @@ async def communicationservices_wss_post(
# Client SDK
automation_client = await _use_automation_client()
- # Queue audio data
- audio_queue: asyncio.Queue[bytes] = asyncio.Queue()
+ # Queues
+ audio_in: asyncio.Queue[bytes] = asyncio.Queue()
+ audio_out: asyncio.Queue[bytes | bool] = asyncio.Queue()
async def _consume_audio() -> None:
+ """
+ Consume audio data from the WebSocket.
+ """
logger.debug("Audio data consumer started")
- async for event in websocket.iter_json():
- # DEBUG: Uncomment to see all events, but be careful, it will be verbose ^_^
- # logger.debug("Audio event received %s", event)
-
- # TODO: Handle configuration event (audio format, sample rate, etc.)
- # Skip non-audio events
- if "kind" not in event or event["kind"] != "AudioData":
- continue
-
- # Filter out silent audio
- audio_data: dict[str, Any] = event.get("audioData", {})
- audio_base64: str | None = audio_data.get("data", None)
- audio_silent: bool | None = audio_data.get("silent", True)
- if audio_silent or not audio_base64:
- continue
-
- # Queue audio
- await audio_queue.put(b64decode(audio_base64))
-
- await asyncio.gather(
- # Consume audio from the WebSocket
- _consume_audio(),
- # Process audio
- # TODO: Dynamically set the audio format
- on_audio_connected(
- audio_bits_per_sample=16,
- audio_channels=1,
- audio_sample_rate=16000,
- audio_stream=audio_queue,
- call=call,
- client=automation_client,
- post_callback=_trigger_post_event,
- training_callback=_trigger_training_event,
- ),
- )
+ with suppress(WebSocketDisconnect):
+ async for event in websocket.iter_json():
+ # TODO: Handle configuration event (audio format, sample rate, etc.)
+ # Skip non-audio events
+ if "kind" not in event or event["kind"] != "AudioData":
+ continue
+ # Filter out silent audio
+ audio_data: dict[str, Any] = event.get("audioData", {})
+ audio_base64: str | None = audio_data.get("data", None)
+ audio_silent: bool | None = audio_data.get("silent", True)
+ if audio_silent or not audio_base64:
+ continue
+ # Queue audio
+ await audio_in.put(b64decode(audio_base64))
+
+ async def _send_audio() -> None:
+ """
+ Send audio data to the WebSocket
+ """
+ logger.debug("Audio data sender started")
+ with suppress(WebSocketDisconnect):
+ while True:
+ audio_data = await audio_out.get()
+ # Send audio
+ if isinstance(audio_data, bytes):
+ await websocket.send_json(
+ {
+ "kind": "AudioData",
+ "audioData": {
+ "data": b64encode(audio_data).decode("utf-8"),
+ },
+ }
+ )
+ # Stop audio
+ elif audio_data is False:
+ await websocket.send_json(
+ {
+ "kind": "StopAudio",
+ "stopAudio": {},
+ }
+ )
+ audio_out.task_done()
+
+ async with Scheduler() as scheduler:
+ await asyncio.gather(
+ # Consume audio from the WebSocket
+ _consume_audio(),
+ # Send audio to the WebSocket
+ _send_audio(),
+ # Process audio
+ # TODO: Dynamically set the audio format
+ on_audio_connected(
+ audio_bits_per_sample=16,
+ audio_channels=1,
+ audio_in=audio_in,
+ audio_out=audio_out,
+ audio_sample_rate=16000,
+ call=call,
+ client=automation_client,
+ post_callback=_trigger_post_event,
+ scheduler=scheduler,
+ training_callback=_trigger_training_event,
+ ),
+ )
@api.post("/communicationservices/callback/{call_id}/{secret}")
@@ -642,22 +677,25 @@ async def communicationservices_callback_post(
raise RequestValidationError(["Events must be a list"])
# Process events in parallel
- await asyncio.gather(
- *[
- _communicationservices_event_worker(
- call_id=call_id,
- event_dict=event,
- secret=secret,
- )
- for event in events
- ]
- )
+ async with Scheduler() as scheduler:
+ await asyncio.gather(
+ *[
+ _communicationservices_event_worker(
+ call_id=call_id,
+ event_dict=event,
+ secret=secret,
+ scheduler=scheduler,
+ )
+ for event in events
+ ]
+ )
# TODO: Refacto, too long (and remove PLR0912/PLR0915 ignore)
async def _communicationservices_event_worker(
call_id: UUID,
event_dict: dict,
+ scheduler: Scheduler,
secret: str,
) -> None:
"""
@@ -685,7 +723,10 @@ async def _communicationservices_event_worker(
# Store connection ID
connection_id = event.data["callConnectionId"]
- async with _db.call_transac(call):
+ async with _db.call_transac(
+ call=call,
+ scheduler=scheduler,
+ ):
call.voice_id = connection_id
# Extract context
@@ -708,6 +749,8 @@ async def _communicationservices_event_worker(
await on_call_connected(
call=call,
client=automation_client,
+ post_callback=_trigger_post_event,
+ scheduler=scheduler,
server_call_id=server_call_id,
)
@@ -717,6 +760,7 @@ async def _communicationservices_event_worker(
call=call,
client=automation_client,
post_callback=_trigger_post_event,
+ scheduler=scheduler,
)
# Speech/IVR recognized
@@ -729,6 +773,8 @@ async def _communicationservices_event_worker(
call=call,
client=automation_client,
label=label_detected,
+ post_callback=_trigger_post_event,
+ scheduler=scheduler,
)
# Speech/IVR failed
@@ -741,26 +787,29 @@ async def _communicationservices_event_worker(
error_code,
error_message,
)
- await on_recognize_error(
+ await on_automation_recognize_error(
call=call,
client=automation_client,
contexts=operation_contexts,
post_callback=_trigger_post_event,
+ scheduler=scheduler,
)
# Media started
case "Microsoft.Communication.PlayStarted":
await on_play_started(
call=call,
+ scheduler=scheduler,
)
# Media played
case "Microsoft.Communication.PlayCompleted":
- await on_play_completed(
+ await on_automation_play_completed(
call=call,
client=automation_client,
contexts=operation_contexts,
post_callback=_trigger_post_event,
+ scheduler=scheduler,
)
# Media play failed
@@ -769,16 +818,16 @@ async def _communicationservices_event_worker(
error_code: int = result_information["subCode"]
await on_play_error(error_code)
- case "Microsoft.Communication.CallTransferAccepted": # Call transfer accepted
- await on_transfer_completed()
-
- case "Microsoft.Communication.CallTransferFailed": # Call transfer failed
+ # Call transfer failed
+ case "Microsoft.Communication.CallTransferFailed":
result_information = event.data["resultInformation"]
sub_code: int = result_information["subCode"]
await on_transfer_error(
call=call,
client=automation_client,
error_code=sub_code,
+ post_callback=_trigger_post_event,
+ scheduler=scheduler,
)
case _:
@@ -832,7 +881,11 @@ async def post_event(
logger.debug("Post event received")
# Execute business logic
- await on_end_call(call)
+ async with Scheduler() as scheduler:
+ await on_end_call(
+ call=call,
+ scheduler=scheduler,
+ )
async def _trigger_training_event(call: CallStateModel) -> None:
@@ -915,11 +968,11 @@ async def twilio_sms_post(
# Enrich span
span_attribute(CallAttributes.CALL_ID, str(call.call_id))
- # Execute business logic
- event_status = await on_sms_received(
- call=call,
- message=Body,
- )
+ async with Scheduler() as scheduler:
+ # Execute business logic
+ event_status = await on_sms_received(
+ call=call, message=Body, scheduler=scheduler
+ )
# Return error for unsuccessful event
if not event_status:
diff --git a/app/models/call.py b/app/models/call.py
index aa4250b..14b2410 100644
--- a/app/models/call.py
+++ b/app/models/call.py
@@ -14,6 +14,7 @@ from app.helpers.config_models.conversation import (
from app.helpers.monitoring import tracer
from app.helpers.pydantic_types.phone_numbers import PhoneNumber
from app.models.message import (
+ ActionEnum as MessageActionEnum,
MessageModel,
PersonaEnum as MessagePersonaEnum,
StyleEnum as MessageStyleEnum,
@@ -169,3 +170,16 @@ class CallStateModel(CallGetModel, extra="ignore"):
continue
return message.style
return MessageStyleEnum.NONE
+
+ def had_interaction(self) -> bool:
+ """
+ Check if the call had an interaction.
+
+ An interaction is defined as a call with a human message.
+ """
+ return not (
+ len(self.messages) >= 3 # noqa: PLR2004
+ and self.messages[-3].action == MessageActionEnum.CALL
+ and self.messages[-2].persona == MessagePersonaEnum.ASSISTANT
+ and self.messages[-1].action == MessageActionEnum.HANGUP
+ )
diff --git a/app/persistence/azure_queue_storage.py b/app/persistence/azure_queue_storage.py
index 239c7ef..bcddd99 100644
--- a/app/persistence/azure_queue_storage.py
+++ b/app/persistence/azure_queue_storage.py
@@ -4,7 +4,7 @@ from binascii import Error as BinasciiError
from collections.abc import AsyncGenerator, Awaitable, Callable
from contextlib import asynccontextmanager
-import aiojobs
+from aiojobs import Scheduler
from azure.core.exceptions import ServiceRequestError
from azure.storage.queue.aio import QueueClient, QueueServiceClient
from pydantic import BaseModel
@@ -135,23 +135,30 @@ class AzureQueueStorage:
self._name,
func.__name__,
)
- async with aiojobs.Scheduler() as scheduler:
- # Loop forever to receive messages
- while messages := self.receive_messages(
- max_messages=32,
- visibility_timeout=32 * 5, # 5 secs per message
- ):
- # Process messages
- async for message in messages:
- await scheduler.spawn(
- self._process_message(
- arg=arg,
- func=func,
- message=message,
+ async with Scheduler() as scheduler:
+ try:
+ # Loop forever to receive messages
+ while messages := self.receive_messages(
+ max_messages=32,
+ visibility_timeout=32 * 5, # 5 secs per message
+ ):
+ # Process messages
+ async for message in messages:
+ await scheduler.spawn(
+ self._process_message(
+ arg=arg,
+ func=func,
+ message=message,
+ )
)
- )
- # Add a small delay to avoid high CPU usage
- await asyncio.sleep(1)
+ # Add a small delay to avoid high CPU usage
+ await asyncio.sleep(1)
+ except asyncio.CancelledError:
+ logger.debug(
+ 'Azure Queue Storage "%s" trigger task cancelled', self._name
+ )
+ finally:
+ await scheduler.close()
async def _process_message(
self,
diff --git a/app/persistence/cosmos_db.py b/app/persistence/cosmos_db.py
index 2aa3afa..c57f009 100644
--- a/app/persistence/cosmos_db.py
+++ b/app/persistence/cosmos_db.py
@@ -4,6 +4,7 @@ from contextlib import asynccontextmanager, suppress
from typing import Any
from uuid import UUID, uuid4
+from aiojobs import Scheduler
from azure.cosmos import ConsistencyLevel
from azure.cosmos.aio import ContainerProxy, CosmosClient
from azure.cosmos.exceptions import CosmosHttpResponseError, CosmosResourceNotFoundError
@@ -120,105 +121,114 @@ class CosmosDbStore(IStore):
return call
@asynccontextmanager
- async def call_transac(self, call: CallStateModel) -> AsyncGenerator[None, None]:
+ async def call_transac(
+ self,
+ call: CallStateModel,
+ scheduler: Scheduler,
+ ) -> AsyncGenerator[None, None]:
# Copy and yield the updated object
init_data = call.model_copy().model_dump(mode="json", exclude_none=True)
yield
- # Compute the diff
- call_data = call.model_dump(mode="json", exclude_none=True)
- update_data: dict[str, Any | list[Any]] = {}
- for field, new_value in call_data.items():
- init_value = init_data.get(field)
- if init_value != new_value:
- if isinstance(new_value, list) and isinstance(init_value, list):
- update_data[field] = [
- item for item in new_value if item not in init_value
- ]
- else:
- update_data[field] = new_value
-
- # Skip if no diff
- if not update_data:
- logger.debug("No update needed for call %s", call.call_id)
- return
-
- # Update
- logger.debug(
- "Updating call %s with %s",
- call.call_id,
- update_data,
- )
- refreshed_call_raw = None
- try:
- async with self._use_client() as db:
- # See: https://learn.microsoft.com/en-us/azure/cosmos-db/partial-document-update#supported-operations
- refreshed_call_raw = await db.patch_item(
- item=str(call.call_id),
- partition_key=call.initiate.phone_number,
- patch_operations=[
- # Replace fields
- *[
- {
- "op": "set",
- "path": f"/{field}",
- "value": value,
- }
- for field, value in update_data.items()
- if not isinstance(value, list)
- ],
- # Add to arrays
- *[
- {
- "op": "add",
- "path": f"/{field}/-",
- "value": value,
- }
- for field, values in update_data.items()
- if isinstance(values, list)
- for value in values
+ async def _exec() -> None:
+ # Compute the diff
+ call_data = call.model_dump(mode="json", exclude_none=True)
+ update_data: dict[str, Any | list[Any]] = {}
+ for field, new_value in call_data.items():
+ init_value = init_data.get(field)
+ if init_value != new_value:
+ if isinstance(new_value, list) and isinstance(init_value, list):
+ update_data[field] = [
+ item for item in new_value if item not in init_value
+ ]
+ else:
+ update_data[field] = new_value
+
+ # Skip if no diff
+ if not update_data:
+ logger.debug("No update needed for call %s", call.call_id)
+ return
+
+ # Update
+ logger.debug(
+ "Updating call %s with %s",
+ call.call_id,
+ update_data,
+ )
+ refreshed_call_raw = None
+ try:
+ async with self._use_client() as db:
+ # See: https://learn.microsoft.com/en-us/azure/cosmos-db/partial-document-update#supported-operations
+ refreshed_call_raw = await db.patch_item(
+ item=str(call.call_id),
+ partition_key=call.initiate.phone_number,
+ patch_operations=[
+ # Replace fields
+ *[
+ {
+ "op": "set",
+ "path": f"/{field}",
+ "value": value,
+ }
+ for field, value in update_data.items()
+ if not isinstance(value, list)
+ ],
+ # Add to arrays
+ *[
+ {
+ "op": "add",
+ "path": f"/{field}/-",
+ "value": value,
+ }
+ for field, values in update_data.items()
+ if isinstance(values, list)
+ for value in values
+ ],
],
- ],
- )
- except CosmosHttpResponseError as e:
- logger.error("Error accessing CosmosDB: %s", e)
+ )
+ except CosmosHttpResponseError as e:
+ logger.error("Error accessing CosmosDB: %s", e)
- # Skip if no refresh
- if not refreshed_call_raw:
- return
+ # Skip if no refresh
+ if not refreshed_call_raw:
+ return
- # Parse refreshed object
- try:
- refreshed_call = CallStateModel.model_validate(refreshed_call_raw)
- except ValidationError:
- logger.debug("Parsing error", exc_info=True)
- return
+ # Parse refreshed object
+ try:
+ refreshed_call = CallStateModel.model_validate(refreshed_call_raw)
+ except ValidationError:
+ logger.debug("Parsing error", exc_info=True)
+ return
+
+ # Refresh live object
+ for field in call.model_fields_set:
+ new_value = getattr(refreshed_call, field)
+ if getattr(call, field) == new_value:
+ continue
+ logger.debug(
+ "Updating local field %s with %s from remote",
+ field,
+ new_value,
+ )
+ with suppress(ValidationError):
+ setattr(call, field, new_value)
- # Refresh live object
- for field in call.model_fields_set:
- new_value = getattr(refreshed_call, field)
- if getattr(call, field) == new_value:
- continue
- logger.debug(
- "Updating local field %s with %s from remote",
- field,
- new_value,
+ # Update cache
+ cache_key_id = self._cache_key_call_id(refreshed_call.call_id)
+ await self._cache.set(
+ key=cache_key_id,
+ ttl_sec=await callback_timeout_hour(),
+ value=refreshed_call.model_dump_json(),
+ ) # Update for ID
+ cache_key_phone_number = self._cache_key_phone_number(
+ refreshed_call.initiate.phone_number
)
- setattr(call, field, new_value)
+ await self._cache.delete(
+ cache_key_phone_number
+ ) # Invalidate for phone number because we don't know if it's the same call
- # Update cache
- cache_key_id = self._cache_key_call_id(refreshed_call.call_id)
- await self._cache.set(
- key=cache_key_id,
- ttl_sec=await callback_timeout_hour(),
- value=refreshed_call.model_dump_json(),
- ) # Update for ID
- cache_key_phone_number = self._cache_key_phone_number(
- refreshed_call.initiate.phone_number
- )
- await self._cache.delete(
- cache_key_phone_number
- ) # Invalidate for phone number because we don't know if it's the same call
+ # Queue the update
+ await scheduler.spawn(_exec())
# TODO: Catch errors
async def call_create(self, call: CallStateModel) -> CallStateModel:
diff --git a/app/persistence/istore.py b/app/persistence/istore.py
index 5920cfd..e144309 100644
--- a/app/persistence/istore.py
+++ b/app/persistence/istore.py
@@ -2,6 +2,8 @@ from abc import ABC, abstractmethod
from contextlib import AbstractAsyncContextManager
from uuid import UUID
+from aiojobs import Scheduler
+
from app.helpers.monitoring import tracer
from app.models.call import CallStateModel
from app.models.readiness import ReadinessEnum
@@ -26,7 +28,11 @@ class IStore(ABC):
@abstractmethod
@tracer.start_as_current_span("store_call_transac")
- def call_transac(self, call: CallStateModel) -> AbstractAsyncContextManager[None]:
+ def call_transac(
+ self,
+ call: CallStateModel,
+ scheduler: Scheduler,
+ ) -> AbstractAsyncContextManager[None]:
pass
@abstractmethod
diff --git a/tests/conftest.py b/tests/conftest.py
index 28cf866..c3820af 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -9,7 +9,16 @@ from typing import Any
import pytest
import yaml
from _pytest.mark.structures import MarkDecorator
+from azure.cognitiveservices.speech import (
+ ResultFuture,
+ SpeechSynthesisResult,
+ SpeechSynthesizer,
+)
+from azure.cognitiveservices.speech.interop import _spx_handle
from azure.communication.callautomation import FileSource, SsmlSource, TextSource
+from azure.communication.callautomation._generated.aio.operations import (
+ CallMediaOperations,
+)
from azure.communication.callautomation._models import TransferCallResult
from azure.communication.callautomation.aio import (
CallAutomationClient,
@@ -27,7 +36,21 @@ from app.main import _str_to_contexts
from app.models.call import CallInitiateModel, CallStateModel
+class CallMediaOperationsMock(CallMediaOperations):
+ def __init__(self) -> None:
+ pass
+
+ async def start_media_streaming(
+ self,
+ *args,
+ **kwargs,
+ ) -> None:
+ pass
+
+
class CallConnectionClientMock(CallConnectionClient):
+ _call_connection_id: str = "dummy"
+ _call_media_client = CallMediaOperationsMock()
_hang_up_callback: Callable[[], None]
_play_media_callback: Callable[[str], None]
_transfer_callback: Callable[[], None]
@@ -123,6 +146,26 @@ class CallAutomationClientMock(CallAutomationClient):
return self._call_client
+class SpeechSynthesizerMock(SpeechSynthesizer):
+ _play_media_callback: Callable[[str], None]
+
+ def __init__(self, play_media_callback: Callable[[str], None]) -> None:
+ self._play_media_callback = play_media_callback
+
+ def speak_text_async(
+ self,
+ text: str,
+ *args, # noqa: ARG002
+ **kwargs, # noqa: ARG002
+ ) -> ResultFuture:
+ self._play_media_callback(text)
+ return ResultFuture(
+ async_handle=_spx_handle(0),
+ get_function=lambda _: _spx_handle(0),
+ wrapped_type=SpeechSynthesisResult,
+ )
+
+
class DeepEvalAzureOpenAI(GPTModel):
_cache: pytest.Cache
_langchain_kwargs: dict[str, Any]
diff --git a/tests/llm.py b/tests/llm.py
index 544cf1f..c225573 100644
--- a/tests/llm.py
+++ b/tests/llm.py
@@ -3,8 +3,8 @@ import json
import re
from datetime import datetime
-import aiojobs
import pytest
+from aiojobs import Scheduler
from deepeval import assert_test
from deepeval.metrics import (
AnswerRelevancyMetric,
@@ -19,20 +19,25 @@ from pydantic import TypeAdapter
from pytest_assume.plugin import assume
from app.helpers.call_events import (
+ on_automation_play_completed,
on_call_connected,
on_call_disconnected,
on_end_call,
on_ivr_recognized,
- on_play_completed,
on_play_started,
)
from app.helpers.call_llm import _out_answer
+from app.helpers.config import CONFIG
from app.helpers.logging import logger
from app.models.call import CallStateModel
from app.models.message import MessageModel, PersonaEnum as MessagePersonaEnum
from app.models.reminder import ReminderModel
from app.models.training import TrainingModel
-from tests.conftest import CallAutomationClientMock, with_conversations
+from tests.conftest import (
+ CallAutomationClientMock,
+ SpeechSynthesizerMock,
+ with_conversations,
+)
class ClaimRelevancyMetric(BaseMetric):
@@ -249,6 +254,7 @@ async def test_llm( # noqa: PLR0913
3. Test claim data exists
4. Test LLM metrics
"""
+ db = CONFIG.database.instance()
def _play_media_callback(text: str) -> None:
nonlocal actual_output
@@ -257,6 +263,9 @@ async def test_llm( # noqa: PLR0913
actual_output = ""
# Mock client
+ tts_client = SpeechSynthesizerMock(
+ play_media_callback=_play_media_callback,
+ )
automation_client = CallAutomationClientMock(
hang_up_callback=lambda: None,
play_media_callback=_play_media_callback,
@@ -267,36 +276,48 @@ async def test_llm( # noqa: PLR0913
# Mock call
call.lang = lang
- async def _post_callback(_call: CallStateModel) -> None:
- await on_end_call(call=_call)
+ async with Scheduler() as scheduler:
- async def _training_callback(_call: CallStateModel) -> None:
- await _call.trainings(cache_only=False)
+ async def _post_callback(_call: CallStateModel) -> None:
+ await on_end_call(
+ call=_call,
+ scheduler=scheduler,
+ )
- # Connect call
- await on_call_connected(
- call=call,
- client=automation_client,
- server_call_id="dummy",
- )
+ async def _training_callback(_call: CallStateModel) -> None:
+ await _call.trainings(cache_only=False)
- # First IVR
- await on_ivr_recognized(
- call=call,
- client=automation_client,
- label=call.lang.short_code,
- )
+ # Connect call
+ await on_call_connected(
+ call=call,
+ client=automation_client,
+ post_callback=_post_callback,
+ scheduler=scheduler,
+ server_call_id="dummy",
+ )
+
+ # First IVR
+ await on_ivr_recognized(
+ call=call,
+ client=automation_client,
+ label=call.lang.short_code,
+ post_callback=_post_callback,
+ scheduler=scheduler,
+ )
- # Simulate conversation with speech recognition
- async with aiojobs.Scheduler() as scheduler:
+ # Simulate conversation with speech recognition
for speech in speeches:
# Add message to history
- call.messages.append(
- MessageModel(
- content=speech,
- persona=MessagePersonaEnum.HUMAN,
+ async with db.call_transac(
+ call=call,
+ scheduler=scheduler,
+ ):
+ call.messages.append(
+ MessageModel(
+ content=speech,
+ persona=MessagePersonaEnum.HUMAN,
+ )
)
- )
# Respond
await _out_answer(
@@ -305,27 +326,34 @@ async def test_llm( # noqa: PLR0913
post_callback=_post_callback,
scheduler=scheduler,
training_callback=_training_callback,
+ tts_client=tts_client,
)
+
# Play
await on_play_started(
call=call,
+ scheduler=scheduler,
)
+
# Receip
- await on_play_completed(
+ await on_automation_play_completed(
call=call,
client=automation_client,
contexts=call_client.last_contexts,
post_callback=_post_callback,
+ scheduler=scheduler,
)
+
# Reset contexts
call_client.last_contexts.clear()
- # Disconnect call
- await on_call_disconnected(
- call=call,
- client=automation_client,
- post_callback=_post_callback,
- )
+ # Disconnect call
+ await on_call_disconnected(
+ call=call,
+ client=automation_client,
+ post_callback=_post_callback,
+ scheduler=scheduler,
+ )
# Remove newlines for log comparison
actual_output = _remove_newlines(actual_output)
@@ -362,13 +390,11 @@ async def test_llm( # noqa: PLR0913
ToxicityMetric(threshold=1, model=deepeval_model), # Hate speech, insults
] # Include those by default
- if not any(
- field == "answer_relevancy" for field in claim_tests_excl
- ): # Test respond relevancy from questions
+ # Test respond relevancy from questions
+ if not any(field == "answer_relevancy" for field in claim_tests_excl):
llm_metrics.append(AnswerRelevancyMetric(threshold=0.5, model=deepeval_model))
- if not any(
- field == "contextual_relevancy" for field in claim_tests_excl
- ): # Test respond relevancy from context
+ # Test respond relevancy from context
+ if not any(field == "contextual_relevancy" for field in claim_tests_excl):
llm_metrics.append(
ContextualRelevancyMetric(threshold=0.25, model=deepeval_model)
)
diff --git a/tests/local.py b/tests/local.py
index 118badd..f903230 100644
--- a/tests/local.py
+++ b/tests/local.py
@@ -1,19 +1,21 @@
import asyncio
-import aiojobs
+from aiojobs import Scheduler
from app.helpers.call_events import (
on_call_connected,
on_call_disconnected,
on_end_call,
on_ivr_recognized,
- on_play_completed,
)
from app.helpers.call_llm import _out_answer
from app.helpers.config import CONFIG
from app.helpers.logging import logger
from app.models.call import CallInitiateModel, CallStateModel
-from tests.conftest import CallAutomationClientMock
+from app.models.message import MessageModel, PersonaEnum as MessagePersonaEnum
+from tests.conftest import CallAutomationClientMock, SpeechSynthesizerMock
+
+_db = CONFIG.database.instance()
async def main() -> None:
@@ -33,6 +35,9 @@ async def main() -> None:
logger.info("🤖 Transfering")
# Mocks
+ tts_client = SpeechSynthesizerMock(
+ play_media_callback=_play_media_callback,
+ )
call = CallStateModel(
initiate=CallInitiateModel(
**CONFIG.conversation.initiate.model_dump(),
@@ -48,33 +53,54 @@ async def main() -> None:
)
call_client = automation_client.get_call_connection()
- async def _post_callback(_call: CallStateModel) -> None:
- await on_end_call(call=_call)
+ async with Scheduler() as scheduler:
- async def _training_callback(_call: CallStateModel) -> None:
- await _call.trainings(cache_only=False)
-
- # Connect call
- await on_call_connected(
- call=call,
- client=automation_client,
- server_call_id="dummy",
- )
+ async def _post_callback(_call: CallStateModel) -> None:
+ await on_end_call(
+ call=_call,
+ scheduler=scheduler,
+ )
- # First IVR
- await on_ivr_recognized(
- call=call,
- client=automation_client,
- label=call.lang.short_code,
- )
+ async def _training_callback(_call: CallStateModel) -> None:
+ await _call.trainings(cache_only=False)
+
+ # Connect call
+ await on_call_connected(
+ call=call,
+ client=automation_client,
+ post_callback=_post_callback,
+ scheduler=scheduler,
+ server_call_id="dummy",
+ )
+
+ # First IVR
+ await on_ivr_recognized(
+ call=call,
+ client=automation_client,
+ label=call.lang.short_code,
+ post_callback=_post_callback,
+ scheduler=scheduler,
+ )
- # Simulate conversation with speech recognition
- async with aiojobs.Scheduler() as scheduler:
# Simulate conversation
while continue_conversation:
- message = input("Customer: ")
- if message.strip().lower() == "exit":
+ # Get speech
+ speech = input("Customer: ")
+ if speech.strip().lower() == "exit":
break
+
+ # Add message to history
+ async with _db.call_transac(
+ call=call,
+ scheduler=scheduler,
+ ):
+ call.messages.append(
+ MessageModel(
+ content=speech,
+ persona=MessagePersonaEnum.HUMAN,
+ )
+ )
+
# Respond
await _out_answer(
call=call,
@@ -82,25 +108,21 @@ async def main() -> None:
post_callback=_post_callback,
scheduler=scheduler,
training_callback=_training_callback,
+ tts_client=tts_client,
)
- # Receip
- await on_play_completed(
- call=call,
- client=automation_client,
- contexts=call_client.last_contexts,
- post_callback=_post_callback,
- )
+
# Reset contexts
call_client.last_contexts.clear()
- logger.info("Conversation ended, handling disconnection...")
+ logger.info("Conversation ended, handling disconnection...")
- # Disconnect call
- await on_call_disconnected(
- call=call,
- client=automation_client,
- post_callback=_post_callback,
- )
+ # Disconnect call
+ await on_call_disconnected(
+ call=call,
+ client=automation_client,
+ post_callback=_post_callback,
+ scheduler=scheduler,
+ )
logger.info("Bye bye!")