Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
quality: Code lint
Clémence Lesné9b6ba3296805
diff --git a/helpers/prompts.py b/helpers/prompts.pyindex 6a921ff..1c28258 100644--- a/helpers/prompts.py+++ b/helpers/prompts.py@@ -58,8 +58,12 @@ class LLM(str, Enum):class TTS(str, Enum):CALLTRANSFER_FAILURE = "Il semble que je ne puisse pas vous mettre en relation avec un agent pour l'instant, mais le prochain agent disponible vous rappellera dès que possible."CONNECT_AGENT = "Je suis désolé, je n'ai pas été en mesure de répondre à votre demande. Permettez-moi de vous transférer à un agent qui pourra vous aider davantage. Veuillez rester en ligne et je vous recontacterai sous peu."- END_CALL_TO_CONNECT_AGENT = "Bien sûr, restez en ligne. Je vais vous transférer à un agent."- ERROR = "Je suis désolé, j'ai rencontré une erreur. Pouvez-vous répéter votre demande ?"+ END_CALL_TO_CONNECT_AGENT = (+ "Bien sûr, restez en ligne. Je vais vous transférer à un agent."+ )+ ERROR = (+ "Je suis désolé, j'ai rencontré une erreur. Pouvez-vous répéter votre demande ?"+ )GOODBYE = f"Merci de votre appel, j'espère avoir pu vous aider. N'hésitez pas à rappeler, j'ai tout mémorisé. {CONFIG.workflow.bot_company} vous souhaite une excellente journée !"HELLO = f"Bonjour, je suis {CONFIG.workflow.bot_name}, l'assistant {CONFIG.workflow.bot_company} ! Je suis spécialiste des sinistres. Lorsque vous entendrez un bip, c'est que je travaille. Mais d'abord, quel est l'objet de votre appel ?"NEW_CLAIM = "Je vais créer un nouveau dossier pour vous..."diff --git a/main.py b/main.pyindex a9f9003..39ebc70 100644--- a/main.py+++ b/main.py@@ -261,7 +261,9 @@ async def call_event_post(request: Request, call_id: UUID) -> None:if not call.messages: # First callcall.messages.append(- CallMessageModel(content=TTSPrompt.HELLO, persona=CallPersona.ASSISTANT)+ CallMessageModel(+ content=TTSPrompt.HELLO, persona=CallPersona.ASSISTANT+ ))await handle_recognize(call=call,@@ -270,9 +272,11 @@ async def call_event_post(request: Request, call_id: UUID) -> None:to=target_caller,)- else: # Returning call+ else: # Returning callcall.messages.append(- CallMessageModel(content="Customer called again.", persona=CallPersona.HUMAN)+ CallMessageModel(+ content="Customer called again.", persona=CallPersona.HUMAN+ ))await handle_play(call=call,@@ -290,7 +294,9 @@ async def call_event_post(request: Request, call_id: UUID) -> None:_logger.info(f"Call disconnected ({call.id})")await handle_hangup(call=call, client=client)- elif event_type == "Microsoft.Communication.RecognizeCompleted": # Speech recognized+ elif (+ event_type == "Microsoft.Communication.RecognizeCompleted"+ ): # Speech recognizedif event.data["recognitionType"] == "speech":speech_text = event.data["speechResult"]["speech"]_logger.info(f"Recognition completed ({call.id}): {speech_text}")@@ -307,7 +313,9 @@ async def call_event_post(request: Request, call_id: UUID) -> None:)await intelligence(call, client, target_caller)- elif event_type == "Microsoft.Communication.RecognizeFailed": # Speech recognition failed+ elif (+ event_type == "Microsoft.Communication.RecognizeFailed"+ ): # Speech recognition failedresult_information = event.data["resultInformation"]error_code = result_information["subCode"]@@ -322,9 +330,13 @@ async def call_event_post(request: Request, call_id: UUID) -> None:# 8532 = Action failed, inter-digit silence timeout reached# 8512 = Unknown internal server error# See: https://github.com/MicrosoftDocs/azure-docs/blob/main/articles/communication-services/how-tos/call-automation/recognize-action.md#event-codes- if error_code in (8510, 8532, 8512) and call.recognition_retry < 10: # Timeout retry+ if (+ error_code in (8510, 8532, 8512) and call.recognition_retry < 10+ ): # Timeout retrycall.messages.append(- CallMessageModel(content=TTSPrompt.TIMEOUT_SILENCE, persona=CallPersona.ASSISTANT)+ CallMessageModel(+ content=TTSPrompt.TIMEOUT_SILENCE, persona=CallPersona.ASSISTANT+ ))await handle_recognize(call=call,@@ -371,14 +383,19 @@ async def call_event_post(request: Request, call_id: UUID) -> None:elif error_code == 9999: # Unknown internal server error_logger.warn("Error during media play, unknown internal server error")else:- _logger.warn(f"Error during media play, unknown error code {error_code}")-+ _logger.warn(+ f"Error during media play, unknown error code {error_code}"+ )- elif event_type == "Microsoft.Communication.CallTransferAccepted": # Call transfer accepted+ elif (+ event_type == "Microsoft.Communication.CallTransferAccepted"+ ): # Call transfer accepted_logger.info(f"Call transfer accepted event ({call.id})")# TODO: Is there anything to do here?- elif event_type == "Microsoft.Communication.CallTransferFailed": # Call transfer failed+ elif (+ event_type == "Microsoft.Communication.CallTransferFailed"+ ): # Call transfer failed_logger.debig(f"Call transfer failed event ({call.id})")result_information = event.data["resultInformation"]sub_code = result_information["subCode"]@@ -461,7 +478,9 @@ async def handle_play(See: https://learn.microsoft.com/en-us/azure/ai-services/speech-service/language-support?tabs=tts"""if store:- call.messages.append(CallMessageModel(content=text, persona=CallPersona.ASSISTANT))+ call.messages.append(+ CallMessageModel(content=text, persona=CallPersona.ASSISTANT)+ )try:client.play_media_to_all(play_source=audio_from_text(text), operation_context=context@@ -715,11 +734,13 @@ async def gpt_chat(call: CallModel) -> ActionModel:elif name == IndentAction.NEW_REMINDER:intent = IndentAction.NEW_REMINDERparameters = json.loads(arguments)- call.reminders.append(ReminderModel(- description=parameters["description"],- due_date_time=parameters["due_date_time"],- title=parameters["title"],- ))+ call.reminders.append(+ ReminderModel(+ description=parameters["description"],+ due_date_time=parameters["due_date_time"],+ title=parameters["title"],+ )+ )model.content = f"New reminder created for \"{parameters['due_date_time']}\" with title \"{parameters['title']}\" and description \"{parameters['description']}\"."models.append(model)@@ -858,7 +879,9 @@ def callback_url(caller_id: str) -> str:def init_db():- db.execute("CREATE TABLE IF NOT EXISTS calls (id VARCHAR(32) PRIMARY KEY, phone_number TEXT, data TEXT, created_at TEXT)")+ db.execute(+ "CREATE TABLE IF NOT EXISTS calls (id VARCHAR(32) PRIMARY KEY, phone_number TEXT, data TEXT, created_at TEXT)"+ )db.commit()