Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
config: Allow prompts to be overriden from config
Clémence Lesnédb67ef869096
diff --git a/helpers/config_models/prompts.py b/helpers/config_models/prompts.pynew file mode 100644index 0000000..2061687--- /dev/null+++ b/helpers/config_models/prompts.py@@ -0,0 +1,281 @@+from datetime import datetime+from fastapi.encoders import jsonable_encoder+from models.claim import ClaimModel+from models.message import Action as MessageAction, MessageModel+from models.reminder import ReminderModel+from pydantic import BaseModel+from pydantic_settings import BaseSettings+from typing import List, Union+import json+++def _pydantic_to_str(obj: Union[BaseModel, List[BaseModel]]) -> str:+ return json.dumps(jsonable_encoder(obj))+++class SoundModel(BaseSettings, env_prefix="prompts_sound_"):+ loading_tpl: str = "{public_url}/loading.wav"+ ready_tpl: str = "{public_url}/ready.wav"++ def loading(self) -> str:+ from helpers.config import CONFIG++ return self.loading_tpl.format(+ public_url=CONFIG.resources.public_url,+ )++ def ready(self) -> str:+ from helpers.config import CONFIG++ return self.ready_tpl.format(+ public_url=CONFIG.resources.public_url,+ )+++class LlmModel(BaseSettings, env_prefix="prompts_llm_"):+ default_system_tpl: str = """+ Assistant called {bot_name} and is in a call center for the insurance company {bot_company} as an expert with 20 years of experience. Today is {date}. Customer is calling from {phone_number}. Call center number is {bot_phone_number}.+ """+ chat_system_tpl: str = """+ Assistant will help the customer with their insurance claim.++ Assistant:+ - Answers in {conversation_lang}, even if the customer speaks in English+ - Ask the customer to repeat or rephrase their question if it is not clear+ - Be proactive in the reminders you create, customer assistance is your priority+ - Cannot talk about any topic other than insurance claims+ - Do not ask the customer more than 2 questions in a row+ - Each conversation message is prefixed with the the action ({actions}), it adds context to the message, never add it in your answer+ - If user called multiple times, continue the discussion from the previous call+ - Is polite, helpful, and professional+ - Keep the sentences short and simple+ - Rephrase the customer's questions as statements and answer them+ - When the customer says a word and then spells out letters, this means that the word is written in the way the customer spelled it (e.g. "I live in Paris, P-A-R-I-S", "My name is John, J-O-H-N")++ Required customer data to be gathered by the assistant (if not already in the claim):+ - Address+ - Date and time of the incident+ - Insurance policy number+ - Location of the incident+ - Name (first and last)+ - Phone number or email address++ General process to follow:+ 1. Gather information to know the customer identity (e.g. name, policy number)+ 2. Gather general information about the incident to understand the situation (e.g. what, when, where)+ 3. Make sure the customer is safe (if not, refer to emergency services or the police)+ 4. Gather detailed information about the incident (e.g. identity of other people involved, witnesses, damages, how it happened)+ 5. Be proactive and create reminders for the customer (e.g. follup up on the claim, send documents)++ Assistant requires data from the customer to fill the claim. Latest claim data will be given. Assistant role is not over until all the relevant data is gathered.++ Claim status:+ {claim}++ Reminders:+ {reminders}+ """+ sms_summary_system_tpl: str = """+ Assistant will summarize the call with the customer in a single SMS. The customer cannot reply to this SMS.++ Assistant:+ - Answers in {conversation_lang}, even if the customer speaks in English+ - Briefly summarize the call with the customer+ - Can include personal details about the customer+ - Cannot talk about any topic other than insurance claims+ - Do not prefix the answer with any text (e.g. "The answer is", "Summary of the call")+ - Include details stored in the claim, to make the customer confident that the situation is understood+ - Include salutations (e.g. "Have a nice day", "Best regards", "Best wishes for recovery")+ - Is polite, helpful, and professional+ - Refer to the customer by their name, if known+ - Use simple and short sentences++ Claim status:+ {claim}++ Reminders:+ {reminders}++ Conversation history:+ {messages}+ """+ synthesis_short_system_tpl: str = """+ Assistant will summarize the call with the customer in a few words. The customer cannot reply to this message, but will read it in their web portal.++ Assistant:+ - Answers in {conversation_lang}, even if the customer speaks in English+ - Do not prefix the answer with any text (e.g. "The answer is", "Summary of the call")+ - Prefix the answer with a determiner (e.g. "the theft of your car", "your broken window")+ - Take into consideration all the conversation history, from the beginning++ Answer examples:+ - "the breakdown of your scooter"+ - "the flooding in your field"+ - "the theft of your car"+ - "the water damage in your kitchen"+ - "your broken window"++ Claim status:+ {claim}++ Reminders:+ {reminders}++ Conversation history:+ {messages}+ """+ synthesis_long_system_tpl: str = """+ Assistant will summarize the call with the customer in a paragraph. The customer cannot reply to this message, but will read it in their web portal.++ Assistant:+ - Answers in {conversation_lang}, even if the customer speaks in English+ - Do not include details of the call process+ - Do not include personal details (e.g. name, phone number, address)+ - Do not prefix the answer with any text (e.g. "The answer is", "Summary of the call")+ - Include details stored in the claim, to make the customer confident that the situation is understood+ - Prefer including details about the incident (e.g. what, when, where, how)+ - Say "you" to refer to the customer, and "I" to refer to the assistant+ - Take into consideration all the conversation history, from the beginning++ Claim status:+ {claim}++ Reminders:+ {reminders}++ Conversation history:+ {messages}+ """++ def default_system(self, phone_number: str) -> str:+ from helpers.config import CONFIG++ # TODO: Parse the date from the end-user timezone, allowing LLM to be used in multiple countries+ return self.default_system_tpl.format(+ bot_company=CONFIG.workflow.bot_company,+ bot_name=CONFIG.workflow.bot_name,+ bot_phone_number=CONFIG.communication_service.phone_number,+ date=datetime.now().isoformat(),+ phone_number=phone_number,+ )++ def chat_system(self, claim: ClaimModel, reminders: List[ReminderModel]) -> str:+ from helpers.config import CONFIG++ return self.chat_system_tpl.format(+ actions=", ".join([action.value for action in MessageAction]),+ claim=_pydantic_to_str(claim),+ conversation_lang=CONFIG.workflow.conversation_lang,+ reminders=_pydantic_to_str(reminders),+ )++ def sms_summary_system(+ self,+ claim: ClaimModel,+ messages: List[MessageModel],+ reminders: List[ReminderModel],+ ) -> str:+ from helpers.config import CONFIG++ return self.sms_summary_system_tpl.format(+ claim=_pydantic_to_str(claim),+ conversation_lang=CONFIG.workflow.conversation_lang,+ messages=_pydantic_to_str(messages),+ reminders=_pydantic_to_str(reminders),+ )++ def synthesis_short_system(+ self,+ claim: ClaimModel,+ messages: List[MessageModel],+ reminders: List[ReminderModel],+ ) -> str:+ from helpers.config import CONFIG++ return self.synthesis_short_system_tpl.format(+ claim=_pydantic_to_str(claim),+ conversation_lang=CONFIG.workflow.conversation_lang,+ messages=_pydantic_to_str(messages),+ reminders=_pydantic_to_str(reminders),+ )++ def synthesis_long_system(+ self,+ claim: ClaimModel,+ messages: List[MessageModel],+ reminders: List[ReminderModel],+ ) -> str:+ from helpers.config import CONFIG++ return self.synthesis_long_system_tpl.format(+ claim=_pydantic_to_str(claim),+ conversation_lang=CONFIG.workflow.conversation_lang,+ messages=_pydantic_to_str(messages),+ reminders=_pydantic_to_str(reminders),+ )+++class TtsModel(BaseSettings, env_prefix="prompts_tts_"):+ calltransfer_failure_tpl: str = "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_tpl: str = "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_tpl: str = (+ "Bien sûr, restez en ligne. Je vais vous transférer à un agent."+ )+ error_tpl: str = (+ "Je suis désolé, j'ai rencontré une erreur. Pouvez-vous répéter votre demande ?"+ )+ goodbye_tpl: str = "Merci de votre appel, j'espère avoir pu vous aider. N'hésitez pas à rappeler, j'ai tout mémorisé. {bot_company} vous souhaite une excellente journée !"+ hello_tpl: str = "Bonjour, je suis {bot_name}, l'assistant {bot_company} ! Je suis spécialiste des sinistres. Je ne peux pas travailler et écouter en même temps. Voici comment je fonctionne : lorsque je travaillerai, vous entendrez une petite musique ; après, au bip, ce sera à votre tour de parler. Vous pouvez me parler comme à un humain, je comprendrai la conversation. Je suis là pour vous aider. Quel est l'objet de votre appel ?"+ timeout_silence_tpl: str = "Je suis désolé, je n'ai rien entendu. Si vous avez besoin d'aide, dites-moi comment je peux vous aider."+ welcome_back_tpl: str = "Bonjour, je suis {bot_name}, l'assistant {bot_company} ! Je vois que vous avez déjà appelé il y a moins de {conversation_timeout_hour} heures. Laissez-moi quelques secondes pour récupérer votre dossier..."+ timeout_loading_tpl: str = (+ "Je mets plus de temps que prévu à vous répondre. Merci de votre patience..."+ )++ def calltransfer_failure(self) -> str:+ return self.calltransfer_failure_tpl++ def connect_agent(self) -> str:+ return self.connect_agent_tpl++ def end_call_to_connect_agent(self) -> str:+ return self.end_call_to_connect_agent_tpl++ def error(self) -> str:+ return self.error_tpl++ def goodbye(self) -> str:+ from helpers.config import CONFIG++ return self.goodbye_tpl.format(+ bot_company=CONFIG.workflow.bot_company,+ )++ def hello(self) -> str:+ from helpers.config import CONFIG++ return self.hello_tpl.format(+ bot_company=CONFIG.workflow.bot_company,+ bot_name=CONFIG.workflow.bot_name,+ )++ def timeout_silence(self) -> str:+ return self.timeout_silence_tpl++ def welcome_back(self) -> str:+ from helpers.config import CONFIG++ return self.welcome_back_tpl.format(+ bot_company=CONFIG.workflow.bot_company,+ bot_name=CONFIG.workflow.bot_name,+ conversation_timeout_hour=CONFIG.workflow.conversation_timeout_hour,+ )++ def timeout_loading(self) -> str:+ return self.timeout_loading_tpl+++class PromptsModel(BaseSettings, env_prefix="prompts_"):+ llm: LlmModel = LlmModel() # Object is fully defined by default+ sounds: SoundModel = SoundModel() # Object is fully defined by default+ tts: TtsModel = TtsModel() # Object is fully defined by defaultdiff --git a/helpers/config_models/root.py b/helpers/config_models/root.pyindex a88b5c2..959feac 100644--- a/helpers/config_models/root.py+++ b/helpers/config_models/root.py@@ -4,6 +4,7 @@ from helpers.config_models.communication_service import CommunicationServiceModefrom helpers.config_models.database import DatabaseModelfrom helpers.config_models.monitoring import MonitoringModelfrom helpers.config_models.openai import OpenAiModel+from helpers.config_models.prompts import PromptsModelfrom helpers.config_models.resources import ResourcesModelfrom helpers.config_models.workflow import WorkflowModelfrom pydantic import Field@@ -17,6 +18,7 @@ class RootModel(BaseSettings, env_prefix=""):database: DatabaseModelmonitoring: MonitoringModelopenai: OpenAiModel+ prompts: PromptsModel = PromptsModel() # Object is fully defined by defaultresources: ResourcesModelversion: str = Field(frozen=True)workflow: WorkflowModeldiff --git a/helpers/prompts.py b/helpers/prompts.pydeleted file mode 100644index 2bc780a..0000000--- a/helpers/prompts.py+++ /dev/null@@ -1,142 +0,0 @@-from enum import Enum-from helpers.config import CONFIG-from models.message import Action as MessageAction---class Sounds(str, Enum):- LOADING = f"{CONFIG.resources.public_url}/loading.wav"- READY = f"{CONFIG.resources.public_url}/ready.wav"---class LLM(str, Enum):- DEFAULT_SYSTEM = f"""- Assistant called {CONFIG.workflow.bot_name} and is in a call center for the insurance company {CONFIG.workflow.bot_company} as an expert with 20 years of experience. Today is {{date}}. Customer is calling from {{phone_number}}. Call center number is {CONFIG.communication_service.phone_number}.- """- CHAT_SYSTEM = f"""- Assistant will help the customer with their insurance claim.-- Assistant:- - Answers in {CONFIG.workflow.conversation_lang}, even if the customer speaks in English- - Ask the customer to repeat or rephrase their question if it is not clear- - Be proactive in the reminders you create, customer assistance is your priority- - Cannot talk about any topic other than insurance claims- - Do not ask the customer more than 2 questions in a row- - Each conversation message is prefixed with the the action ({', '.join([action.value for action in MessageAction])}), it adds context to the message, never add it in your answer- - If user called multiple times, continue the discussion from the previous call- - Is polite, helpful, and professional- - Keep the sentences short and simple- - Rephrase the customer's questions as statements and answer them- - When the customer says a word and then spells out letters, this means that the word is written in the way the customer spelled it (e.g. "I live in Paris, P-A-R-I-S", "My name is John, J-O-H-N")-- Required customer data to be gathered by the assistant (if not already in the claim):- - Address- - Date and time of the incident- - Insurance policy number- - Location of the incident- - Name (first and last)- - Phone number or email address-- General process to follow:- 1. Gather information to know the customer identity (e.g. name, policy number)- 2. Gather general information about the incident to understand the situation (e.g. what, when, where)- 3. Make sure the customer is safe (if not, refer to emergency services or the police)- 4. Gather detailed information about the incident (e.g. identity of other people involved, witnesses, damages, how it happened)- 5. Be proactive and create reminders for the customer (e.g. follup up on the claim, send documents)-- Assistant requires data from the customer to fill the claim. Latest claim data will be given. Assistant role is not over until all the relevant data is gathered.-- Claim status:- {{claim}}-- Reminders:- {{reminders}}- """- SMS_SUMMARY_SYSTEM = f"""- Assistant will summarize the call with the customer in a single SMS. The customer cannot reply to this SMS.-- Assistant:- - Answers in {CONFIG.workflow.conversation_lang}, even if the customer speaks in English- - Briefly summarize the call with the customer- - Can include personal details about the customer- - Cannot talk about any topic other than insurance claims- - Do not prefix the answer with any text (e.g. "The answer is", "Summary of the call")- - Include details stored in the claim, to make the customer confident that the situation is understood- - Include salutations (e.g. "Have a nice day", "Best regards", "Best wishes for recovery")- - Is polite, helpful, and professional- - Refer to the customer by their name, if known- - Use simple and short sentences-- Claim status:- {{claim}}-- Reminders:- {{reminders}}-- Conversation history:- {{conversation}}- """- SYNTHESIS_SHORT_SYSTEM = f"""- Assistant will summarize the call with the customer in a few words. The customer cannot reply to this message, but will read it in their web portal.-- Assistant:- - Answers in {CONFIG.workflow.conversation_lang}, even if the customer speaks in English- - Do not prefix the answer with any text (e.g. "The answer is", "Summary of the call")- - Prefix the answer with a determiner (e.g. "the theft of your car", "your broken window")- - Take into consideration all the conversation history, from the beginning-- Answer examples:- - "the breakdown of your scooter"- - "the flooding in your field"- - "the theft of your car"- - "the water damage in your kitchen"- - "your broken window"-- Claim status:- {{claim}}-- Reminders:- {{reminders}}-- Conversation history:- {{conversation}}- """- SYNTHESIS_LONG_SYSTEM = f"""- Assistant will summarize the call with the customer in a paragraph. The customer cannot reply to this message, but will read it in their web portal.-- Assistant:- - Answers in {CONFIG.workflow.conversation_lang}, even if the customer speaks in English- - Do not include details of the call process- - Do not include personal details (e.g. name, phone number, address)- - Do not prefix the answer with any text (e.g. "The answer is", "Summary of the call")- - Include details stored in the claim, to make the customer confident that the situation is understood- - Prefer including details about the incident (e.g. what, when, where, how)- - Say "you" to refer to the customer, and "I" to refer to the assistant- - Take into consideration all the conversation history, from the beginning-- Claim status:- {{claim}}-- Reminders:- {{reminders}}-- Conversation history:- {{conversation}}- """---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 ?"- )- 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. Je ne peux pas travailler et écouter en même temps. Voici comment je fonctionne : lorsque je travaillerai, vous entendrez une petite musique ; après, au bip, ce sera à votre tour de parler. Vous pouvez me parler comme à un humain, je comprendrai la conversation. Je suis là pour vous aider. Quel est l'objet de votre appel ?"- TIMEOUT_SILENCE = "Je suis désolé, je n'ai rien entendu. Si vous avez besoin d'aide, dites-moi comment je peux vous aider."- WELCOME_BACK = f"Bonjour, je suis {CONFIG.workflow.bot_name}, l'assistant {CONFIG.workflow.bot_company} ! Je vois que vous avez déjà appelé il y a moins de {CONFIG.workflow.conversation_timeout_hour} heures. Laissez-moi quelques secondes pour récupérer votre dossier..."- TIMEOUT_LOADING = (- "Je mets plus de temps que prévu à vous répondre. Merci de votre patience..."- )diff --git a/main.py b/main.pyindex cb97e67..d1307ea 100644--- a/main.py+++ b/main.py@@ -18,15 +18,12 @@ from azure.core.exceptions import ResourceNotFoundErrorfrom azure.core.messaging import CloudEventfrom azure.eventgrid import EventGridEvent, SystemEventNamesfrom azure.identity import DefaultAzureCredential, get_bearer_token_provider-from datetime import datetimefrom enum import Enumfrom fastapi import FastAPI, status, Request, HTTPException, BackgroundTasks-from fastapi.encoders import jsonable_encoderfrom fastapi.responses import JSONResponse, HTMLResponsefrom helpers.config import CONFIGfrom helpers.config_models.database import Mode as DatabaseModefrom helpers.logging import build_logger-from helpers.prompts import LLM as LLMPrompt, TTS as TTSPrompt, Sounds as SoundPromptfrom jinja2 import Environment, FileSystemLoader, select_autoescapefrom models.action import ActionModel, Indent as IndentActionfrom models.call import CallModel@@ -220,10 +217,14 @@ async def call_event_post(request: Request, background_tasks: BackgroundTasks, phone_number: str) -> None:for event_dict in await request.json():- background_tasks.add_task(communication_event_worker, event_dict, phone_number)+ background_tasks.add_task(+ communication_event_worker, background_tasks, event_dict, phone_number+ )-async def communication_event_worker(event_dict: dict, phone_number: str) -> None:+async def communication_event_worker(+ background_tasks: BackgroundTasks, event_dict: dict, phone_number: str+) -> None:call = await db.call_asearch_one(phone_number)if not call:_logger.warn(f"Call with {phone_number} not found")@@ -254,18 +255,16 @@ async def communication_event_worker(event_dict: dict, phone_number: str) -> Nonif len(call.messages) == 1: # First callawait handle_recognize_text(- call=call,- client=client,- text=TTSPrompt.HELLO,+ call=call, client=client, text=CONFIG.prompts.tts.hello())else: # Returning callawait handle_play(call=call,client=client,- text=TTSPrompt.WELCOME_BACK,+ text=CONFIG.prompts.tts.welcome_back(),)- call = await intelligence(call, client)+ call = await intelligence(background_tasks, call, client)elif event_type == "Microsoft.Communication.CallDisconnected": # Call hung up_logger.info(f"Call disconnected ({call.call_id})")@@ -282,7 +281,7 @@ async def communication_event_worker(event_dict: dict, phone_number: str) -> Noncall.messages.append(MessageModel(content=speech_text, persona=MessagePersona.HUMAN))- call = await intelligence(call, client)+ call = await intelligence(background_tasks, call, client)elif (event_type == "Microsoft.Communication.RecognizeFailed"@@ -301,7 +300,7 @@ async def communication_event_worker(event_dict: dict, phone_number: str) -> Nonawait handle_recognize_text(call=call,client=client,- text=TTSPrompt.TIMEOUT_SILENCE,+ text=CONFIG.prompts.tts.timeout_silence(),)call.recognition_retry += 1@@ -310,7 +309,7 @@ async def communication_event_worker(event_dict: dict, phone_number: str) -> Noncall=call,client=client,context=Context.GOODBYE,- text=TTSPrompt.GOODBYE,+ text=CONFIG.prompts.tts.goodbye(),)elif event_type == "Microsoft.Communication.PlayCompleted": # Media played@@ -363,19 +362,21 @@ async def communication_event_worker(event_dict: dict, phone_number: str) -> Noncall=call,client=client,context=Context.TRANSFER_FAILED,- text=TTSPrompt.CALLTRANSFER_FAILURE,+ text=CONFIG.prompts.tts.calltransfer_failure(),)await db.call_aset(call)-async def intelligence(call: CallModel, client: CallConnectionClient) -> CallModel:+async def intelligence(+ background_tasks: BackgroundTasks, call: CallModel, client: CallConnectionClient+) -> CallModel:"""Handle the intelligence of the call, including: GPT chat, GPT completion, TTS, and media play.Play the loading sound while waiting for the intelligence to be processed. If the intelligence is not processed after 15 seconds, play the timeout sound. If the intelligence is not processed after 30 seconds, stop the intelligence processing and play the error sound."""- chat_task = asyncio.create_task(gpt_chat(call))+ chat_task = asyncio.create_task(gpt_chat(background_tasks, call))soft_timeout_task = asyncio.create_task(asyncio.sleep(CONFIG.workflow.intelligence_soft_timeout_sec))@@ -392,7 +393,7 @@ async def intelligence(call: CallModel, client: CallConnectionClient) -> CallModawait handle_media(call=call,client=client,- sound=SoundPrompt.LOADING,+ sound_url=CONFIG.prompts.sounds.loading(),)# Break when chat coroutine is doneif chat_task.done():@@ -420,7 +421,7 @@ async def intelligence(call: CallModel, client: CallConnectionClient) -> CallModawait handle_play(call=call,client=client,- text=TTSPrompt.TIMEOUT_LOADING,+ text=CONFIG.prompts.tts.timeout_loading(),)# Wait to not block the event loop and play too many soundsawait asyncio.sleep(5)@@ -432,7 +433,9 @@ async def intelligence(call: CallModel, client: CallConnectionClient) -> CallMod_logger.debug(f"Error loading intelligence ({call.call_id}), answering with default error")- chat_action = ActionModel(content=TTSPrompt.ERROR, intent=IndentAction.CONTINUE)+ chat_action = ActionModel(+ content=CONFIG.prompts.tts.error(), intent=IndentAction.CONTINUE+ )_logger.info(f"Chat ({call.call_id}): {chat_action}")@@ -441,7 +444,7 @@ async def intelligence(call: CallModel, client: CallConnectionClient) -> CallModcall=call,client=client,context=Context.CONNECT_AGENT,- text=TTSPrompt.END_CALL_TO_CONNECT_AGENT,+ text=CONFIG.prompts.tts.end_call_to_connect_agent(),)elif chat_action.intent == IndentAction.END_CALL:@@ -449,7 +452,7 @@ async def intelligence(call: CallModel, client: CallConnectionClient) -> CallModcall=call,client=client,context=Context.GOODBYE,- text=TTSPrompt.GOODBYE,+ text=CONFIG.prompts.tts.goodbye(),)elif chat_action.intent in (@@ -467,7 +470,7 @@ async def intelligence(call: CallModel, client: CallConnectionClient) -> CallModtext=chat_action.content,)# Recursively call intelligence to continue the conversation- call = await intelligence(call, client)+ call = await intelligence(background_tasks, call, client)else:await handle_recognize_text(@@ -522,23 +525,18 @@ async def handle_play(_logger.debug(f"Call hung up before playing ({call.call_id})")-async def gpt_completion(system: LLMPrompt, call: CallModel) -> str:+async def gpt_completion(system: str, call: CallModel) -> str:_logger.debug(f"Running GPT completion ({call.call_id})")messages = [{- "content": LLMPrompt.DEFAULT_SYSTEM.format(- date=datetime.now().strftime("%A %d %B %Y %H:%M:%S"),+ "content": CONFIG.prompts.llm.default_system(phone_number=call.phone_number,),"role": "system",},{- "content": system.format(- claim=json.dumps(jsonable_encoder(call.claim)),- conversation=json.dumps(jsonable_encoder(call.messages)),- reminders=json.dumps(jsonable_encoder(call.reminders)),- ),+ "content": system,"role": "system",},]@@ -560,21 +558,22 @@ async def gpt_completion(system: LLMPrompt, call: CallModel) -> str:return content or ""-async def gpt_chat(call: CallModel) -> Tuple[CallModel, ActionModel]:+async def gpt_chat(+ background_tasks: BackgroundTasks, call: CallModel+) -> Tuple[CallModel, ActionModel]:_logger.debug(f"Running GPT chat ({call.call_id})")messages = [{- "content": LLMPrompt.DEFAULT_SYSTEM.format(- date=datetime.now().strftime("%A %d %B %Y %H:%M:%S"),+ "content": CONFIG.prompts.llm.default_system(phone_number=call.phone_number,),"role": "system",},{- "content": LLMPrompt.CHAT_SYSTEM.format(- claim=json.dumps(jsonable_encoder(call.claim)),- reminders=json.dumps(jsonable_encoder(call.reminders)),+ "content": CONFIG.prompts.llm.chat_system(+ claim=call.claim,+ reminders=call.reminders,),"role": "system",},@@ -652,7 +651,7 @@ async def gpt_chat(call: CallModel) -> Tuple[CallModel, ActionModel]:{"type": "function","function": {- "description": "Use this if the user wants to create a new claim. This will reset the claim and reminder data. Old is stored but not accessible anymore. Approval from the customer must be explicitely given. Do not use this action twice in a row. Example: 'I want to create a new claim'.",+ "description": "Use this if the user wants to create a new claim for a totally different subject. This will reset the claim and reminder data. Old is stored but not accessible anymore. Approval from the customer must be explicitely given. Example: 'I want to create a new claim'.","name": IndentAction.NEW_CLAIM.value,"parameters": {"properties": {@@ -785,7 +784,13 @@ async def gpt_chat(call: CallModel) -> Tuple[CallModel, ActionModel]:elif name == IndentAction.UPDATED_CLAIM.value:intent = IndentAction.UPDATED_CLAIM- parameters = json.loads(arguments)+ try:+ parameters = json.loads(arguments)+ except Exception:+ _logger.warn(+ f"LLM send back invalid JSON for {arguments}, ignoring this tool call"+ )+ continueif not customer_response_prop in parameters:_logger.warn(@@ -804,7 +809,13 @@ async def gpt_chat(call: CallModel) -> Tuple[CallModel, ActionModel]:elif name == IndentAction.NEW_CLAIM.value:intent = IndentAction.NEW_CLAIM- parameters = json.loads(arguments)+ try:+ parameters = json.loads(arguments)+ except Exception:+ _logger.warn(+ f"LLM send back invalid JSON for {arguments}, ignoring this tool call"+ )+ continueif not customer_response_prop in parameters:_logger.warn(@@ -813,6 +824,9 @@ async def gpt_chat(call: CallModel) -> Tuple[CallModel, ActionModel]:else:content += parameters[customer_response_prop] + " "+ # Generate synthesis for the old claim+ background_tasks.add_task(post_call_synthesis, call)+# Add context of the last message, if not, LLM messed up and loop on this actionlast_message = call.messages[-1]call = CallModel(phone_number=call.phone_number)@@ -821,7 +835,13 @@ async def gpt_chat(call: CallModel) -> Tuple[CallModel, ActionModel]:elif name == IndentAction.NEW_OR_UPDATED_REMINDER.value:intent = IndentAction.NEW_OR_UPDATED_REMINDER- parameters = json.loads(arguments)+ try:+ parameters = json.loads(arguments)+ except Exception:+ _logger.warn(+ f"LLM send back invalid JSON for {arguments}, ignoring this tool call"+ )+ continueif not customer_response_prop in parameters:_logger.warn(@@ -876,7 +896,7 @@ async def gpt_chat(call: CallModel) -> Tuple[CallModel, ActionModel]:return (call,- ActionModel(content=TTSPrompt.ERROR, intent=IndentAction.CONTINUE),+ ActionModel(content=CONFIG.prompts.tts.error(), intent=IndentAction.CONTINUE),)@@ -902,14 +922,14 @@ async def handle_recognize_text(await handle_recognize_media(call=call,client=client,- sound=SoundPrompt.READY,+ sound_url=CONFIG.prompts.sounds.ready(),)async def handle_recognize_media(client: CallConnectionClient,call: CallModel,- sound: SoundPrompt,+ sound_url: str,) -> None:"""Play a media to a call participant and start recognizing the response.@@ -920,7 +940,7 @@ async def handle_recognize_media(client.start_recognizing_media(end_silence_timeout=3, # Sometimes user includes breaks in their speechinput_type=RecognizeInputType.SPEECH,- play_prompt=FileSource(url=sound),+ play_prompt=FileSource(url=sound_url),speech_language=CONFIG.workflow.conversation_lang,target_participant=PhoneNumberIdentifier(call.phone_number),)@@ -931,13 +951,13 @@ async def handle_recognize_media(async def handle_media(client: CallConnectionClient,call: CallModel,- sound: SoundPrompt,+ sound_url: str,context: Optional[str] = None,) -> None:try:client.play_media(operation_context=context,- play_source=FileSource(url=sound),+ play_source=FileSource(url=sound_url),)except ResourceNotFoundError:_logger.debug(f"Call hung up before playing ({call.call_id})")@@ -969,7 +989,12 @@ async def post_call_sms(call: CallModel) -> None:"""Send an SMS report to the customer."""- content = await gpt_completion(LLMPrompt.SMS_SUMMARY_SYSTEM, call)+ content = await gpt_completion(+ CONFIG.prompts.llm.sms_summary_system(+ call.claim, call.messages, call.reminders+ ),+ call,+ )_logger.info(f"SMS report ({call.call_id}): {content}")try:@@ -1040,8 +1065,18 @@ async def post_call_synthesis(call: CallModel) -> None:_logger.debug(f"Synthesizing call ({call.call_id})")short, long = await asyncio.gather(- gpt_completion(LLMPrompt.SYNTHESIS_SHORT_SYSTEM, call),- gpt_completion(LLMPrompt.SYNTHESIS_LONG_SYSTEM, call),+ gpt_completion(+ CONFIG.prompts.llm.synthesis_short_system(+ call.claim, call.messages, call.reminders+ ),+ call,+ ),+ gpt_completion(+ CONFIG.prompts.llm.synthesis_long_system(+ call.claim, call.messages, call.reminders+ ),+ call,+ ),)_logger.info(f"Short synthesis ({call.call_id}): {short}")_logger.info(f"Long synthesis ({call.call_id}): {long}")@@ -1050,3 +1085,4 @@ async def post_call_synthesis(call: CallModel) -> None:long=long,short=short,)+ await db.call_aset(call)