Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
feat: Add a conversation synthesis to be displayed on the web
Clémence Lesné8f631cb3b788
diff --git a/helpers/prompts.py b/helpers/prompts.pyindex a80a63d..713161a 100644--- a/helpers/prompts.py+++ b/helpers/prompts.py@@ -1,5 +1,6 @@from enum import Enumfrom helpers.config import CONFIG+from models.message import Action as MessageActionclass Sounds(str, Enum):@@ -20,6 +21,7 @@ class LLM(str, Enum):- 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@@ -73,6 +75,53 @@ class LLM(str, Enum):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):diff --git a/main.py b/main.pyindex 41fce7f..6e68d2a 100644--- a/main.py+++ b/main.py@@ -9,6 +9,7 @@ from azure.communication.callautomation import ()from azure.communication.sms import SmsClientfrom azure.core.credentials import AzureKeyCredential+from azure.core.exceptions import ClientAuthenticationErrorfrom azure.core.exceptions import ResourceNotFoundErrorfrom azure.core.messaging import CloudEventfrom azure.eventgrid import EventGridEvent, SystemEventNames@@ -16,23 +17,26 @@ from azure.identity import DefaultAzureCredential, get_bearer_token_providerfrom 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 CONFIG+from helpers.config_models.database import Mode as DatabaseModefrom helpers.logging import build_loggerfrom helpers.prompts import LLM as LLMPrompt, TTS as TTSPrompt, Sounds as SoundPromptfrom jinja2 import Environment, FileSystemLoader, select_autoescapefrom models.action import ActionModel, Indent as IndentAction+from models.call import CallModelfrom models.reminder import ReminderModel-from helpers.config_models.database import Mode as DatabaseMode-from persistence.sqlite import SqliteStore+from models.synthesis import SynthesisModelfrom persistence.cosmos import CosmosStore-from pydantic.json import pydantic_encoder+from persistence.sqlite import SqliteStore+import reimport asyncio-from models.call import (- CallModel,- MessageModel as CallMessageModel,- Persona as CallPersona,- ToolModel as CallToolModel,+from models.message import (+ Action as MessageAction,+ MessageModel,+ Persona as MessagePersona,+ ToolModel as MessageToolModel,)from models.claim import ClaimModelfrom openai import AsyncAzureOpenAI@@ -234,6 +238,14 @@ async def communication_evnt_worker(event_dict: dict, call_id: UUID) -> None:_logger.info(f"Call connected ({call.call_id})")call.recognition_retry = 0 # Reset recognition retry counter+ call.messages.append(+ MessageModel(+ action=MessageAction.CALL,+ content="",+ persona=MessagePersona.HUMAN,+ )+ )+if not call.messages: # First callawait handle_recognize_text(call=call,@@ -242,11 +254,6 @@ async def communication_evnt_worker(event_dict: dict, call_id: UUID) -> None:)else: # Returning call- call.messages.append(- CallMessageModel(- content="Customer called again.", persona=CallPersona.HUMAN- )- )await handle_play(call=call,client=client,@@ -267,7 +274,7 @@ async def communication_evnt_worker(event_dict: dict, call_id: UUID) -> None:if speech_text is not None and len(speech_text) > 0:call.messages.append(- CallMessageModel(content=speech_text, persona=CallPersona.HUMAN)+ MessageModel(content=speech_text, persona=MessagePersona.HUMAN))await intelligence(call, client)@@ -481,7 +488,7 @@ async def handle_play("""if store:call.messages.append(- CallMessageModel(content=text, persona=CallPersona.ASSISTANT)+ MessageModel(content=text, persona=MessagePersona.ASSISTANT))# Split text in chunks of max 400 characters, separated by a comma@@ -520,9 +527,9 @@ async def gpt_completion(system: LLMPrompt, call: CallModel) -> str:},{"content": system.format(- claim=call.claim.model_dump_json(),- conversation=json.dumps(call.messages, default=pydantic_encoder),- reminders=json.dumps(call.reminders, default=pydantic_encoder),+ claim=json.dumps(jsonable_encoder(call.claim)),+ conversation=json.dumps(jsonable_encoder(call.messages)),+ reminders=json.dumps(jsonable_encoder(call.reminders)),),"role": "system",},@@ -558,32 +565,32 @@ async def gpt_chat(call: CallModel) -> ActionModel:},{"content": LLMPrompt.CHAT_SYSTEM.format(- claim=call.claim.model_dump_json(),- reminders=json.dumps(call.reminders, default=pydantic_encoder),+ claim=json.dumps(jsonable_encoder(call.claim)),+ reminders=json.dumps(jsonable_encoder(call.reminders)),),"role": "system",},]for message in call.messages:- if message.persona == CallPersona.HUMAN:+ if message.persona == MessagePersona.HUMAN:messages.append({- "content": message.content,+ "content": f"{message.action.value}: {message.content}","role": "user",})- elif message.persona == CallPersona.ASSISTANT:+ elif message.persona == MessagePersona.ASSISTANT:if not message.tool_calls:messages.append({- "content": message.content,+ "content": f"{message.action.value}: {message.content}","role": "assistant",})else:messages.append({- "content": message.content,+ "content": f"{message.action.value}: {message.content}","role": "assistant","tool_calls": [{@@ -601,7 +608,7 @@ async def gpt_chat(call: CallModel) -> ActionModel:for tool_call in message.tool_calls:messages.append({- "content": message.content,+ "content": tool_call.content,"role": "tool","tool_call_id": tool_call.tool_id,}@@ -614,7 +621,7 @@ async def gpt_chat(call: CallModel) -> ActionModel:"type": "function","function": {"description": "Use this if the user wants to talk to a human and Assistant is unable to help. This will transfer the customer to an human agent. Approval from the customer must be explicitely given. Example: 'I want to talk to a human', 'I want to talk to a real person'.",- "name": IndentAction.TALK_TO_HUMAN,+ "name": IndentAction.TALK_TO_HUMAN.value,"parameters": {"properties": {},"required": [],@@ -626,7 +633,7 @@ async def gpt_chat(call: CallModel) -> ActionModel:"type": "function","function": {"description": "Use this if the user wants to end the call, or if the user is satisfied with the answer and confirmed the end of the call.",- "name": IndentAction.END_CALL,+ "name": IndentAction.END_CALL.value,"parameters": {"properties": {},"required": [],@@ -638,7 +645,7 @@ async def gpt_chat(call: 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. Example: 'I want to create a new claim'.",- "name": IndentAction.NEW_CLAIM,+ "name": IndentAction.NEW_CLAIM.value,"parameters": {"properties": {f"{customer_response_prop}": {@@ -657,7 +664,7 @@ async def gpt_chat(call: CallModel) -> ActionModel:"type": "function","function": {"description": "Use this if the user wants to update a claim field with a new value. Example: 'Update claim explanation to: I was driving on the highway when a car hit me from behind', 'Update policyholder contact info to: 123 rue de la paix 75000 Paris, +33735119775, only call after 6pm'.",- "name": IndentAction.UPDATED_CLAIM,+ "name": IndentAction.UPDATED_CLAIM.value,"parameters": {"properties": {"field": {@@ -687,7 +694,7 @@ async def gpt_chat(call: CallModel) -> ActionModel:"type": "function","function": {"description": "Use this if you think there is something important to do in the future, and you want to be reminded about it. If it already exists, it will be updated with the new values. Example: 'Remind Assitant thuesday at 10am to call back the customer', 'Remind Assitant next week to send the report', 'Remind the customer next week to send the documents by the end of the month'.",- "name": IndentAction.NEW_OR_UPDATED_REMINDER,+ "name": IndentAction.NEW_OR_UPDATED_REMINDER.value,"parameters": {"properties": {"description": {@@ -736,6 +743,9 @@ async def gpt_chat(call: CallModel) -> ActionModel:)content = res.choices[0].message.content or ""+ content = re.sub(+ rf"^(?:{'|'.join([action.value for action in MessageAction])}):", "", content+ ).strip() # Remove action from content, AI often adds it by mistake event if explicitly asked not totool_calls = res.choices[0].message.tool_calls_logger.debug(f"Chat response: {content}")@@ -750,20 +760,20 @@ async def gpt_chat(call: CallModel) -> ActionModel:arguments = tool_call.function.arguments_logger.info(f"Tool call {name} with parameters {arguments}")- model = CallToolModel(+ model = MessageToolModel(content="",function_arguments=arguments,function_name=name,tool_id=tool_call.id,)- if name == IndentAction.TALK_TO_HUMAN:+ if name == IndentAction.TALK_TO_HUMAN.value:intent = IndentAction.TALK_TO_HUMAN- elif name == IndentAction.END_CALL:+ elif name == IndentAction.END_CALL.value:intent = IndentAction.END_CALL- elif name == IndentAction.UPDATED_CLAIM:+ elif name == IndentAction.UPDATED_CLAIM.value:intent = IndentAction.UPDATED_CLAIMparameters = json.loads(arguments)@@ -774,10 +784,15 @@ async def gpt_chat(call: CallModel) -> ActionModel:else:content += parameters[customer_response_prop] + " "- setattr(call.claim, parameters["field"], parameters["value"])- model.content = f"Updated claim field \"{parameters['field']}\" with value \"{parameters['value']}\"."+ if not parameters["field"] in ClaimModel.editable_fields():+ _logger.debug(+ f"AI model tried to update a non-editable field {parameters['field']}"+ )+ else:+ setattr(call.claim, parameters["field"], parameters["value"])+ model.content = f"Updated claim field \"{parameters['field']}\" with value \"{parameters['value']}\"."- elif name == IndentAction.NEW_CLAIM:+ elif name == IndentAction.NEW_CLAIM.value:intent = IndentAction.NEW_CLAIMparameters = json.loads(arguments)@@ -792,7 +807,7 @@ async def gpt_chat(call: CallModel) -> ActionModel:call.reminders = []model.content = "Claim and reminders created reset."- elif name == IndentAction.NEW_OR_UPDATED_REMINDER:+ elif name == IndentAction.NEW_OR_UPDATED_REMINDER.value:intent = IndentAction.NEW_OR_UPDATED_REMINDERparameters = json.loads(arguments)@@ -829,9 +844,9 @@ async def gpt_chat(call: CallModel) -> ActionModel:models.append(model)call.messages.append(- CallMessageModel(+ MessageModel(content=content,- persona=CallPersona.ASSISTANT,+ persona=MessagePersona.ASSISTANT,tool_calls=models,))@@ -918,9 +933,24 @@ async def handle_hangup(client: CallConnectionClient, call: CallModel) -> None:_logger.debug(f"Call already hung up ({call.call_id})")call.messages.append(- CallMessageModel(content="Customer ended the call.", persona=CallPersona.HUMAN)+ MessageModel(+ content="",+ persona=MessagePersona.HUMAN,+ action=MessageAction.HANGUP,+ )+ )++ # Start post-call intelligence+ await asyncio.gather(+ post_call_sms(call),+ post_call_synthesis(call),)++async def post_call_sms(call: CallModel) -> None:+ """+ Send an SMS report to the customer.+ """content = await gpt_completion(LLMPrompt.SMS_SUMMARY_SYSTEM, call)_logger.info(f"SMS report ({call.call_id}): {content}")@@ -933,26 +963,23 @@ async def handle_hangup(client: CallConnectionClient, call: CallModel) -> None:response = responses[0]if response.successful:- _logger.info(+ _logger.debug(f"SMS report sent {response.message_id} to {response.to} ({call.call_id})")call.messages.append(- CallMessageModel(- content=f"SMS report sent to {response.to}: {content}",- persona=CallPersona.ASSISTANT,+ MessageModel(+ action=MessageAction.SMS,+ content=content,+ persona=MessagePersona.ASSISTANT,))else:_logger.warn(f"Failed SMS to {response.to}, status {response.http_status_code}, error {response.error_message} ({call.call_id})")- call.messages.append(- CallMessageModel(- content=f"Failed to send SMS report to {response.to}: {response.error_message}",- persona=CallPersona.ASSISTANT,- )- )+ except ClientAuthenticationError:+ _logger.error("Authentication error for SMS, check the credentials")except Exception:_logger.warn(f"Failed SMS to {call.phone_number} ({call.call_id})", exc_info=True@@ -986,3 +1013,22 @@ async def callback_url(caller_id: str) -> str:call = CallModel(phone_number=caller_id)await db.call_aset(call)return f"{CALL_EVENT_URL}/{call.call_id}"+++async def post_call_synthesis(call: CallModel) -> None:+ """+ Synthesize the call and store it to the model.+ """+ _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),+ )+ _logger.info(f"Short synthesis ({call.call_id}): {short}")+ _logger.info(f"Long synthesis ({call.call_id}): {long}")++ call.synthesis = SynthesisModel(+ long=long,+ short=short,+ )diff --git a/models/call.py b/models/call.pyindex a4b0faa..04bf45e 100644--- a/models/call.py+++ b/models/call.py@@ -1,32 +1,13 @@from datetime import datetime-from enum import Enumfrom models.claim import ClaimModel+from models.message import MessageModelfrom models.reminder import ReminderModel+from models.synthesis import SynthesisModelfrom pydantic import BaseModel, Field-from typing import List+from typing import List, Optionalfrom uuid import UUID, uuid4-class Persona(str, Enum):- ASSISTANT = "assistant"- HUMAN = "human"- TOOL = "tool"---class ToolModel(BaseModel):- content: str- function_arguments: str- function_name: str- tool_id: str---class MessageModel(BaseModel):- content: str- created_at: datetime = Field(default_factory=datetime.utcnow, frozen=True)- persona: Persona- tool_calls: List[ToolModel] = []--class CallModel(BaseModel):call_id: UUID = Field(default_factory=uuid4, frozen=True)claim: ClaimModel = Field(default_factory=ClaimModel)@@ -35,3 +16,4 @@ class CallModel(BaseModel):phone_number: strrecognition_retry: int = Field(default=0)reminders: List[ReminderModel] = []+ synthesis: Optional[SynthesisModel] = Nonediff --git a/models/message.py b/models/message.pynew file mode 100644index 0000000..234379f--- /dev/null+++ b/models/message.py@@ -0,0 +1,32 @@+from datetime import datetime+from enum import Enum+from pydantic import BaseModel, Field+from typing import List+++class Action(str, Enum):+ CALL = "call"+ HANGUP = "hangup"+ SMS = "sms"+ TALK = "talk"+++class Persona(str, Enum):+ ASSISTANT = "assistant"+ HUMAN = "human"+ TOOL = "tool"+++class ToolModel(BaseModel):+ content: str+ function_arguments: str+ function_name: str+ tool_id: str+++class MessageModel(BaseModel):+ action: Action = Action.TALK+ content: str+ created_at: datetime = Field(default_factory=datetime.utcnow, frozen=True)+ persona: Persona+ tool_calls: List[ToolModel] = []diff --git a/models/synthesis.py b/models/synthesis.pynew file mode 100644index 0000000..6d61632--- /dev/null+++ b/models/synthesis.py@@ -0,0 +1,6 @@+from pydantic import BaseModel+++class SynthesisModel(BaseModel):+ long: str+ short: strdiff --git a/public_website/report.html b/public_website/report.htmlindex 086c436..cb6e8ba 100644--- a/public_website/report.html+++ b/public_website/report.html@@ -4,64 +4,27 @@<meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><script src="https://cdn.tailwindcss.com"></script>- <title>Claim report {{ call.claim.claim_id }}</title>+ <title>Déclaration de sinistre {{ call.claim.claim_id }}</title></head>- <body class="container mx-auto px-4 bg-white text-sm">- <div class="grid grid-cols-6 gap-4 m-4">+ <body class="container mx-auto lg:p-8 bg-white text-sm">+ <div class="flex flex-col lg:grid lg:grid-cols-6 gap-4"><!-- Top introduction -->- <div class="col-span-full px-4 py-8">- <h1>Hello {{ call.claim.policyholder_name | title }} 👋🏻</h1>- <p class="text-2xl">Your claim <span class="font-mono">#{{ call.claim.claim_id }}</span> of the {{ call.claim.created_at.strftime('%d %b %Y') }} is being processed.</p>+ <div class="col-span-full my-8 px-4">+ <h1>Bonjour {{ call.claim.policyholder_name | title }} 👋🏻</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></div>- <!-- Claim details -->- <div class="col-span-full">- <div class="rounded-md ring-1 ring-gray-200">- <h2 class="text-lg px-4 pt-4">🔎 Claim details</h2>-- <table class="table-auto w-full">- <tbody>- <tr class="border-b border-slate-100">- <td class="p-4 text-gray-500">We understood</td>- <td class="p-4">- {{ call.claim.incident_description }}- {{ call.claim.extra_details }}- </td>- </tr>- <tr class="border-b border-slate-100">- <td class="p-4 text-gray-500">Medical situation</td>- <td class="p-4">- {{ call.claim.injuries_description }}- {{ call.claim.medical_records }}- </td>- </tr>- <tr class="border-b border-slate-100">- <td class="p-4 text-gray-500">Incident date</td>- <!-- TODO: Try to parse the date and display it in a human readable format -->- <td class="p-4">- {{ call.claim.incident_location }}, {{ call.claim.incident_date_time }}- </td>- </tr>- <tr class="border-b border-slate-100">- <td class="p-4 text-gray-500">Policy number</td>- <td class="p-4">- {{ call.claim.policy_number }}- </td>- </tr>- <tr class="border-b border-slate-100">- <td class="p-4 text-gray-500">Contact info</td>- <td class="p-4">- {{ call.claim.policyholder_email | lower }}, {{ call.claim.policyholder_phone }}- </td>- </tr>- </tbody>- </table>+ <!-- Long synthesis -->+ <div class="col-span-full mb-8">+ <div class="rounded-md lg:shadow-xl lg:ring-1 ring-gray-200/60 p-4 space-y-4">+ <h2 class="text-lg">✏️ Synthèse</h2>+ <p>{{ call.synthesis.long }}</p></div></div><!-- Conversation --><div class="col-start-1 col-end-5">- <div class="p-4 space-y-4 rounded-md ring-1 ring-gray-200">+ <div class="p-4 space-y-4 rounded-md lg:ring-1 ring-gray-200/60"><h2 class="text-lg">💬 Conversation</h2><!-- Agent and customer -->@@ -88,13 +51,26 @@<div class="basis-full space-y-2 px-4 py-0.5"><div class="flex flex-row justify-between content-center text-xs"><div>- {{ name | title }} <span class="text-gray-500">commented</span>+ {{ name | title }}+ <span class="text-gray-500">+ {% if message.action == 'call' %}+ a appelé+ {% elif message.action == 'hangup' %}+ a raccroché+ {% elif message.action == 'sms' %}+ a envoyé un SMS+ {% elif message.action == 'talk' %}+ a dit+ {% endif %}+ </span></div><div class="text-gray-500">- {{ message.created_at.strftime('%d %b %Y') }}+ {{ message.created_at.strftime('%d %b %Y %H:%M') }}</div></div>+ {% if message.content %}<p class="text-gray-500">{{ message.content }}</p>+ {% endif %}</div></div>{% else %}@@ -106,13 +82,13 @@</div></div>- <!-- Reminders -->- <div class="col-start-5 col-end-7">- <div class="rounded-md ring-1 ring-gray-200 p-4">- <h2 class="text-lg pb-4">⏰ Reminders</h2>+ <div class="col-start-5 col-end-7 space-y-4">+ <!-- Reminders -->+ <div class="rounded-md lg:ring-1 ring-gray-200/60 p-4">+ <h2 class="text-lg pb-4">⏰ Rappels</h2>{% if not call.reminders %}- <p class="p-4 text-gray-500">No reminders yet.</p>+ <p class="text-gray-500">Aucun rappel pour l'instant.</p>{% else %}<div class="space-y-6"><!-- TODO: Sort reminders by due date -->@@ -127,6 +103,34 @@</div>{% endif %}</div>++ <!-- Details -->+ <div class="rounded-md lg:ring-1 ring-gray-200/60">+ <h2 class="text-lg px-4 pt-4">🔎 Détails</h2>+ <table class="table-auto w-full">+ <tbody>+ <tr class="border-b border-slate-100">+ <td class="p-4 text-gray-500">Date</td>+ <!-- TODO: Try to parse the date and display it in a human readable format -->+ <td class="p-4">+ {{ call.claim.incident_location }}, {{ call.claim.incident_date_time }}+ </td>+ </tr>+ <tr class="border-b border-slate-100">+ <td class="p-4 text-gray-500">Police</td>+ <td class="p-4">+ {{ call.claim.policy_number }}+ </td>+ </tr>+ <tr class="border-b border-slate-100">+ <td class="p-4 text-gray-500">Contact</td>+ <td class="p-4">+ {{ call.claim.policyholder_email | lower }}, {{ call.claim.policyholder_phone }}+ </td>+ </tr>+ </tbody>+ </table>+ </div></div></div></body>