Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
perf: Async opt + preload trainings after each assistant response
Clémence Lesnéd05f5714d969
diff --git a/bicep/app.bicep b/bicep/app.bicepindex e69efc0..6da5f6b 100644--- a/bicep/app.bicep+++ b/bicep/app.bicep@@ -59,6 +59,7 @@ var config = {phone_number: localConfig.communication_services.phone_numberpost_queue_name: postQueue.namesms_queue_name: smsQueue.name+ trainings_queue_name: trainingsQueue.name}sms: localConfig.smscognitive_service: {@@ -216,6 +217,10 @@ resource functionApp 'Microsoft.Web/sites@2023-12-01' = {instanceCount: 1name: 'function:call_event'}+ {+ instanceCount: 1+ name: 'function:trainings_event'+ }]}runtime: {@@ -304,6 +309,11 @@ resource postQueue 'Microsoft.Storage/storageAccounts/queueServices/queues@2023-name: 'post-${phonenumberSanitized}'}+resource trainingsQueue 'Microsoft.Storage/storageAccounts/queueServices/queues@2023-01-01' = {+ parent: queueService+ name: 'trainings-${phonenumberSanitized}'+}+resource blobService 'Microsoft.Storage/storageAccounts/blobServices@2023-01-01' = {parent: storageAccountname: 'default'diff --git a/function_app.py b/function_app.pyindex d785aa9..b4ed3ef 100644--- a/function_app.py+++ b/function_app.py@@ -305,14 +305,20 @@ async def call_event(connection="Storage",queue_name=CONFIG.communication_services.sms_queue_name,)[email protected]_output(+ arg_name="trainings",+ connection="Storage",+ queue_name=CONFIG.communication_services.trainings_queue_name,+)@app.queue_output(arg_name="post",connection="Storage",queue_name=CONFIG.communication_services.post_queue_name,)async def sms_event(- sms: func.QueueMessage,post: func.Out[str],+ sms: func.QueueMessage,+ trainings: func.Out[str],) -> None:event = EventGridEvent.from_json(sms.get_body())event_type = event.event_type@@ -332,8 +338,9 @@ async def sms_event(call=call,client=_automation_client,message=message,- post_call_callback=lambda _call: _trigger_post_call_event(- call=_call, post=post+ post_callback=lambda _call: _trigger_post_event(call=_call, post=post),+ trainings_callback=lambda _call: _trigger_trainings_event(+ call=_call, trainings=trainings),)@@ -343,6 +350,11 @@ async def sms_event(methods=["POST"],trigger_arg_name="req",)[email protected]_output(+ arg_name="trainings",+ connection="Storage",+ queue_name=CONFIG.communication_services.trainings_queue_name,+)@app.queue_output(arg_name="post",connection="Storage",@@ -351,6 +363,7 @@ async def sms_event(async def communicationservices_event_post(post: func.Out[str],req: func.HttpRequest,+ trainings: func.Out[str],) -> func.HttpResponse:try:call_id = UUID(req.route_params["call_id"])@@ -364,6 +377,7 @@ async def communicationservices_event_post(event_dict=event_dict,post=post,secret=secret,+ trainings=trainings,)for event_dict in req.get_json()]@@ -376,6 +390,7 @@ async def _communicationservices_event_worker(event_dict: dict,post: func.Out[str],secret: str,+ trainings: func.Out[str],) -> None:call = await _db.call_aget(call_id)if not call:@@ -414,9 +429,7 @@ async def _communicationservices_event_worker(await on_call_disconnected(call=call,client=_automation_client,- post_call_callback=lambda _call: _trigger_post_call_event(- call=_call, post=post- ),+ post_callback=lambda _call: _trigger_post_event(call=_call, post=post),)elif (@@ -431,9 +444,12 @@ async def _communicationservices_event_worker(call=call,client=_automation_client,text=speech_text,- post_call_callback=lambda _call: _trigger_post_call_event(+ post_callback=lambda _call: _trigger_post_event(call=_call, post=post),+ trainings_callback=lambda _call: _trigger_trainings_event(+ call=_call, trainings=trainings+ ),)elif recognition_result == "choices": # Handle IVR@@ -442,8 +458,9 @@ async def _communicationservices_event_worker(call=call,client=_automation_client,label=label_detected,- post_call_callback=lambda _call: _trigger_post_call_event(- call=_call, post=post+ post_callback=lambda _call: _trigger_post_event(call=_call, post=post),+ trainings_callback=lambda _call: _trigger_trainings_event(+ call=_call, trainings=trainings),)@@ -475,9 +492,7 @@ async def _communicationservices_event_worker(call=call,client=_automation_client,contexts=operation_contexts,- post_call_callback=lambda _call: _trigger_post_call_event(- call=_call, post=post- ),+ post_callback=lambda _call: _trigger_post_event(call=_call, post=post),)elif event_type == "Microsoft.Communication.PlayFailed": # Media play failed@@ -506,6 +521,19 @@ async def _communicationservices_event_worker() # TODO: Do not persist on every event, this is simpler but not efficient[email protected]_trigger(+ arg_name="trainings",+ connection="Storage",+ queue_name=CONFIG.communication_services.trainings_queue_name,+)+async def trainings_event(+ trainings: func.QueueMessage,+) -> None:+ call = CallStateModel.model_validate_json(trainings.get_body())+ logger.debug(f"Trainings event received for call {call}")+ await call.trainings() # Get trainings by advance to populate cache++@app.queue_trigger(arg_name="post",connection="Storage",@@ -519,7 +547,17 @@ async def post_event(await on_end_call(call)-def _trigger_post_call_event(+def _trigger_trainings_event(+ call: CallStateModel,+ trainings: func.Out[str],+) -> None:+ """+ Shortcut to add trainings to the queue.+ """+ trainings.set(call.model_dump_json(indent=None))+++def _trigger_post_event(call: CallStateModel,post: func.Out[str],) -> None:@@ -562,6 +600,11 @@ async def _communicationservices_event_url(methods=["POST"],trigger_arg_name="req",)[email protected]_output(+ arg_name="trainings",+ connection="Storage",+ queue_name=CONFIG.communication_services.trainings_queue_name,+)@app.queue_output(arg_name="post",connection="Storage",@@ -570,6 +613,7 @@ async def _communicationservices_event_url(async def twilio_sms_post(post: func.Out[str],req: func.HttpRequest,+ trainings: func.Out[str],) -> func.HttpResponse:"""Handle incoming SMS event from Twilio.@@ -589,8 +633,9 @@ async def twilio_sms_post(call=call,message=message,client=_automation_client,- post_call_callback=lambda _call: _trigger_post_call_event(- call=_call, post=post+ post_callback=lambda _call: _trigger_post_event(call=_call, post=post),+ trainings_callback=lambda _call: _trigger_trainings_event(+ call=_call, trainings=trainings),)if not event_status:diff --git a/helpers/call_events.py b/helpers/call_events.pyindex 2f61583..c711b22 100644--- a/helpers/call_events.py+++ b/helpers/call_events.py@@ -100,13 +100,13 @@ async def on_call_connected(async def on_call_disconnected(call: CallStateModel,client: CallAutomationClient,- post_call_callback: Callable[[CallStateModel], None],+ post_callback: Callable[[CallStateModel], None],) -> None:logger.info("Call disconnected")await _handle_hangup(call=call,client=client,- post_call_callback=post_call_callback,+ post_callback=post_callback,)@@ -114,23 +114,27 @@ async def on_call_disconnected(async def on_speech_recognized(call: CallStateModel,client: CallAutomationClient,- post_call_callback: Callable[[CallStateModel], None],+ post_callback: Callable[[CallStateModel], None],text: str,+ trainings_callback: Callable[[CallStateModel], None],) -> None:logger.info(f"Voice recognition: {text}")call.messages.append(MessageModel(content=text, persona=MessagePersonaEnum.HUMAN))- await _db.call_aset(- call- ) # Save ASAP in DB allowing SMS answers to be more "in-sync"- await handle_clear_queue(- call=call,- client=client,- ) # When the user speak, the conversation should continue based on its last message- call = await load_llm_chat(- call=call,- client=client,- post_call_callback=post_call_callback,- )+ await asyncio.gather(+ _db.call_aset(+ call+ ), # First, save ASAP in DB allowing SMS answers to be more "in-sync"+ handle_clear_queue(+ call=call,+ client=client,+ ), # Second, when the user speak, the conversation should continue based on its last message+ load_llm_chat(+ call=call,+ client=client,+ post_callback=post_callback,+ trainings_callback=trainings_callback,+ ), # Third, the LLM should be loaded to continue the conversation+ ) # All in parallel to lower the answer latency@tracer.start_as_current_span("on_speech_timeout_error")@@ -188,7 +192,7 @@ async def on_play_completed(call: CallStateModel,client: CallAutomationClient,contexts: Optional[list[CallContextEnum]],- post_call_callback: Callable[[CallStateModel], None],+ post_callback: Callable[[CallStateModel], None],) -> None:logger.debug("Play completed")@@ -203,7 +207,7 @@ async def on_play_completed(await _handle_hangup(call=call,client=client,- post_call_callback=post_call_callback,+ post_callback=post_callback,)elif CallContextEnum.CONNECT_AGENT in contexts: # Call transfer@@ -238,7 +242,8 @@ async def on_ivr_recognized(call: CallStateModel,client: CallAutomationClient,label: str,- post_call_callback: Callable[[CallStateModel], None],+ post_callback: Callable[[CallStateModel], None],+ trainings_callback: Callable[[CallStateModel], None],) -> None:try:lang = next(@@ -251,29 +256,34 @@ async def on_ivr_recognized(logger.info(f"Setting call language to {lang}")call.lang = lang.short_code- await _db.call_aset(- call- ) # Persist language change, if the user calls back before the first message, the language will be set+ persist_coro = _db.call_aset(call)if len(call.messages) <= 1: # First call, or only the call action- await handle_recognize_text(- call=call,- client=client,- text=await CONFIG.prompts.tts.hello(call),- )+ await asyncio.gather(+ persist_coro, # First, persist language change for next messages+ handle_recognize_text(+ call=call,+ client=client,+ text=await CONFIG.prompts.tts.hello(call),+ ), # Second, greet the user+ ) # All in parallel to lower the answer latencyelse: # Returning call- await handle_recognize_text(- call=call,- client=client,- style=MessageStyleEnum.CHEERFUL,- text=await CONFIG.prompts.tts.welcome_back(call),- timeout_error=False, # Do not trigger timeout, as the chat will continue- )- call = await load_llm_chat(- call=call,- client=client,- post_call_callback=post_call_callback,+ await asyncio.gather(+ persist_coro, # First, persist language change for next messages+ handle_recognize_text(+ call=call,+ client=client,+ style=MessageStyleEnum.CHEERFUL,+ text=await CONFIG.prompts.tts.welcome_back(call),+ timeout_error=False, # Do not trigger timeout, as the chat will continue+ ), # Second, welcome back the user+ load_llm_chat(+ call=call,+ client=client,+ post_callback=post_callback,+ trainings_callback=trainings_callback,+ ), # Third, the LLM should be loaded to continue the conversation)@@ -303,7 +313,8 @@ async def on_sms_received(call: CallStateModel,client: CallAutomationClient,message: str,- post_call_callback: Callable[[CallStateModel], None],+ post_callback: Callable[[CallStateModel], None],+ trainings_callback: Callable[[CallStateModel], None],) -> bool:logger.info(f"SMS received from {call.initiate.phone_number}: {message}")call.messages.append(@@ -323,7 +334,8 @@ async def on_sms_received(await load_llm_chat(call=call,client=client,- post_call_callback=post_call_callback,+ post_callback=post_callback,+ trainings_callback=trainings_callback,)return True@@ -331,7 +343,7 @@ async def on_sms_received(async def _handle_hangup(call: CallStateModel,client: CallAutomationClient,- post_call_callback: Callable[[CallStateModel], None],+ post_callback: Callable[[CallStateModel], None],) -> None:await handle_hangup(client=client, call=call)call.messages.append(@@ -341,7 +353,7 @@ async def _handle_hangup(action=MessageActionEnum.HANGUP,))- post_call_callback(call)+ post_callback(call)async def on_end_call(diff --git a/helpers/call_llm.py b/helpers/call_llm.pyindex c01ee51..3ffebab 100644--- a/helpers/call_llm.py+++ b/helpers/call_llm.py@@ -111,7 +111,8 @@ def _llm_completion_system(async def load_llm_chat(call: CallStateModel,client: CallAutomationClient,- post_call_callback: Callable[[CallStateModel], None],+ post_callback: Callable[[CallStateModel], None],+ trainings_callback: Callable[[CallStateModel], None],_iterations_remaining: int = 3,) -> CallStateModel:"""@@ -138,18 +139,19 @@ async def load_llm_chat(returnshould_play_sound = False- await handle_recognize_text(- call=call,- client=client,- style=style,- text=text,- timeout_error=False, # Voice will continue, don't trigger+ await asyncio.gather(+ handle_recognize_text(+ call=call,+ client=client,+ style=style,+ text=text,+ timeout_error=False, # Voice will continue, don't trigger+ ), # First, recognize the next voice+ _db.call_aset(+ call+ ), # Second, save in DB allowing (1) user to cut off the Assistant and (2) SMS answers to be in order)- await _db.call_aset(- call- ) # Save ASAP in DB allowing (1) user to cut off the Assistant and (2) SMS answers to be in order-# Pointerdef _pointer_task() -> asyncio.Task:return asyncio.create_task(asyncio.sleep(pointer_timer))@@ -165,7 +167,7 @@ async def load_llm_chat(_execute_llm_chat(call=call,client=client,- post_call_callback=post_call_callback,+ post_callback=post_callback,use_tools=_iterations_remaining > 0,tts_callback=_tts_callback,)@@ -225,6 +227,7 @@ async def load_llm_chat(is_error, continue_chat, call = (chat_task.result()) # Store updated chat model+ trainings_callback(call) # Trigger trainings generationawait _db.call_aset(call) # Save ASAP in DB allowing (1) user to cut off the Assistant and (2) SMS answers to be in order@@ -289,7 +292,8 @@ async def load_llm_chat(return await load_llm_chat(call=call,client=client,- post_call_callback=post_call_callback,+ post_callback=post_callback,+ trainings_callback=trainings_callback,_iterations_remaining=_iterations_remaining - 1,)else:@@ -298,7 +302,8 @@ async def load_llm_chat(return await load_llm_chat(call=call,client=client,- post_call_callback=post_call_callback,+ post_callback=post_callback,+ trainings_callback=trainings_callback,_iterations_remaining=_iterations_remaining - 1,)else:@@ -315,7 +320,7 @@ async def load_llm_chat(async def _execute_llm_chat(call: CallStateModel,client: CallAutomationClient,- post_call_callback: Callable[[CallStateModel], None],+ post_callback: Callable[[CallStateModel], None],tts_callback: Callable[[str, MessageStyleEnum], Awaitable],use_tools: bool,) -> Tuple[bool, bool, CallStateModel]:@@ -377,7 +382,7 @@ async def _execute_llm_chat(plugins = LlmPlugins(call=call,client=client,- post_call_callback=post_call_callback,+ post_callback=post_callback,tts_callback=_buffer_callback,)diff --git a/helpers/config_models/communication_services.py b/helpers/config_models/communication_services.pyindex 049dba3..bcc7a19 100644--- a/helpers/config_models/communication_services.py+++ b/helpers/config_models/communication_services.py@@ -9,3 +9,4 @@ class CommunicationServicesModel(BaseModel):phone_number: PhoneNumberpost_queue_name: strsms_queue_name: str+ trainings_queue_name: strdiff --git a/helpers/llm_tools.py b/helpers/llm_tools.pyindex 9562614..1e0867c 100644--- a/helpers/llm_tools.py+++ b/helpers/llm_tools.py@@ -31,7 +31,7 @@ class UpdateClaimDict(TypedDict):class LlmPlugins:call: CallStateModelclient: CallAutomationClient- post_call_callback: Callable[[CallStateModel], None]+ post_callback: Callable[[CallStateModel], None]style: MessageStyleEnum = MessageStyleEnum.NONEtts_callback: Callable[[str, MessageStyleEnum], Awaitable]@@ -39,12 +39,12 @@ class LlmPlugins:self,call: CallStateModel,client: CallAutomationClient,- post_call_callback: Callable[[CallStateModel], None],+ post_callback: Callable[[CallStateModel], None],tts_callback: Callable[[str, MessageStyleEnum], Awaitable],):self.call = callself.client = client- self.post_call_callback = post_call_callback+ self.post_callback = post_callbackself.tts_callback = tts_callbackasync def end_call(self) -> str:@@ -92,7 +92,7 @@ class LlmPlugins:"""await self.tts_callback(customer_response, self.style)# Launch post-call intelligence for the current call- self.post_call_callback(self.call)+ self.post_callback(self.call)# Store the last message and use it at first message of the new claimlast_message = self.call.messages[-1]call = CallStateModel(diff --git a/tests/llm.py b/tests/llm.pyindex ab10852..82f8fe4 100644--- a/tests/llm.py+++ b/tests/llm.py@@ -186,8 +186,9 @@ async def test_llm(await on_speech_recognized(call=call,client=client,- post_call_callback=lambda _call: None, # Disable post call+ post_callback=lambda _call: None, # Disable post calltext=input,+ trainings_callback=lambda _call: None, # Disable training)# Remove newlines for log comparison