Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
feat: Make system use English by default for all text stored and UI
Clémence Lesné3deb0f82a09b
diff --git a/helpers/config_models/prompts.py b/helpers/config_models/prompts.pyindex 296e4b1..09cda24 100644--- a/helpers/config_models/prompts.py+++ b/helpers/config_models/prompts.py@@ -172,10 +172,10 @@ class LlmModel(BaseModel):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 {default_lang}, even if the customer speaks another language+ - Answers in English, even if the customer speaks another language+ - Consider all the conversation history, from the beginning- 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- Won't make any assumptions# Answer examples@@ -199,14 +199,14 @@ class LlmModel(BaseModel):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 {default_lang}, even if the customer speaks another language+ - Answers in English, even if the customer speaks another language+ - Consider all the conversation history, from the beginning- 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- - Consider all the conversation history, from the beginning- Use Markdown syntax to format the message with paragraphs, bold text, and URL- Won't make any assumptions@@ -228,6 +228,7 @@ class LlmModel(BaseModel):- Only use exact words from the text as citations- Treats a citation as a word or a group of words- Use claim, reminders, and messages extracts as citations+ - Use the same language as the text- Won't make any assumptions- Write citations as Markdown abbreviations at the end of the text (e.g., "*[words from the text]: extract from the conversation")@@ -265,6 +266,7 @@ class LlmModel(BaseModel):Assistant will choose the next action from the company sales team perspective. The Answer is a JSON object with the action to take and the justification for this action.# Rules+ - Answers in English, even if the customer speaks another language- Take as priority the customer satisfaction- Won't make any assumptions- Write no more than a few sentences as justification@@ -375,7 +377,6 @@ class LlmModel(BaseModel):return self._return(self.synthesis_short_system_tpl,claim=call.claim.model_dump_json(),- default_lang=call.lang.human_name,messages=TypeAdapter(list[MessageModel]).dump_json(call.messages).decode(),reminders=TypeAdapter(list[ReminderModel]).dump_json(call.reminders)@@ -386,7 +387,6 @@ class LlmModel(BaseModel):return self._return(self.synthesis_long_system_tpl,claim=call.claim.model_dump_json(),- default_lang=call.lang.human_name,messages=TypeAdapter(list[MessageModel]).dump_json(call.messages).decode(),reminders=TypeAdapter(list[ReminderModel]).dump_json(call.reminders)diff --git a/helpers/llm_tools.py b/helpers/llm_tools.pyindex cd556b2..211ee8e 100644--- a/helpers/llm_tools.py+++ b/helpers/llm_tools.py@@ -89,11 +89,11 @@ class LlmPlugins:self,customer_response: Annotated[str,- "Phrase used to confirm the update. This phrase will be spoken to the user. Describe what you're doing in one sentence. Example: 'I am creating a reminder for next week to call you back.', 'A todo for next week is planned.'.",+ "Phrase used to confirm the update, in the same language as the customer. This phrase will be spoken to the user. Describe what you're doing in one sentence. Example: 'I am creating a reminder for next week to call you back.', 'A todo for next week is planned.'.",],description: Annotated[str,- "Description of the reminder. Should be detailed enough to be understood by anyone. Example: 'Call back customer to get more details about the accident', 'Send analysis report to the customer'.",+ "Description of the reminder, in English. Should be detailed enough to be understood by anyone. Example: 'Call back customer to get more details about the accident', 'Send analysis report to the customer'.",],due_date_time: Annotated[str,@@ -101,11 +101,11 @@ class LlmPlugins:],owner: Annotated[str,- "The owner of the reminder. Can be 'customer', 'assistant', or a third party from the claim. Try to be as specific as possible, with a name. Example: 'customer', 'assistant', 'contact', 'witness', 'police'.",+ "The owner of the reminder, in English. Can be 'customer', 'assistant', or a third party from the claim. Try to be as specific as possible, with a name. Example: 'customer', 'assistant', 'contact', 'witness', 'police'.",],title: Annotated[str,- "Short title of the reminder. Should be short and concise, in the format 'Verb + Subject'. Title is unique and allows the reminder to be updated. Example: 'Call back customer', 'Send analysis report', 'Study replacement estimates for the stolen watch'.",+ "Short title of the reminder, in English. Should be short and concise, in the format 'Verb + Subject'. Title is unique and allows the reminder to be updated. Example: 'Call back customer', 'Send analysis report', 'Study replacement estimates for the stolen watch'.",],) -> str:"""@@ -150,12 +150,12 @@ class LlmPlugins:self,customer_response: Annotated[str,- "Phrase used to confirm the update. This phrase will be spoken to the user. Describe what you're doing in one sentence. Example: 'I am updating the your name to Marie-Jeanne Duchemin and your email to [email protected].'.",+ "Phrase used to confirm the update, in the same language as the customer. This phrase will be spoken to the user. Describe what you're doing in one sentence. Example: 'I am updating the your name to Marie-Jeanne Duchemin and your email to [email protected].'.",],updates: Annotated[list[UpdateClaimDict],"""- The field to update.+ The field to update, in English.# Available fields{{ call.claim.editable_fields() | join(', ') }}@@ -235,11 +235,11 @@ class LlmPlugins:self,customer_response: Annotated[str,- "Phrase used to confirm the search. This phrase will be spoken to the user. Describe what you're doing in one sentence. Example: 'I am searching for the document about the car accident.', 'I am looking for the contract details.'.",+ "Phrase used to confirm the search, in the same language as the customer. This phrase will be spoken to the user. Describe what you're doing in one sentence. Example: 'I am searching for the document about the car accident.', 'I am looking for the contract details.'.",],queries: Annotated[list[str],- "The text queries to perform the search. Example: ['How much does it cost to repair a broken window?', 'What are the requirements to ask for a cyber attack insurance?']",+ "The text queries to perform the search, in English. Example: ['How much does it cost to repair a broken window?', 'What are the requirements to ask for a cyber attack insurance?']",],) -> str:"""@@ -255,7 +255,10 @@ class LlmPlugins:await self.user_callback(customer_response, self.style)# Execute in paralleltasks = await asyncio.gather(- *[_search.training_asearch_all(query, self.call) for query in queries]+ *[+ _search.training_asearch_all(text=query, lang="en-US")+ for query in queries+ ])# Flatten, remove duplicates, and sort by scoretrainings = sorted(set(training for task in tasks for training in task or []))diff --git a/models/call.py b/models/call.pyindex ecfe520..a4e97ad 100644--- a/models/call.py+++ b/models/call.py@@ -48,6 +48,7 @@ class CallStateModel(CallGetModel):)@computed_field+ @propertydef lang(self) -> LanguageEntryModel: # type: ignorefrom helpers.config import CONFIG@@ -79,7 +80,9 @@ class CallStateModel(CallGetModel):search = CONFIG.ai_search.instance()trainings_tasks = await asyncio.gather(*[- search.training_asearch_all(message.content, self)+ search.training_asearch_all(+ text=message.content, lang=self.lang.short_code+ )for message in self.messages[-CONFIG.ai_search.expansion_k :]],) # Get trainings from last messagesdiff --git a/persistence/ai_search.py b/persistence/ai_search.pyindex 1b5a9ae..086feae 100644--- a/persistence/ai_search.py+++ b/persistence/ai_search.py@@ -60,7 +60,9 @@ class AiSearchSearch(ISearch):wait=wait_random_exponential(multiplier=0.5, max=30),)async def training_asearch_all(- self, text: str, call: CallStateModel+ self,+ text: str,+ lang: str,) -> Optional[list[TrainingModel]]:_logger.debug(f'Searching training data for "{text}"')if not text:@@ -90,7 +92,7 @@ class AiSearchSearch(ISearch):],search_text=text,# Spell correction- query_language=call.lang.short_code,+ query_language=lang,query_speller="lexicon",# Vector searchvector_queries=[diff --git a/persistence/isearch.py b/persistence/isearch.pyindex 777432c..3d22e6b 100644--- a/persistence/isearch.py+++ b/persistence/isearch.py@@ -18,6 +18,8 @@ class ISearch(ABC):@abstractmethodasync def training_asearch_all(- self, text: str, call: CallStateModel+ self,+ text: str,+ lang: str,) -> Optional[list[TrainingModel]]:passdiff --git a/public_website/list.html.jinja b/public_website/list.html.jinjaindex f0ff284..1c09de1 100644--- a/public_website/list.html.jinja+++ b/public_website/list.html.jinja@@ -1,7 +1,7 @@{% extends "templates/base.html.jinja" %}{% block title %}-Historique pour {{ phone_number or 'tous les numéros' }}+History for {{ phone_number or 'all numbers' }}{% endblock %}{% block content %}@@ -11,26 +11,26 @@ Historique pour {{ phone_number or 'tous les numéros' }}<form action="/report" method="GET" class="flex space-x-4"><div class="grow flex space-x-4 rounded-full backdrop-blur shadow-md bg-neutral-200/60 hover:bg-neutral-300/60 dark:bg-neutral-700/60 dark:hover:bg-neutral-600/60"><span class="pl-6 py-4 select-none cursor-default">🔎</span>- <input type="tel" name="phone_number" placeholder="Limiter la recherche à un numéro (E164, ex. +33612345678)" value="{{ phone_number or '' }}" class="py-4 grow bg-transparent outline-none">+ <input type="tel" name="phone_number" placeholder="Limit search to one number (E164, e.g. +33612345678)" value="{{ phone_number or '' }}" class="py-4 grow bg-transparent outline-none"></div>- <button type="submit" class="px-6 py-4 rounded-full backdrop-blur shadow-md font-semibold bg-gradient-to-r from-pink-300/30 hover:from-pink-400/30 dark:from-pink-700/30 dark:hover:from-pink-600/30 to-violet-300/30 hover:to-violet-400/30 dark:to-violet-700/30 dark:hover:to-violet-600/30">Rechercher</button>+ <button type="submit" class="px-6 py-4 rounded-full backdrop-blur shadow-md font-semibold bg-gradient-to-r from-pink-300/30 hover:from-pink-400/30 dark:from-pink-700/30 dark:hover:from-pink-600/30 to-violet-300/30 hover:to-violet-400/30 dark:to-violet-700/30 dark:hover:to-violet-600/30">Search</button></form></div></div><!-- History of calls --><div class="col-span-full rounded-md overflow-hidden lg:ring-1 ring-neutral-200/60 dark:ring-neutral-700/60"><div class="grid grid-cols-4 border-b border-neutral-200/60 dark:border-neutral-700/60 text-neutral-600 dark:text-neutral-400">- <div class="p-4 truncate">📞 Téléphone utilisé</div>- <div class="p-4 truncate">📅 Date locale</div>- <div class="p-4 truncate col-span-2">📝 Synthèse courte</div>+ <div class="p-4 truncate">📞 Phone used</div>+ <div class="p-4 truncate">📅 Local date</div>+ <div class="p-4 truncate col-span-2">📝 Short summary</div></div>{% for call in calls %}- <a href="/report/{{ call.call_id }}" title="Appel de {{ call.phone_number }} le {{ call.created_at.astimezone(call.tz()).strftime('%d %b %Y, %H:%M') }}" class="grid grid-cols-4 hover:bg-neutral-100/60 dark:hover:bg-neutral-800/60 {% if not loop.last %}border-b border-neutral-200/60 dark:border-neutral-700/60{% endif %}">+ <a href="/report/{{ call.call_id }}" title="Call from {{ call.phone_number }} the {{ call.created_at.astimezone(call.tz()).strftime('%d %b %Y, %H:%M') }}" class="grid grid-cols-4 hover:bg-neutral-100/60 dark:hover:bg-neutral-800/60 {% if not loop.last %}border-b border-neutral-200/60 dark:border-neutral-700/60{% endif %}"><div class="p-4 truncate">{{ call.phone_number }}</div><div class="p-4 truncate">{{ call.created_at.astimezone(call.tz()).strftime('%d %b %Y, %H:%M') }}</div><div class="col-span-2 p-4 truncate">{{ call.synthesis.short | lower }}</div></a>{% endfor %}</div>-<div class="col-span-full px-4 text-neutral-600 dark:text-neutral-400">Les {{ count }} premiers résultats sont affichés.</div>+<div class="col-span-full px-4 text-neutral-600 dark:text-neutral-400">The {{ count }} first results are displayed.</div>{% endblock %}diff --git a/public_website/single.html.jinja b/public_website/single.html.jinjaindex bb753e2..558e22f 100644--- a/public_website/single.html.jinja+++ b/public_website/single.html.jinja@@ -13,16 +13,16 @@ Sinistre {{ call.claim.claim_id }} ({{ call.phone_number }})</a></div>- <h1>Bonjour {{ (call.claim.policyholder_name | title) if call.claim.policyholder_name else '' }} 👋🏻</h1>- <p class="text-2xl">Votre sinistre <span class="font-mono">#{{ call.claim.claim_id }}</span> à propos de {{ call.synthesis.short | lower }} est en cours de traitement.</p>+ <h1>Hello {{ (call.claim.policyholder_name | title) if call.claim.policyholder_name else '' }} 👋🏻</h1>+ <p class="text-2xl">Your claim <span class="font-mono">#{{ call.claim.claim_id }}</span> about {{ call.synthesis.short | lower }} is currently being processed.</p></header><!-- Long synthesis --><div class="col-span-full mb-8"><div class="lg:rounded-md bg-gradient-to-r from-pink-300/30 dark:from-pink-700/30 to-violet-300/30 dark:to-violet-700/30 lg:ring-1 ring-transparent -mx-4 -my-2 px-8 py-6 space-y-4">- <h2 class="text-lg">Synthèse</h2>+ <h2 class="text-lg">Summary</h2>{% if not call.synthesis.long %}- <p class="text-neutral-600 dark:text-neutral-400">Aucune synthèse pour l'instant.</p>+ <p class="text-neutral-600 dark:text-neutral-400">No summary yet.</p>{% else %}<div class="space-y-2">{{ call.synthesis.long | markdown | safe }}@@ -40,7 +40,7 @@ Sinistre {{ call.claim.claim_id }} ({{ call.phone_number }})<div class="overflow-hidden space-y-6">{% for message in call.messages | sort(attribute='created_at') %}{% if not (message.action == 'talk' and not message.content) %}- {% set name = bot_name if message.persona == 'assistant' else (call.claim.policyholder_name or 'Client') %}+ {% set name = bot_name if message.persona == 'assistant' else (call.claim.policyholder_name or 'Customer') %}<div class="flex flex-row"><div class="basis-6 relative self-stretch"><div class="absolute top-0 left-0 w-full h-full -z-10">@@ -64,13 +64,13 @@ Sinistre {{ call.claim.claim_id }} ({{ call.phone_number }}){{ name | title }}<span class="text-neutral-600 dark:text-neutral-400">{% if message.action == 'call' %}- a appelé+ called{% elif message.action == 'hangup' %}- a raccroché+ hung up{% elif message.action == 'sms' %}- a envoyé un SMS+ sent a text{% elif message.action == 'talk' %}- a dit+ said{% endif %}</span></div>@@ -85,7 +85,7 @@ Sinistre {{ call.claim.claim_id }} ({{ call.phone_number }})</div>{% endif %}{% else %}- <p class="text-neutral-600 dark:text-neutral-400">Aucun message pour l'instant.</p>+ <p class="text-neutral-600 dark:text-neutral-400">No message yet.</p>{% endfor %}</div>@@ -96,10 +96,10 @@ Sinistre {{ call.claim.claim_id }} ({{ call.phone_number }})<div class="col-start-5 col-end-7 space-y-4"><!-- Reminders --><div class="rounded-md lg:ring-1 ring-neutral-200/60 dark:ring-neutral-700/60 p-4 space-y-4">- <h2 class="text-lg">⏰ Rappels</h2>+ <h2 class="text-lg">⏰ Reminders</h2>{% if not call.reminders %}- <p class="text-neutral-600 dark:text-neutral-400">Aucun rappel pour l'instant.</p>+ <p class="text-neutral-600 dark:text-neutral-400">No reminder yet.</p>{% else %}<div class="space-y-6">{% for reminder in call.reminders | sort(attribute='due_date_time') %}@@ -116,10 +116,10 @@ Sinistre {{ call.claim.claim_id }} ({{ call.phone_number }})<!-- Next actions --><div class="rounded-md lg:ring-1 ring-neutral-200/60 dark:ring-neutral-700/60 p-4 space-y-4">- <h2 class="text-lg">📥 Prochaine action</h2>+ <h2 class="text-lg">📥 Next action</h2>{% if not call.next %}- <p class="text-neutral-600 dark:text-neutral-400">Aucune prochaine action pour l'instant.</p>+ <p class="text-neutral-600 dark:text-neutral-400">No further action for the moment.</p>{% else %}<ul>{% for action in next_actions | sort %}@@ -142,7 +142,7 @@ Sinistre {{ call.claim.claim_id }} ({{ call.phone_number }})<!-- Details --><div class="rounded-md lg:ring-1 ring-neutral-200/60 dark:ring-neutral-700/60">- <h2 class="text-lg px-4 pt-4">📁 Détails</h2>+ <h2 class="text-lg px-4 pt-4">📁 Details</h2><table class="table-auto w-full"><tbody>{%@@ -152,11 +152,11 @@ Sinistre {{ call.claim.claim_id }} ({{ call.phone_number }})'value': call.claim.incident_date_time.strftime('%d %b %Y, %H:%M') if call.claim.incident_date_time else 'N/A'},{- 'title': 'Localisation',+ 'title': 'Location','value': call.claim.incident_location or 'N/A'},{- 'title': 'Police',+ 'title': 'Policy','value': call.claim.policy_number or 'N/A'},{@@ -164,7 +164,7 @@ Sinistre {{ call.claim.claim_id }} ({{ call.phone_number }})'value': (call.claim.policyholder_email or 'N/A') ~ ', ' ~ (call.claim.policyholder_phone or 'N/A')},{- 'title': 'Téléphone utilisé',+ 'title': 'Phone used','value': call.phone_number or 'N/A'}]diff --git a/tests/search.py b/tests/search.pyindex cd1f929..617a21d 100644--- a/tests/search.py+++ b/tests/search.py@@ -130,7 +130,6 @@ class RagRelevancyMetric(BaseMetric):@pytest.mark.asyncio # Allow async functions@pytest.mark.repeat(10) # Catch multi-threading and concurrency issuesasync def test_relevancy(- call: CallStateModel,deepeval_model: GPTModel,user_lang: str,user_message: str,@@ -146,10 +145,9 @@ async def test_relevancy(Test is repeated 10 times to catch multi-threading and concurrency issues."""search = CONFIG.ai_search.instance()- call.lang = user_lang# Init data- res_models = await search.training_asearch_all(user_message, call)+ res_models = await search.training_asearch_all(text=user_message, lang=user_lang)res_list = [d.content for d in res_models or []]_logger.info(f"Message: {user_message}")