Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
feat: Allow user to choose the conversation language
Clémence Lesné3ad1a7cb1817
diff --git a/README.md b/README.mdindex 5444a52..b9d243f 100644--- a/README.md+++ b/README.md@@ -47,6 +47,7 @@ Extract of the data stored during the call:- [x] Access the claim on a public website- [x] Access to customer conversation history+- [x] Allow user to change the language of the conversation- [x] Bot can be called from a phone number- [x] Bot use multiple voice tones (e.g. happy, sad, neutral) to keep the conversation engaging- [x] Company products (= lexicon) can be understood by the bot (e.g. a name of a specific insurance product)@@ -106,9 +107,11 @@ graph LRdb[("Conversations and claims\n(Cosmos DB or SQLite)")]event_grid[("Broker\n(Event Grid)")]gpt["GPT-4 Turbo\n(OpenAI)"]+ translation["Translation\n(Cognitive Services)"]endapi -- Answer with text --> communication_service+ api -- Ask for translation --> translationapi -- Few-shot training --> ai_searchapi -- Generate completion --> gptapi -- Save conversation --> db@@ -211,6 +214,7 @@ workflow:agent_phone_number: "+33612345678"bot_company: Contosobot_name: Robert+ lang: {}communication_service:phone_number: "+33612345678"@@ -264,11 +268,9 @@ communication_service:access_key: xxxendpoint: https://xxx.france.communication.azure.comphone_number: "+33612345678"- voice_name: fr-FR-DeniseNeuralcognitive_service:# Must be of type "AI services multi-service account"- # See: https://learn.microsoft.com/en-us/azure/ai-services/multi-service-resource?tabs=macos&pivots=azportal#create-a-new-multi-service-resourceendpoint: https://xxx.cognitiveservices.azure.comopenai:@@ -373,7 +375,7 @@ prompts:Assistant will provide internal IT support to employees. Assistant requires data from the employee to provide IT support. The assistant's role is not over until the issue is resolved or the request is fulfilled.# Rules- - Answers in {conversation_lang}, even if the employee speaks in a different language+ - Answers in {default_lang}, even if the customer speaks another language- Cannot talk about any topic other than IT support- Is polite, helpful, and professional- Rephrase the employee's questions as statements and answer them@@ -401,6 +403,28 @@ prompts:{reminders}```+### Customize the languages++The bot can be used in multiple languages. It can understand the language the user chose.++See the [list of supported languages](https://learn.microsoft.com/en-us/azure/ai-services/speech-service/language-support?tabs=tts#supported-languages) for the Text-to-Speech service.++```yaml+# config.yaml+[...]++workflow:+ lang:+ default_short_code: "fr-FR"+ availables:+ - pronunciations_en: ["French", "FR", "France"]+ short_code: "fr-FR"+ voice_name: "fr-FR-DeniseNeural"+ - pronunciations_en: ["Chinese", "ZH", "China"]+ short_code: "zh-CN"+ voice_name: "zh-CN-XiaoxiaoNeural"+```+### Customize the moderation levelsLevels are defined for each category of Content Safety. The higher the score, the more strict the moderation is, from 0 to 7.diff --git a/bicep/app.bicep b/bicep/app.bicepindex 5b4339d..94e69ad 100644--- a/bicep/app.bicep+++ b/bicep/app.bicep@@ -4,7 +4,6 @@ param agentPhoneNumber stringparam botCompany stringparam botName stringparam botPhoneNumber string-param botVoiceName stringparam gptModel stringparam gptVersion stringparam imageVersion string@@ -38,12 +37,12 @@ var config = {agent_phone_number: agentPhoneNumberbot_company: botCompanybot_name: botName+ lang: loadYamlContent('../config.yaml').workflow.lang}communication_service: {access_key: communication.listKeys().primaryKeyendpoint: communication.properties.hostNamephone_number: botPhoneNumber- voice_name: botVoiceName}cognitive_service: {endpoint: cognitiveCommunication.properties.endpoint@@ -68,6 +67,10 @@ var config = {llm: loadYamlContent('../config.yaml').prompts.llmtts: loadYamlContent('../config.yaml').prompts.tts}+ ai_translation: {+ access_key: translate.listKeys().key1+ endpoint: 'https://${translate.name}.cognitiveservices.azure.com/'+ }}output appUrl string = appUrl@@ -81,7 +84,7 @@ resource logAnalyticsWorkspace 'Microsoft.OperationalInsights/workspaces@2022-10properties: {retentionInDays: 30sku: {- name: 'PerGB2018'+ name: 'PerGB2018' // Pay-as-you-go}}}@@ -221,7 +224,7 @@ resource cognitiveCommunication 'Microsoft.CognitiveServices/accounts@2023-10-01location: locationtags: tagssku: {- name: 'S0'+ name: 'S0' // Only one available}kind: 'CognitiveServices'properties: {@@ -234,7 +237,7 @@ resource cognitiveDocument 'Microsoft.CognitiveServices/accounts@2023-10-01-prevlocation: locationtags: tagssku: {- name: 'S0'+ name: 'S0' // Pay-as-you-go}kind: 'FormRecognizer'properties: {@@ -247,7 +250,7 @@ resource cognitiveContentsafety 'Microsoft.CognitiveServices/accounts@2023-10-01location: locationtags: tagssku: {- name: 'S0'+ name: 'S0' // Pay-as-you-go}kind: 'ContentSafety'properties: {@@ -278,7 +281,7 @@ resource cognitiveOpenai 'Microsoft.CognitiveServices/accounts@2023-10-01-previelocation: openaiLocationtags: tagssku: {- name: 'S0'+ name: 'S0' // Pay-as-you-go}kind: 'OpenAI'properties: {@@ -291,7 +294,7 @@ resource gpt 'Microsoft.CognitiveServices/accounts/deployments@2023-10-01-previename: gptModelFullNamesku: {capacity: 50- name: 'Standard'+ name: 'Standard' // Pay-as-you-go}properties: {// raiPolicyName: contentfilter.name@@ -367,7 +370,7 @@ resource ada 'Microsoft.CognitiveServices/accounts/deployments@2023-10-01-previename: adaModelFullNamesku: {capacity: 50- name: 'Standard'+ name: 'Standard' // Pay-as-you-go}properties: {// raiPolicyName: contentfilter.name@@ -460,7 +463,7 @@ resource search 'Microsoft.Search/searchServices@2023-11-01' = {location: searchLocationtags: tagssku: {- name: 'basic'+ name: 'basic' // Smallest with semantic search}identity: {type: 'SystemAssigned'@@ -469,3 +472,16 @@ resource search 'Microsoft.Search/searchServices@2023-11-01' = {semanticSearch: 'standard'}}++resource translate 'Microsoft.CognitiveServices/accounts@2023-10-01-preview' = {+ name: '${prefix}-translate'+ location: location+ tags: tags+ sku: {+ name: 'S1' // Pay-as-you-go+ }+ kind: 'TextTranslation'+ properties: {+ customSubDomainName: '${prefix}-translate'+ }+}diff --git a/bicep/main.bicep b/bicep/main.bicepindex 286cde4..d191438 100644--- a/bicep/main.bicep+++ b/bicep/main.bicep@@ -42,7 +42,6 @@ module app 'app.bicep' = {botCompany: botCompanybotName: botNamebotPhoneNumber: botPhoneNumber- botVoiceName: 'fr-FR-DeniseNeural'gptModel: gptModelgptVersion: gptVersionimageVersion: imageVersiondiff --git a/helpers/config_models/ai_translation.py b/helpers/config_models/ai_translation.pynew file mode 100644index 0000000..c3c0c10--- /dev/null+++ b/helpers/config_models/ai_translation.py@@ -0,0 +1,7 @@+from pydantic import SecretStr+from pydantic_settings import BaseSettings+++class AiTranslationModel(BaseSettings):+ access_key: SecretStr+ endpoint: strdiff --git a/helpers/config_models/communication_service.py b/helpers/config_models/communication_service.pyindex c350c93..11edab3 100644--- a/helpers/config_models/communication_service.py+++ b/helpers/config_models/communication_service.py@@ -11,4 +11,3 @@ class CommunicationServiceModel(BaseSettings):access_key: SecretStrendpoint: strphone_number: PhoneNumber- voice_name: strdiff --git a/helpers/config_models/prompts.py b/helpers/config_models/prompts.pyindex 484f509..f9f3097 100644--- a/helpers/config_models/prompts.py+++ b/helpers/config_models/prompts.py@@ -9,7 +9,8 @@ from models.message import (PersonaEnum as MessagePersona,StyleEnum as MessageStyle,)-from models.next import Action as NextAction+from azure.core.exceptions import HttpResponseError+from models.call import CallModelfrom models.next import ActionEnum as NextActionfrom models.reminder import ReminderModelfrom models.training import TrainingModel@@ -78,7 +79,7 @@ class LlmModel(BaseSettings):# Rules- Answer directly to the customer's questions- - Answers in {conversation_lang}, even if the customer speaks in English+ - Answers in {default_lang}, even if the customer speaks another language- Aways answer with at least one full sentence- Be proactive in the reminders you create, customer assistance is your priority- Do not ask for something which is already stored in the claim@@ -138,7 +139,7 @@ class LlmModel(BaseSettings):Assistant will summarize the call with the customer in a single SMS. The customer cannot reply to this SMS.# Rules- - Answers in {conversation_lang}, even if the customer speaks in English+ - Answers in {default_lang}, even if the customer speaks another language- Briefly summarize the call with the customer- Can include personal details about the customer- Cannot talk about any topic besides insurance claims@@ -165,7 +166,7 @@ class LlmModel(BaseSettings):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.# Rules- - Answers in {conversation_lang}, even if the customer speaks in English+ - Answers in {default_lang}, even if the customer speaks another language- 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")- Consider all the conversation history, from the beginning@@ -192,7 +193,7 @@ class LlmModel(BaseSettings):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.# Rules- - Answers in {conversation_lang}, even if the customer speaks in English+ - Answers in {default_lang}, even if the customer speaks another language- 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")@@ -309,80 +310,48 @@ class LlmModel(BaseSettings):))- def chat_system(- self,- claim: ClaimModel,- reminders: List[ReminderModel],- trainings: List[TrainingModel],- ) -> str:+ def chat_system(self, call: CallModel, trainings: List[TrainingModel]) -> str:from helpers.config import CONFIGreturn self._return(self.chat_system_tpl,actions=", ".join([action.value for action in MessageAction]),bot_company=CONFIG.workflow.bot_company,- claim=_pydantic_to_str(claim),- conversation_lang=CONFIG.workflow.conversation_lang,- reminders=_pydantic_to_str(reminders),+ claim=_pydantic_to_str(call.claim),+ default_lang=call.lang.human_name,+ reminders=_pydantic_to_str(call.reminders),styles=", ".join([style.value for style in MessageStyle]),trainings=trainings,)- def sms_summary_system(- self,- claim: ClaimModel,- messages: List[MessageModel],- reminders: List[ReminderModel],- ) -> str:- from helpers.config import CONFIG-+ def sms_summary_system(self, call: CallModel) -> str:return self._return(self.sms_summary_system_tpl,- claim=_pydantic_to_str(claim),- conversation_lang=CONFIG.workflow.conversation_lang,- messages=_pydantic_to_str(messages),- reminders=_pydantic_to_str(reminders),+ claim=_pydantic_to_str(call.claim),+ default_lang=call.lang.human_name,+ messages=_pydantic_to_str(call.messages),+ reminders=_pydantic_to_str(call.reminders),)- def synthesis_short_system(- self,- claim: ClaimModel,- messages: List[MessageModel],- reminders: List[ReminderModel],- ) -> str:- from helpers.config import CONFIG-+ def synthesis_short_system(self, call: CallModel) -> str:return self._return(self.synthesis_short_system_tpl,- claim=_pydantic_to_str(claim),- conversation_lang=CONFIG.workflow.conversation_lang,- messages=_pydantic_to_str(messages),- reminders=_pydantic_to_str(reminders),+ claim=_pydantic_to_str(call.claim),+ default_lang=call.lang.human_name,+ messages=_pydantic_to_str(call.messages),+ reminders=_pydantic_to_str(call.reminders),)- def synthesis_long_system(- self,- claim: ClaimModel,- messages: List[MessageModel],- reminders: List[ReminderModel],- ) -> str:- from helpers.config import CONFIG-+ def synthesis_long_system(self, call: CallModel) -> str:return self._return(self.synthesis_long_system_tpl,- claim=_pydantic_to_str(claim),- conversation_lang=CONFIG.workflow.conversation_lang,- messages=_pydantic_to_str(messages),- reminders=_pydantic_to_str(reminders),+ claim=_pydantic_to_str(call.claim),+ default_lang=call.lang.human_name,+ messages=_pydantic_to_str(call.messages),+ reminders=_pydantic_to_str(call.reminders),)- def citations_system(- self,- claim: ClaimModel,- messages: List[MessageModel],- reminders: List[ReminderModel],- text: Optional[str],- ) -> Optional[str]:+ def citations_system(self, call: CallModel, text: Optional[str]) -> Optional[str]:"""Return the formatted prompt. Prompt is used to add citations to the text, without cluttering the content itself.@@ -393,31 +362,26 @@ class LlmModel(BaseSettings):return self._return(self.citations_system_tpl,- claim=_pydantic_to_str(claim),+ claim=_pydantic_to_str(call.claim),messages=_pydantic_to_str([message- for message in messages+ for message in call.messagesif message.persona is not MessagePersona.TOOL],exclude={"tool_calls"},), # Filter out tool messages, to avoid LLM to cite itself- reminders=_pydantic_to_str(reminders),+ reminders=_pydantic_to_str(call.reminders),text=text,)- def next_system(- self,- claim: ClaimModel,- messages: List[MessageModel],- reminders: List[ReminderModel],- ) -> str:+ def next_system(self, call: CallModel) -> str:return self._return(self.next_system_tpl,actions=", ".join([action.value for action in NextAction]),- claim=_pydantic_to_str(claim),- messages=_pydantic_to_str(messages),- reminders=_pydantic_to_str(reminders),+ claim=_pydantic_to_str(call.claim),+ messages=_pydantic_to_str(call.messages),+ reminders=_pydantic_to_str(call.reminders),)def _return(@@ -444,84 +408,134 @@ class LlmModel(BaseSettings):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."+ tts_lang: str = "en-US"+ calltransfer_failure_tpl: str = (+ "It seems I can't connect you with an agent at the moment, but the next available agent will call you back as soon as possible.")- error_tpl: str = (- "Je suis désolé, j'ai rencontré une erreur. Pouvez-vous répéter votre demande ?"+ connect_agent_tpl: str = (+ "I'm sorry, I wasn't able to answer your request. Please allow me to transfer you to an agent who can assist you further. Please stay on the line and I will get back to you shortly."+ )+ end_call_to_connect_agent_tpl: str = (+ "Of course, stay on the line. I'll transfer you to an agent.")+ error_tpl: str = "I'm sorry, I've made a mistake. Could you repeat your request?"goodbye_tpl: str = (- "Merci de votre appel, j'espère avoir pu vous aider. Vous pouvez rappeler, j'ai tout mémorisé. {bot_company} vous souhaite une excellente journée !"+ "Thank you for calling, I hope I've been able to help. You can call back, I've got it all memorized. {bot_company} wishes you a wonderful day!")hello_tpl: str = """- Bonjour, je suis {bot_name}, l'assistant virtuel {bot_company} ! Je suis spécialiste des sinistres. Je ne peux pas travailler et écouter simultanément.+ Hello, I'm {bot_name}, the virtual assistant {bot_company}! I'm a claims specialist. I can't work and listen at the same time.- Voici comment je fonctionne : pendant que je traite vos informations, vous pourriez entendre une légère musique de fond. Dès que vous entendez le bip, c'est à vous de parler. N'hésitez pas à me parler de façon naturelle, je suis conçu pour comprendre vos requêtes.+ Here's how I work: while I'm processing your information, you might hear some light background music. As soon as you hear the beep, it's your turn to talk. Feel free to speak to me in a natural way - I'm designed to understand your requests.- Exemples de questions que vous pouvez me poser :- - "Je suis tombé de vélo hier, je me suis cassé le bras, ma voisine m'a emmené à l'hôpital"- - "J'ai eu un accident ce matin, je faisais des courses"+ Examples of questions you can ask me:+ - "I fell off my bike yesterday, broke my arm, my neighbor took me to hospital"+ - "I had an accident this morning, I was shopping".- Quel est votre problème ?+ What's your problem?"""- 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."+ timeout_silence_tpl: str = (+ "I'm sorry, I didn't hear anything. If you need help, let me know how I can help you."+ )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…"+ "Hello, I'm {bot_name}, assistant {bot_company}! I see you've already called less than {conversation_timeout_hour} hours ago. Please allow me a few seconds to retrieve your file…")timeout_loading_tpl: str = (- "Je mets plus de temps que prévu à vous répondre. Merci de votre patience…"+ "It's taking me longer than expected to reply. Thank you for your patience…")+ ivr_language_tpl: str = "To continue in {label}, press {index}."- def calltransfer_failure(self) -> str:- return self._return(self.calltransfer_failure_tpl)+ async def calltransfer_failure(self, call: CallModel) -> str:+ return await self._translate(self.calltransfer_failure_tpl, call)- def connect_agent(self) -> str:- return self._return(self.connect_agent_tpl)+ async def connect_agent(self, call: CallModel) -> str:+ return await self._translate(self.connect_agent_tpl, call)- def end_call_to_connect_agent(self) -> str:- return self._return(self.end_call_to_connect_agent_tpl)+ async def end_call_to_connect_agent(self, call: CallModel) -> str:+ return await self._translate(self.end_call_to_connect_agent_tpl, call)- def error(self) -> str:- return self._return(self.error_tpl)+ async def error(self, call: CallModel) -> str:+ return await self._translate(self.error_tpl, call)- def goodbye(self) -> str:+ async def goodbye(self, call: CallModel) -> str:from helpers.config import CONFIG- return self._return(+ return await self._translate(self.goodbye_tpl,+ call,bot_company=CONFIG.workflow.bot_company,)- def hello(self) -> str:+ async def hello(self, call: CallModel) -> str:from helpers.config import CONFIG- return self._return(+ return await self._translate(self.hello_tpl,+ call,bot_company=CONFIG.workflow.bot_company,bot_name=CONFIG.workflow.bot_name,)- def timeout_silence(self) -> str:- return self._return(self.timeout_silence_tpl)+ async def timeout_silence(self, call: CallModel) -> str:+ return await self._translate(self.timeout_silence_tpl, call)- def welcome_back(self) -> str:+ async def welcome_back(self, call: CallModel) -> str:from helpers.config import CONFIG- return self._return(+ return await self._translate(self.welcome_back_tpl,+ call,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._return(self.timeout_loading_tpl)+ async def timeout_loading(self, call: CallModel) -> str:+ return await self._translate(self.timeout_loading_tpl, call)++ async def ivr_language(self, call: CallModel) -> str:+ from helpers.config import CONFIG++ res = ""+ for i, lang in enumerate(CONFIG.workflow.lang.availables):+ res += (+ self._return(+ self.ivr_language_tpl,+ index=i + 1,+ label=lang.human_name,+ )+ + " "+ )+ return await self._translate(res.strip(), call)def _return(self, prompt_tpl: str, **kwargs) -> str:return dedent(prompt_tpl.format(**kwargs)).strip()+ async def _translate(self, prompt_tpl: str, call: CallModel, **kwargs) -> str:+ """+ Format the prompt and translate it to the TTS language.++ If the translation fails, the initial prompt is returned.+ """+ from helpers.translation import translate_text++ initial = self._return(prompt_tpl, **kwargs)+ translation = None+ try:+ translation = await translate_text(+ initial, self.tts_lang, call.lang.short_code+ )+ except HttpResponseError as e:+ self._logger.warning(f"Failed to translate TTS prompt: {e}")+ pass+ return translation or initial++ @computed_field+ @cached_property+ def _logger(self) -> Logger:+ from helpers.logging import build_logger++ return build_logger(__name__)+class PromptsModel(BaseSettings, env_prefix="prompts_"):llm: LlmModel = LlmModel() # Object is fully defined by defaultdiff --git a/helpers/config_models/root.py b/helpers/config_models/root.pyindex 49c3910..3176044 100644--- a/helpers/config_models/root.py+++ b/helpers/config_models/root.py@@ -1,4 +1,5 @@from helpers.config_models.ai_search import AiSearchModel+from helpers.config_models.ai_translation import AiTranslationModelfrom helpers.config_models.api import ApiModelfrom helpers.config_models.cognitive_service import CognitiveServiceModelfrom helpers.config_models.communication_service import CommunicationServiceModel@@ -18,6 +19,7 @@ class RootModel(BaseSettings, env_prefix=""):version: str = Field(frozen=True)# Editable fieldsai_search: AiSearchModel+ ai_translation: AiTranslationModelapi: ApiModelcognitive_service: CognitiveServiceModelcommunication_service: CommunicationServiceModeldiff --git a/helpers/config_models/workflow.py b/helpers/config_models/workflow.pyindex 72274c6..56ec9fb 100644--- a/helpers/config_models/workflow.py+++ b/helpers/config_models/workflow.py@@ -1,16 +1,78 @@+from functools import cached_propertyfrom pydantic_extra_types.phone_numbers import PhoneNumberfrom pydantic_settings import BaseSettings+from typing import List# E164 is standard accross all Microsoft servicesPhoneNumber.phone_format = "E164"+class LanguageEntryModel(BaseSettings):+ """+ Language entry, containing the standard short code, an human name and the Azure Text-to-Speech voice name.++ See: https://learn.microsoft.com/en-us/azure/ai-services/speech-service/language-support?tabs=tts#supported-languages+ """++ pronunciations_en: List[str]+ short_code: str+ voice: str++ @property+ def human_name(self) -> str:+ return self.pronunciations_en[0]++ def __str__(self): # Pretty print for logs+ return self.short_code+++class LanguageModel(BaseSettings):+ """+ Manage language for the workflow.+ """++ default_short_code: str = "fr-FR"+ availables: List[LanguageEntryModel] = [+ LanguageEntryModel(+ pronunciations_en=["French", "FR", "France"],+ short_code="fr-FR",+ voice="fr-FR-DeniseNeural",+ ),+ LanguageEntryModel(+ short_code="en-US",+ pronunciations_en=["English", "EN", "United States"],+ voice="en-US-AvaNeural",+ ),+ LanguageEntryModel(+ short_code="es-ES",+ pronunciations_en=["Spanish", "ES", "Spain"],+ voice="es-ES-ElviraNeural",+ ),+ LanguageEntryModel(+ short_code="zh-CN",+ pronunciations_en=["Chinese", "ZH", "China"],+ voice="zh-CN-XiaoxiaoNeural",+ ),+ ]++ @cached_property+ def default_lang(self) -> LanguageEntryModel:+ return next(+ (+ lang+ for lang in self.availables+ if self.default_short_code == lang.short_code+ ),+ self.availables[0],+ )++class WorkflowModel(BaseSettings, env_prefix="workflow_"):agent_phone_number: PhoneNumberbot_company: strbot_name: str- conversation_lang: str = "fr-FR" # Frenchconversation_timeout_hour: int = 72 # 3 daysintelligence_hard_timeout_sec: int = 180 # 3 minutesintelligence_soft_timeout_sec: int = 30 # 30 seconds+ lang: LanguageModel = LanguageModel() # Object is fully defined by defaultdiff --git a/helpers/translation.py b/helpers/translation.pynew file mode 100644index 0000000..d070149--- /dev/null+++ b/helpers/translation.py@@ -0,0 +1,64 @@+from azure.ai.translation.text.aio import TextTranslationClient+from azure.ai.translation.text.models import InputTextItem+from azure.core.credentials import AzureKeyCredential+from contextlib import asynccontextmanager+from helpers.config import CONFIG+from helpers.logging import build_logger+from typing import AsyncGenerator, Optional+from azure.core.exceptions import HttpResponseError+from tenacity import (+ retry,+ stop_after_attempt,+ wait_random_exponential,+ retry_if_exception_type,+)+++_logger = build_logger(__name__)+_logger.info(f"Using Translation {CONFIG.ai_translation.endpoint}")+_cache = {} # Local cache for translations, TODO: Use Redis+++@retry(+ reraise=True,+ retry=retry_if_exception_type(HttpResponseError),+ stop=stop_after_attempt(3),+ wait=wait_random_exponential(multiplier=0.5, max=30),+)+async def translate_text(+ text: str, source_lang: str, target_lang: str+) -> Optional[str]:+ """+ Translate text from source language to target language.++ Catch errors for a maximum of 3 times.+ """+ if source_lang == target_lang: # No need to translate+ return text++ cache_key = (text, source_lang, target_lang)+ if cache_key in _cache: # Search in cache+ return _cache[cache_key]++ async with _use_client() as client: # Perform translation+ res = await client.translate(+ content=[InputTextItem(text=text)], # type: ignore+ from_parameter=source_lang,+ to=[target_lang],+ )+ translation = res[0] if res else None+ translation = translation.translations[0].text if translation else None+ _cache[cache_key] = translation # Add to cache+ return translation+++@asynccontextmanager+async def _use_client() -> AsyncGenerator[TextTranslationClient, None]:+ client = TextTranslationClient(+ credential=AzureKeyCredential(+ CONFIG.ai_translation.access_key.get_secret_value()+ ),+ endpoint=CONFIG.ai_translation.endpoint,+ )+ yield client+ await client.close()diff --git a/main.py b/main.pyindex 3e44641..af4a05e 100644--- a/main.py+++ b/main.py@@ -12,8 +12,10 @@ from typing import Any, Callable, Coroutine, Generator, List, Optional, Tuple, Tfrom azure.communication.callautomation import (CallAutomationClient,CallConnectionClient,+ DtmfTone,FileSource,PhoneNumberIdentifier,+ RecognitionChoice,RecognizeInputType,SsmlSource,)@@ -28,6 +30,7 @@ from enum import Enumfrom fastapi import FastAPI, status, Request, HTTPException, BackgroundTasksfrom fastapi.responses import JSONResponse, HTMLResponsefrom helpers.config_models.database import ModeEnum as DatabaseMode+from helpers.logging import build_loggerfrom jinja2 import Environment, FileSystemLoader, select_autoescapefrom models.action import ActionModel, IndentEnum as IndentActionfrom models.call import CallModel@@ -240,14 +243,24 @@ async def call_inbound_post(request: Request):_logger.debug(f"Incoming call handler caller ID: {phone_number}")call_context = event.data["incomingCallContext"]- answer_call_result = call_automation_client.answer_call(- callback_url=await callback_url(phone_number),- cognitive_services_endpoint=CONFIG.cognitive_service.endpoint,- incoming_call_context=call_context,- )- _logger.info(- f"Answered call with {phone_number} ({answer_call_result.call_connection_id})"- )++ try:+ answer_call_result = call_automation_client.answer_call(+ callback_url=await callback_url(phone_number),+ cognitive_services_endpoint=CONFIG.cognitive_service.endpoint,+ incoming_call_context=call_context,+ )+ _logger.info(+ f"Answered call with {phone_number} ({answer_call_result.call_connection_id})"+ )+ except HttpResponseError as e:+ if (+ "lifetime validation of the signed http request failed"+ in e.message.lower()+ ):+ _logger.debug("Old call event received, ignoring")+ else:+ raise e@api.post(@@ -297,21 +310,12 @@ async def communication_event_worker())- if len(call.messages) == 1: # First call- await asyncio.sleep(1) # Wait for the call to be ready, sometimes an error "(8501) Action is invalid when call is not in Established state" is raised- await handle_recognize_text(- call=call,- client=client,- text=CONFIG.prompts.tts.hello(),- )-- else: # Returning call- await handle_play(- call=call,- client=client,- text=CONFIG.prompts.tts.welcome_back(),- )- call = await intelligence(background_tasks, call, client)+ await asyncio.sleep(+ 0.5+ ) # Wait for the call to be ready, sometimes an error "(8501) Action is invalid when call is not in Established state" is raised+ await handle_ivr_language(+ call=call, client=client+ ) # Every time a call is answered, confirm the languageelif event_type == "Microsoft.Communication.CallDisconnected": # Call hung up_logger.info(f"Call disconnected ({call.call_id})")@@ -332,6 +336,44 @@ async def communication_event_worker()call = await intelligence(background_tasks, call, client)+ elif recognition_result == "choices": # Handle IVR+ label_detected = event.data["choiceResult"]["label"]++ try:+ lang = next(+ (+ x+ for x in CONFIG.workflow.lang.availables+ if x.short_code == label_detected+ ),+ CONFIG.workflow.lang.default_lang,+ )+ _logger.info(f"IVR recognition ({call.call_id}): {lang}")+ except ValueError:+ _logger.warn(f"Unknown IVR {label_detected}, code not implemented")+ return++ _logger.info(f"Setting call language to {lang} ({call.call_id})")+ call.lang = lang+ await db.call_aset(+ call+ ) # Persist language change, if the user calls back before the first message, the language will be set++ if len(call.messages) == 1: # First call+ await handle_recognize_text(+ call=call,+ client=client,+ text=await CONFIG.prompts.tts.hello(call),+ )++ if len(call.messages) > 1: # Returning call+ await handle_play(+ call=call,+ client=client,+ text=await CONFIG.prompts.tts.welcome_back(call),+ )+ call = await intelligence(background_tasks, call, client)+elif (event_type == "Microsoft.Communication.RecognizeFailed"): # Speech recognition failed@@ -348,7 +390,7 @@ async def communication_event_worker(await handle_recognize_text(call=call,client=client,- text=CONFIG.prompts.tts.timeout_silence(),+ text=await CONFIG.prompts.tts.timeout_silence(call),)call.recognition_retry += 1else:@@ -356,15 +398,20 @@ async def communication_event_worker(call=call,client=client,context=ContextEnum.GOODBYE,- text=CONFIG.prompts.tts.goodbye(),+ text=await CONFIG.prompts.tts.goodbye(call),)else: # Other recognition error- _logger.warn(f"Recognition failed with unknown error code {error_code}, answering with default error ({call.call_id})")+ if error_code == 8511: # Failure while trying to play the prompt+ _logger.warn(f"Failed to play prompt ({call.call_id})")+ else:+ _logger.warn(+ f"Recognition failed with unknown error code {error_code}, answering with default error ({call.call_id})"+ )await handle_recognize_text(call=call,client=client,- text=CONFIG.prompts.tts.error(),+ text=await CONFIG.prompts.tts.error(call),)elif event_type == "Microsoft.Communication.PlayCompleted": # Media played@@ -421,7 +468,7 @@ async def communication_event_worker(call=call,client=client,context=ContextEnum.TRANSFER_FAILED,- text=CONFIG.prompts.tts.calltransfer_failure(),+ text=await CONFIG.prompts.tts.calltransfer_failure(call),)await db.call_aset(call)@@ -494,7 +541,7 @@ async def intelligence(await handle_play(call=call,client=client,- text=CONFIG.prompts.tts.timeout_loading(),+ text=await CONFIG.prompts.tts.timeout_loading(call),)else: # Do not play timeout prompt plus loading, it can be frustrating for the userawait handle_media(@@ -513,7 +560,7 @@ async def intelligence(f"Error loading intelligence ({call.call_id}), answering with default error")chat_action = ActionModel(- content=CONFIG.prompts.tts.error(),+ content=await CONFIG.prompts.tts.error(call),intent=IndentAction.CONTINUE,)@@ -524,7 +571,7 @@ async def intelligence(call=call,client=client,context=ContextEnum.CONNECT_AGENT,- text=CONFIG.prompts.tts.end_call_to_connect_agent(),+ text=await CONFIG.prompts.tts.end_call_to_connect_agent(call),)elif chat_action.intent == IndentAction.END_CALL:@@ -532,7 +579,7 @@ async def intelligence(call=call,client=client,context=ContextEnum.GOODBYE,- text=CONFIG.prompts.tts.goodbye(),+ text=await CONFIG.prompts.tts.goodbye(call),)elif chat_action.intent in (@@ -596,7 +643,7 @@ async def handle_play(_logger.debug(f"Playing chunk: {chunk}")client.play_media(operation_context=context,- play_source=audio_from_text(chunk, style),+ play_source=audio_from_text(chunk, style, call),)except ResourceNotFoundError:_logger.debug(f"Call hung up before playing ({call.call_id})")@@ -725,7 +772,7 @@ async def llm_chat(return new_styleasync def _error_response() -> Tuple[CallModel, ActionModel]:- content = CONFIG.prompts.tts.error()+ content = await CONFIG.prompts.tts.error(call)style = MessageStyle.NONEawait user_callback(content, style)call.messages.append(@@ -748,7 +795,7 @@ async def llm_chat(# Query expansion from last messagestrainings_tasks = await asyncio.gather(*[- search.training_asearch_all(message.content)+ search.training_asearch_all(message.content, call)for message in call.messages[-CONFIG.ai_search.expansion_k :]],)@@ -772,8 +819,7 @@ async def llm_chat(),ChatCompletionSystemMessageParam(content=CONFIG.prompts.llm.chat_system(- claim=call.claim,- reminders=call.reminders,+ call=call,trainings=trainings,),role="system",@@ -1212,7 +1258,6 @@ async def handle_recognize_text(text=text,)- _logger.debug(f"Recognizing ({call.call_id})")await handle_recognize_media(call=call,client=client,@@ -1229,12 +1274,13 @@ async def handle_recognize_media("""Play a media to a call participant and start recognizing the response."""+ _logger.debug(f"Recognizing media ({call.call_id})")try:client.start_recognizing_media(end_silence_timeout=3, # Sometimes user includes breaks in their speechinput_type=RecognizeInputType.SPEECH,play_prompt=FileSource(url=sound_url),- speech_language=CONFIG.workflow.conversation_lang,+ speech_language=call.lang.short_code,target_participant=PhoneNumberIdentifier(call.phone_number),)except ResourceNotFoundError:@@ -1299,11 +1345,7 @@ async def post_call_sms(call: CallModel) -> None:Send an SMS report to the customer."""content = await llm_completion(- system=CONFIG.prompts.llm.sms_summary_system(- claim=call.claim,- messages=call.messages,- reminders=call.reminders,- ),+ system=CONFIG.prompts.llm.sms_summary_system(call),call=call,)@@ -1345,7 +1387,7 @@ async def post_call_sms(call: CallModel) -> None:)-def audio_from_text(text: str, style: MessageStyle) -> SsmlSource:+def audio_from_text(text: str, style: MessageStyle, call: CallModel) -> SsmlSource:"""Generate an audio source that can be read by Azure Communication Services SDK.@@ -1357,7 +1399,7 @@ def audio_from_text(text: str, style: MessageStyle) -> SsmlSource:f"Text is too long to be processed by TTS, truncating to 400 characters, fix this!")text = text[:400]- ssml = f'<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xmlns:mstts="https://www.w3.org/2001/mstts" xml:lang="{CONFIG.workflow.conversation_lang}"><voice name="{CONFIG.communication_service.voice_name}" effect="eq_telecomhp8k"><lexicon uri="{CONFIG.resources.public_url}/lexicon.xml"/><mstts:express-as style="{style.value}" styledegree="0.5"><prosody rate="0.95">{text}</prosody></mstts:express-as></voice></speak>'+ ssml = f'<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xmlns:mstts="https://www.w3.org/2001/mstts" xml:lang="{call.lang.short_code}"><voice name="{call.lang.voice}" effect="eq_telecomhp8k"><lexicon uri="{CONFIG.resources.public_url}/lexicon.xml"/><mstts:express-as style="{style.value}" styledegree="0.5"><prosody rate="0.95">{text}</prosody></mstts:express-as></voice></speak>'return SsmlSource(ssml_text=ssml)@@ -1383,25 +1425,15 @@ async def post_call_synthesis(call: CallModel) -> None:short, long = await asyncio.gather(llm_completion(call=call,- system=CONFIG.prompts.llm.synthesis_short_system(- claim=call.claim,- messages=call.messages,- reminders=call.reminders,- ),+ system=CONFIG.prompts.llm.synthesis_short_system(call),),llm_completion(call=call,system=CONFIG.prompts.llm.citations_system(- claim=call.claim,- messages=call.messages,- reminders=call.reminders,+ call=call,text=await llm_completion(call=call,- system=CONFIG.prompts.llm.synthesis_long_system(- claim=call.claim,- messages=call.messages,- reminders=call.reminders,- ),+ system=CONFIG.prompts.llm.synthesis_long_system(call),),),),@@ -1428,11 +1460,7 @@ async def post_call_next(call: CallModel) -> None:next = await llm_model(call=call,model=NextModel,- system=CONFIG.prompts.llm.next_system(- claim=call.claim,- messages=call.messages,- reminders=call.reminders,- ),+ system=CONFIG.prompts.llm.next_system(call),)if not next:@@ -1453,3 +1481,55 @@ def _sentence_split(text: str) -> Generator[str, None, None]:for i, separator in enumerate(separators):local_content = splits[i] + separatoryield local_content+++async def handle_recognize_ivr(+ client: CallConnectionClient,+ call: CallModel,+ text: str,+ choices: List[RecognitionChoice],+) -> None:+ _logger.info(f"Playing text before IVR ({call.call_id}): {text}")+ _logger.debug(f"Recognizing IVR ({call.call_id})")+ try:+ client.start_recognizing_media(+ choices=choices,+ input_type=RecognizeInputType.CHOICES,+ play_prompt=audio_from_text(text, MessageStyle.NONE, call),+ speech_language=call.lang.short_code,+ target_participant=PhoneNumberIdentifier(call.phone_number),+ )+ except ResourceNotFoundError:+ _logger.debug(f"Call hung up before recognizing ({call.call_id})")+++async def handle_ivr_language(+ client: CallConnectionClient,+ call: CallModel,+) -> None:+ tones = [+ DtmfTone.ONE,+ DtmfTone.TWO,+ DtmfTone.THREE,+ DtmfTone.FOUR,+ DtmfTone.FIVE,+ DtmfTone.SIX,+ DtmfTone.SEVEN,+ DtmfTone.EIGHT,+ DtmfTone.NINE,+ ]+ choices = []+ for i, lang in enumerate(CONFIG.workflow.lang.availables):+ choices.append(+ RecognitionChoice(+ label=lang.short_code,+ phrases=lang.pronunciations_en,+ tone=tones[i],+ )+ )+ await handle_recognize_ivr(+ call=call,+ client=client,+ choices=choices,+ text=await CONFIG.prompts.tts.ivr_language(call),+ )diff --git a/models/call.py b/models/call.pyindex a512417..8901af7 100644--- a/models/call.py+++ b/models/call.py@@ -1,10 +1,11 @@from datetime import datetime+from helpers.config_models.workflow import LanguageEntryModelfrom models.claim import ClaimModelfrom models.message import MessageModelfrom models.next import NextModelfrom models.reminder import ReminderModelfrom models.synthesis import SynthesisModel-from pydantic import BaseModel, Field+from pydantic import BaseModel, Field, computed_fieldfrom typing import List, Optionalfrom uuid import UUID, uuid4@@ -13,6 +14,8 @@ class CallModel(BaseModel):# Immutable fieldscall_id: UUID = Field(default_factory=uuid4, frozen=True)created_at: datetime = Field(default_factory=datetime.utcnow, frozen=True)+ # Private fields+ lang_short_code: Optional[str] = None# Editable fieldsclaim: ClaimModel = Field(default_factory=ClaimModel)messages: List[MessageModel] = []@@ -21,3 +24,22 @@ class CallModel(BaseModel):recognition_retry: int = Field(default=0)reminders: List[ReminderModel] = []synthesis: Optional[SynthesisModel] = None++ @computed_field+ def lang(self) -> LanguageEntryModel: # type: ignore+ from helpers.config import CONFIG++ if self.lang_short_code:+ return next(+ (+ lang+ for lang in CONFIG.workflow.lang.availables+ if lang.short_code == self.lang_short_code+ ),+ CONFIG.workflow.lang.default_lang,+ )+ return CONFIG.workflow.lang.default_lang++ @lang.setter+ def lang(self, value: LanguageEntryModel) -> None:+ self.lang_short_code = value.short_codediff --git a/persistence/ai_search.py b/persistence/ai_search.pyindex b31089b..38e4bf8 100644--- a/persistence/ai_search.py+++ b/persistence/ai_search.py@@ -6,6 +6,7 @@ from contextlib import asynccontextmanagerfrom helpers.config import CONFIGfrom helpers.config_models.ai_search import AiSearchModelfrom helpers.logging import build_logger+from models.call import CallModelfrom models.training import TrainingModelfrom persistence.isearch import ISearchfrom pydantic import ValidationError@@ -25,7 +26,9 @@ class AiSearchSearch(ISearch):)self._config = config- async def training_asearch_all(self, text: str) -> Optional[List[TrainingModel]]:+ async def training_asearch_all(+ self, text: str, call: CallModel+ ) -> Optional[List[TrainingModel]]:_logger.debug(f'Searching training data for "{text}"')if not text:return None@@ -42,7 +45,7 @@ class AiSearchSearch(ISearch):],search_text=text,# Spell correction- query_language=CONFIG.workflow.conversation_lang,+ query_language=call.lang.short_code,query_speller="lexicon",# Vector searchvector_queries=[diff --git a/persistence/isearch.py b/persistence/isearch.pyindex 4319fb4..55f728c 100644--- a/persistence/isearch.py+++ b/persistence/isearch.py@@ -1,9 +1,12 @@from abc import ABC, abstractmethod+from models.call import CallModelfrom models.training import TrainingModelfrom typing import List, Optionalclass ISearch(ABC):@abstractmethod- async def training_asearch_all(self, text: str) -> Optional[List[TrainingModel]]:+ async def training_asearch_all(+ self, text: str, call: CallModel+ ) -> Optional[List[TrainingModel]]:passdiff --git a/requirements.txt b/requirements.txtindex 396dcfa..c7ce4b3 100644--- a/requirements.txt+++ b/requirements.txt@@ -1,6 +1,7 @@aiohttp==3.9.3 # Required for azure-search-documents, azure-ai-contentsafety, azure-cosmosaiosqlite==0.19.0azure-ai-contentsafety==1.0.0+azure-ai-translation-text==1.0.0b1azure-communication-callautomation==1.1.0azure-communication-sms==1.0.1azure-cosmos==4.5.1