Skip to content

Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!

Python

breaking: Allow to configure task and claim schema on demand by API

Clémence Lesnéc9fc9f89169a
diff --git a/Makefile b/Makefile
index ade8a9b..f0835cf 100644
--- a/Makefile
+++ b/Makefile
@@ -13,9 +13,6 @@ cognitive_communication_location := westeurope
openai_location := southcentralus
search_location := northeurope
# App configuration
-agent_phone_number ?= $(shell cat config.yaml | yq '.workflow.agent_phone_number')
-bot_company ?= $(shell cat config.yaml | yq '.workflow.bot_company')
-bot_name ?= $(shell cat config.yaml | yq '.workflow.bot_name')
bot_phone_number ?= $(shell cat config.yaml | yq '.communication_service.phone_number')
event_subscription_name ?= $(shell echo '$(name)-$(bot_phone_number)' | tr -dc '[:alnum:]-')
twilio_phone_number ?= $(shell cat config.yaml | yq '.sms.twilio.phone_number')
@@ -137,9 +134,6 @@ deploy:
az deployment sub create \
--location $(app_location) \
--parameters \
- 'agentPhoneNumber=$(agent_phone_number)' \
- 'botCompany=$(bot_company)' \
- 'botName=$(bot_name)' \
'cognitiveCommunicationLocation=$(cognitive_communication_location)' \
'openaiLocation=$(openai_location)' \
'searchLocation=$(search_location)' \
diff --git a/README.md b/README.md
index adb21d1..0fda5df 100644
--- a/README.md
+++ b/README.md
@@ -8,36 +8,39 @@ AI-powered call center solution with Azure and OpenAI GPT.
## Overview
-A French demo is avaialble on YouTube. Do not hesitate to watch the demo in x1.5 speed to get a quick overview of the project.
-
-[![French demo](https://img.youtube.com/vi/4r5s-NZ9CuY/maxresdefault.jpg)](https://youtube.com/watch?v=4r5s-NZ9CuY)
+Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
-Main interactions shown in the demo:
+Insurance, IT support, customer service, and more. The bot can be customized in few seconds (really) to fit your needs.
-1. User calls the call center
-2. The bot answers and the conversation starts
-3. The bot stores conversation, claim and todo list in the database
-
-Extract of the data stored during the call:
-
-```json
-{
- "claim": {
- "incident_date_time": "2024-01-11T19:33:41",
- "incident_description": "The vehicle began to travel with a burning smell and the driver pulled over to the side of the freeway.",
- "policy_number": "B01371946",
- "policyholder_phone": "[number masked for the demo]",
- "policyholder_name": "Clémence Lesne",
- "vehicle_info": "Ford Fiesta 2003"
- },
- "reminders": [
+```bash
+# Ask the bot to call a phone number
+data='{
+ "bot_company": "Contoso",
+ "bot_name": "Marion",
+ "phone_number": "+11234567890",
+ "task": "Assistant will help the customer with their digital workplace. Assistant is working for the IT support department. The objective is to help the customer with their issue and gather information in the claim.",
+ "agent_phone_number": "+33612345678",
+ "claim": [
{
- "description": "Check that all the information in Clémence Lesne's file is correct and complete.",
- "due_date_time": "2024-01-18T16:00:00",
- "title": "Check Clémence file"
+ "name": "hardware_info",
+ "type": "text"
+ },
+ {
+ "name": "first_seen",
+ "type": "datetime"
+ },
+ {
+ "name": "building_location",
+ "type": "text"
}
]
-}
+}'
+
+curl \
+ --header 'Content-Type: application/json' \
+ --request POST \
+ --url https://xxx/call \
+ --data $data
```
### Features
@@ -69,6 +72,40 @@ Extract of the data stored during the call:
- [ ] Call back the user when needed
- [ ] Simulate a IVR workflow
+### Demo
+
+A French demo is avaialble on YouTube. Do not hesitate to watch the demo in x1.5 speed to get a quick overview of the project.
+
+[![French demo](https://img.youtube.com/vi/4r5s-NZ9CuY/maxresdefault.jpg)](https://youtube.com/watch?v=4r5s-NZ9CuY)
+
+Main interactions shown in the demo:
+
+1. User calls the call center
+2. The bot answers and the conversation starts
+3. The bot stores conversation, claim and todo list in the database
+
+Extract of the data stored during the call:
+
+```json
+{
+ "claim": {
+ "incident_date_time": "2024-01-11T19:33:41",
+ "incident_description": "The vehicle began to travel with a burning smell and the driver pulled over to the side of the freeway.",
+ "policy_number": "B01371946",
+ "policyholder_phone": "[number masked for the demo]",
+ "policyholder_name": "Clémence Lesne",
+ "vehicle_info": "Ford Fiesta 2003"
+ },
+ "reminders": [
+ {
+ "description": "Check that all the information in Clémence Lesne's file is correct and complete.",
+ "due_date_time": "2024-01-18T16:00:00",
+ "title": "Check Clémence file"
+ }
+ ]
+}
+```
+
### User report after the call
A report is available at `https://[your_domain]/report/[phone_number]` (like `http://localhost:8080/report/%2B133658471534`). It shows the conversation history, claim data and reminders.
@@ -85,11 +122,11 @@ graph
user(["User"])
agent(["Agent"])
- api["Claim AI"]
+ app["Call Center AI"]
- api -- Transfer to --> agent
- api -. Send voice .-> user
- user -- Call --> api
+ app -- Transfer to --> agent
+ app -. Send voice .-> user
+ user -- Call --> app
```
### Component level architecture
@@ -104,7 +141,7 @@ graph LR
subgraph "Claim AI"
ai_search[("RAG\n(AI Search)")]
- api["API"]
+ app["App"]
communication_service_sms["SMS gateway\n(Communication Services)"]
communication_service["Call gateway\n(Communication Services)"]
constent_safety["Moderation\n(Content Safety)"]
@@ -115,16 +152,16 @@ graph LR
translation["Translation\n(Cognitive Services)"]
end
- api -- Answer with text --> communication_service
- api -- Ask for translation --> translation
- api -- Few-shot training --> ai_search
- api -- Generate completion --> gpt
- api -- Get cached data --> redis
- api -- Save conversation --> db
- api -- Send SMS report --> communication_service_sms
- api -- Test for profanity --> constent_safety
- api -- Transfer to agent --> communication_service
- api -. Watch .-> event_grid
+ app -- Answer with text --> communication_service
+ app -- Ask for translation --> translation
+ app -- Few-shot training --> ai_search
+ app -- Generate completion --> gpt
+ app -- Get cached data --> redis
+ app -- Save conversation --> db
+ app -- Send SMS report --> communication_service_sms
+ app -- Test for profanity --> constent_safety
+ app -- Transfer to agent --> communication_service
+ app -. Watch .-> event_grid
communication_service -- Notifies --> event_grid
communication_service -- Transfer to --> agent
@@ -149,58 +186,58 @@ sequenceDiagram
participant Event Grid
participant Communication Services
participant Content Safety
- participant API
+ participant App
participant Cosmos DB
participant OpenAI GPT
participant AI Search
- API->>Event Grid: Subscribe to events
+ App->>Event Grid: Subscribe to events
Customer->>PSTN: Initiate a call
PSTN->>Communication Services: Forward call
Communication Services->>Event Grid: New call event
- Event Grid->>API: Send event to event URL (HTTP webhook)
- activate API
- API->>Communication Services: Accept the call and give inbound URL
- deactivate API
+ Event Grid->>App: Send event to event URL (HTTP webhook)
+ activate App
+ App->>Communication Services: Accept the call and give inbound URL
+ deactivate App
Communication Services->>Speech to Text: Transform speech to text
- Communication Services->>API: Send text to the inbound URL
- activate API
+ Communication Services->>App: Send text to the inbound URL
+ activate App
alt First call
- API->>Communication Services: Send static SSML text
+ App->>Communication Services: Send static SSML text
else Callback
- API->>AI Search: Gather training data
- API->>OpenAI GPT: Ask for a completion
- OpenAI GPT-->>API: Answer (HTTP/2 SSE)
+ App->>AI Search: Gather training data
+ App->>OpenAI GPT: Ask for a completion
+ OpenAI GPT-->>App: Answer (HTTP/2 SSE)
loop Over buffer
loop Over multiple tools
alt Is this a claim data update?
- API->>Content Safety: Ask for safety test
+ App->>Content Safety: Ask for safety test
alt Is the text safe?
- API->>Communication Services: Send dynamic SSML text
+ App->>Communication Services: Send dynamic SSML text
end
- API->>Cosmos DB: Update claim data
+ App->>Cosmos DB: Update claim data
else Does the user want the human agent?
- API->>Communication Services: Send static SSML text
- API->>Communication Services: Transfer to a human
+ App->>Communication Services: Send static SSML text
+ App->>Communication Services: Transfer to a human
Communication Services->>Human agent: Call the phone number
else Should we end the call?
- API->>Communication Services: Send static SSML text
- API->>Communication Services: End the call
+ App->>Communication Services: Send static SSML text
+ App->>Communication Services: End the call
end
end
alt Is there a text?
alt Is there enough text to make a sentence?
- API->>Content Safety: Ask for safety test
+ App->>Content Safety: Ask for safety test
alt Is the text safe?
- API->>Communication Services: Send dynamic SSML text
+ App->>Communication Services: Send dynamic SSML text
end
end
end
end
- API->>Cosmos DB: Persist conversation
+ App->>Cosmos DB: Persist conversation
end
- deactivate API
+ deactivate App
Communication Services->>PSTN: Send voice
PSTN->>Customer: Forward voice
```
@@ -217,10 +254,11 @@ Create a local `config.yaml` file (most of the fields are filled automatically b
```yaml
# config.yaml
workflow:
- agent_phone_number: "+33612345678"
- bot_company: Contoso
- bot_name: Robert
- lang: {}
+ initiate:
+ agent_phone_number: "+33612345678"
+ bot_company: Contoso
+ bot_name: Robert
+ lang: {}
communication_service:
phone_number: "+33612345678"
@@ -260,9 +298,10 @@ resources:
public_url: "https://xxx.blob.core.windows.net/public"
workflow:
- agent_phone_number: "+33612345678"
- bot_company: Contoso
- bot_name: Robert
+ initiate:
+ agent_phone_number: "+33612345678"
+ bot_company: Contoso
+ bot_name: Robert
communication_service:
access_key: xxx
@@ -364,140 +403,106 @@ Required index schema:
An exampe is [available at `examples/import-training.ipynb`](examples/import-training.ipynb). It shows how to import training data from a PDF files dataset.
-### Customize the prompts
+### Customize the languages
-Note that prompt examples contains `{xxx}` placeholders. These placeholders are replaced by the bot with the corresponding data. For example, `{bot_name}` is internally replaced by the bot name.
+The bot can be used in multiple languages. It can understand the language the user chose.
-Be sure to write all the TTS prompts in English. This language is used as a pivot language for the conversation translation.
+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
[...]
-prompts:
- tts:
- hello_tpl: |
- Hello, I'm {bot_name}, from {bot_company}! I'm an IT support specialist.
+workflow:
+ initiate:
+ 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"
+```
- Here's how I work: when I'm working, you'll hear a little music; then, at the beep, it's your turn to speak. You can speak to me naturally, I'll understand.
+### Customize the moderation levels
- Examples:
- - "I've got a problem with my computer, it won't turn on".
- - "The external screen is flashing, I don't know why".
+Levels are defined for each category of Content Safety. The higher the score, the more strict the moderation is, from 0 to 7.
- What's your problem?
- llm:
- default_system_tpl: |
- Assistant is called {bot_name} and is in a call center for the company {bot_company} as an expert with 20 years of experience in IT service.
+Moderation is applied on all bot data, including the web page and the conversation.
- # Context
- Today is {date}. Customer is calling from {phone_number}. Call center number is {bot_phone_number}.
- chat_system_tpl: |
- # Objective
- 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.
+```yaml
+# config.yaml
+[...]
- # Rules
- - 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
- - Use additional context to enhance the conversation with useful details
- - When the employee says a word and then spells out letters, this means that the word is written in the way the employee spelled it (e.g. "I work in Paris PARIS", "My name is John JOHN", "My email is Clemence CLEMENCE at gmail GMAIL dot com COM")
- - You work for {bot_company}, not someone else
+content_safety:
+ category_hate_score: 0
+ category_self_harm_score: 0
+ category_sexual_score: 5
+ category_violence_score: 0
+```
- # Required employee data to be gathered by the assistant
- - Department
- - Description of the IT issue or request
- - Employee name
- - Location
+### Customize the claim data schema
- # General process to follow
- 1. Gather information to know the employee's identity (e.g. name, department)
- 2. Gather details about the IT issue or request to understand the situation (e.g. description, location)
- 3. Provide initial troubleshooting steps or solutions
- 4. Gather additional information if needed (e.g. error messages, screenshots)
- 5. Be proactive and create reminders for follow-up or further assistance
+Customization of the data schema is fully supported. You can add or remove fields as needed, depending on the requirements.
- # Support status
- {claim}
+By default, the schema of composed of:
- # Reminders
- {reminders}
-```
+- `caller_email` (`email`)
+- `caller_name` (`text`)
+- `caller_phone` (`phone_number`)
+- `extra_details` (`text`)
-### Customize the languages
+Values are validated to ensure the data format commit to your schema. They can be either:
-The bot can be used in multiple languages. It can understand the language the user chose.
+- `datetime`
+- `email`
+- `phone_number` (`E164` format)
+- `text`
-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.
+Finally, an optional description can be provided. The description must be short and meaningful, it will be passed to the LLM.
+
+Default schema, for inbound calls, is defined in the configuration:
```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"
+ default_initiate:
+ claim:
+ - name: additional_notes
+ type: text
+ # description: xxx
+ - name: device_info
+ type: text
+ # description: xxx
+ - name: incident_datetime
+ type: datetime
+ # description: xxx
```
-### Customize the moderation levels
+Claim schema can be customized for each call, by adding the `claim` field in the `POST /call` API call.
-Levels are defined for each category of Content Safety. The higher the score, the more strict the moderation is, from 0 to 7.
+### Customize the call objective
-Moderation is applied on all bot data, including the web page and the conversation.
+The objective is a description of what the bot will do during the call. It is used to give a context to the LLM. It should be short, meaningful, and written in English.
+
+This solution is priviledged instead of overriding the LLM prompt.
+
+Default task, for inbound calls, is defined in the configuration:
```yaml
# config.yaml
[...]
-content_safety:
- category_hate_score: 0
- category_self_harm_score: 0
- category_sexual_score: 5
- category_violence_score: 0
+workflow:
+ initiate:
+ task: "Assistant will help the customer with their insurance claim. Assistant requires data from the customer to fill the claim. The latest claim data will be given. Assistant role is not over until all the relevant data is gathered."
```
-### Customize the claim data schema
-
-Customization of the data schema is not supported yet through the configuration file. However, you can customize the data schema by modifying the application source code.
-
-The data schema is defined in `models/claim.py`. All the fields are required to be of type `Optional[str]` (except the immutable fields).
-
-```python
-# models/claim.py
-class ClaimModel(BaseModel):
- # Immutable fields
- # [...]
- # Editable fields
- additional_notes: Optional[str] = None
- device_info: Optional[str] = None
- error_messages: Optional[str] = None
- follow_up_required: Optional[bool] = None
- incident_date_time: Optional[datetime] = None
- issue_description: Optional[str] = None
- resolution_details: Optional[str] = None
- steps_taken: Optional[str] = None
- ticket_id: Optional[str] = None
- user_email: Optional[EmailStr] = None
- user_name: Optional[str] = None
- user_phone: Optional[PhoneNumber] = None
-
- # Depending on requirements, you might also include fields for:
- # - Software version
- # - Operating system
- # - Network details (if relevant to the issue)
- # - Any attachments like screenshots or log files (consider how to handle binary data)
-
- # Built-in functions
- [...]
-```
+Task can be customized for each call, by adding the `task` field in the `POST /call` API call.
### Use an OpenAI compatible model for the LLM
@@ -555,3 +560,74 @@ sms:
auth_token: xxx
phone_number: "+33612345678"
```
+
+### Customize the prompts
+
+Note that prompt examples contains `{xxx}` placeholders. These placeholders are replaced by the bot with the corresponding data. For example, `{bot_name}` is internally replaced by the bot name.
+
+Be sure to write all the TTS prompts in English. This language is used as a pivot language for the conversation translation.
+
+```yaml
+# config.yaml
+[...]
+
+prompts:
+ tts:
+ hello_tpl: |
+ Hello, I'm {bot_name}, from {bot_company}! I'm an IT support specialist.
+
+ Here's how I work: when I'm working, you'll hear a little music; then, at the beep, it's your turn to speak. You can speak to me naturally, I'll understand.
+
+ Examples:
+ - "I've got a problem with my computer, it won't turn on".
+ - "The external screen is flashing, I don't know why".
+
+ What's your problem?
+ llm:
+ default_system_tpl: |
+ Assistant is called {bot_name} and is in a call center for the company {bot_company} as an expert with 20 years of experience in IT service.
+
+ # Context
+ Today is {date}. Customer is calling from {phone_number}. Call center number is {bot_phone_number}.
+ chat_system_tpl: |
+ # Objective
+ 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 {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
+ - Use additional context to enhance the conversation with useful details
+ - When the employee says a word and then spells out letters, this means that the word is written in the way the employee spelled it (e.g. "I work in Paris PARIS", "My name is John JOHN", "My email is Clemence CLEMENCE at gmail GMAIL dot com COM")
+ - You work for {bot_company}, not someone else
+
+ # Required employee data to be gathered by the assistant
+ - Department
+ - Description of the IT issue or request
+ - Employee name
+ - Location
+
+ # General process to follow
+ 1. Gather information to know the employee's identity (e.g. name, department)
+ 2. Gather details about the IT issue or request to understand the situation (e.g. description, location)
+ 3. Provide initial troubleshooting steps or solutions
+ 4. Gather additional information if needed (e.g. error messages, screenshots)
+ 5. Be proactive and create reminders for follow-up or further assistance
+
+ # Support status
+ {claim}
+
+ # Reminders
+ {reminders}
+```
+
+## Q&A
+
+### Why no LLM framework is used?
+
+At the time of development, no LLM framework was available to handle all of these features: streaming capability with multi-tools, backup models on availability issue, callbacks mechanisms in the triggered tools. So, OpenAI SDK is used directly and some algorithms are implemented to handle reliability.
+
+### What's missing in this project for production deployment?
+
+Mostly decoupling. Today, post-call intelligence is done with the BackgroundTasks implementation from Starlette. But this executes tasks in the worker same thread, after the HTTP reponse made. For production, a message broker like Azure Service Bus should be used (Dapr can ease your life by abstracting it from the code).
diff --git a/bicep/app.bicep b/bicep/app.bicep
index 6187697..69ee049 100644
--- a/bicep/app.bicep
+++ b/bicep/app.bicep
@@ -1,8 +1,5 @@
param adaModel string
param adaVersion string
-param agentPhoneNumber string
-param botCompany string
-param botName string
param cognitiveCommunicationLocation string
param gptBackupContext int
param gptBackupModel string
@@ -22,6 +19,7 @@ var appUrl = 'https://call-center-ai.${acaEnv.properties.defaultDomain}'
var gptBackupModelFullName = toLower('${gptBackupModel}-${gptBackupVersion}')
var gptModelFullName = toLower('${gptModel}-${gptVersion}')
var adaModelFullName = toLower('${adaModel}-${adaVersion}')
+var cosmosContainerName = 'calls-v3' // Third schema version
var localConfig = loadYamlContent('../config.yaml')
var config = {
api: {
@@ -45,10 +43,12 @@ var config = {
public_url: storageAccount.properties.primaryEndpoints.web
}
workflow: {
- agent_phone_number: agentPhoneNumber
- bot_company: botCompany
- bot_name: botName
- lang: localConfig.workflow.lang
+ initiate: {
+ agent_phone_number: localConfig.workflow.initiate.agent_phone_number
+ bot_company: localConfig.workflow.initiate.bot_company
+ bot_name: localConfig.workflow.initiate.bot_name
+ lang: localConfig.workflow.initiate.lang
+ }
}
communication_service: {
access_key: communication.listKeys().primaryKey
@@ -508,10 +508,10 @@ resource database 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases@2023-11-15
resource container 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers@2023-11-15' = {
parent: database
- name: 'calls'
+ name: cosmosContainerName
properties: {
resource: {
- id: 'calls'
+ id: cosmosContainerName
indexingPolicy: {
automatic: true
includedPaths: [
@@ -544,7 +544,7 @@ resource container 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/container
}
partitionKey: {
paths: [
- '/phone_number'
+ '/initiate/phone_number'
]
kind: 'Hash'
}
diff --git a/bicep/main.bicep b/bicep/main.bicep
index 58af261..1a025bc 100644
--- a/bicep/main.bicep
+++ b/bicep/main.bicep
@@ -1,8 +1,5 @@
param adaModel string = 'text-embedding-ada-002'
param adaVersion string = '2'
-param agentPhoneNumber string
-param botCompany string
-param botName string
param cognitiveCommunicationLocation string
param gptBackupContext int = 16385
param gptBackupModel string = 'gpt-35-turbo'
@@ -43,9 +40,6 @@ module app 'app.bicep' = {
params: {
adaModel: adaModel
adaVersion: adaVersion
- agentPhoneNumber: agentPhoneNumber
- botCompany: botCompany
- botName: botName
cognitiveCommunicationLocation: cognitiveCommunicationLocation
gptBackupContext: gptBackupContext
gptBackupModel: gptBackupModel
diff --git a/helpers/call_events.py b/helpers/call_events.py
index 7a081fc..7327b07 100644
--- a/helpers/call_events.py
+++ b/helpers/call_events.py
@@ -80,7 +80,7 @@ async def on_call_connected(
client: CallAutomationClient,
) -> None:
_logger.info("Call connected")
- call.recognition_retry = 0 # Reset recognition retry counter
+ call.voice_recognition_retry = 0 # Reset recognition retry counter
call.messages.append(
MessageModel(
action=MessageActionEnum.CALL,
@@ -131,14 +131,14 @@ async def on_speech_timeout_error(
call: CallStateModel,
client: CallAutomationClient,
) -> None:
- if call.recognition_retry < 10:
+ if call.voice_recognition_retry < 10:
await handle_recognize_text(
call=call,
client=client,
store=False, # Do not store timeout prompt as it perturbs the LLM and makes it hallucinate
text=await CONFIG.prompts.tts.timeout_silence(call),
)
- call.recognition_retry += 1
+ call.voice_recognition_retry += 1
else:
await handle_play(
call=call,
@@ -189,7 +189,7 @@ async def on_play_completed(
await handle_transfer(
call=call,
client=client,
- target=CONFIG.workflow.agent_phone_number,
+ target=call.initiate.agent_phone_number,
)
@@ -222,8 +222,8 @@ async def on_ivr_recognized(
) -> None:
try:
lang = next(
- (x for x in CONFIG.workflow.lang.availables if x.short_code == label),
- CONFIG.workflow.lang.default_lang,
+ (x for x in call.initiate.lang.availables if x.short_code == label),
+ call.initiate.lang.default_lang,
)
except ValueError:
_logger.warning(f"Unknown IVR {label}, code not implemented")
@@ -284,7 +284,7 @@ async def on_sms_received(
client: CallAutomationClient,
message: str,
) -> bool:
- _logger.info(f"SMS received from {call.phone_number}: {message}")
+ _logger.info(f"SMS received from {call.initiate.phone_number}: {message}")
call.messages.append(
MessageModel(
action=MessageActionEnum.SMS,
@@ -365,7 +365,9 @@ async def _post_call_sms(call: CallStateModel) -> None:
# Send the SMS to both the current caller and the policyholder
success = False
- for number in set([call.phone_number, call.claim.policyholder_phone]):
+ for number in set(
+ [call.initiate.phone_number, call.claim.get("policyholder_phone", None)]
+ ):
if not number:
continue
res = await _sms.asend(content, number)
@@ -457,7 +459,7 @@ async def _handle_ivr_language(
DtmfTone.NINE,
]
choices = []
- for i, lang in enumerate(CONFIG.workflow.lang.availables):
+ for i, lang in enumerate(CONFIG.workflow.initiate.lang.availables):
choices.append(
RecognitionChoice(
label=lang.short_code,
diff --git a/helpers/call_llm.py b/helpers/call_llm.py
index a5141d3..de91a81 100644
--- a/helpers/call_llm.py
+++ b/helpers/call_llm.py
@@ -98,9 +98,7 @@ def _llm_completion_system(
) -> list[ChatCompletionSystemMessageParam]:
messages = [
ChatCompletionSystemMessageParam(
- content=CONFIG.prompts.llm.default_system(
- phone_number=call.phone_number,
- ),
+ content=CONFIG.prompts.llm.default_system(call),
role="system",
),
ChatCompletionSystemMessageParam(
@@ -327,9 +325,7 @@ async def _execute_llm_chat(
# Build system prompts
system = [
ChatCompletionSystemMessageParam(
- content=CONFIG.prompts.llm.default_system(
- phone_number=call.phone_number,
- ),
+ content=CONFIG.prompts.llm.default_system(call),
role="system",
),
ChatCompletionSystemMessageParam(
diff --git a/helpers/call_utils.py b/helpers/call_utils.py
index ea9654f..0c4892f 100644
--- a/helpers/call_utils.py
+++ b/helpers/call_utils.py
@@ -78,7 +78,7 @@ async def _handle_recognize_media(
input_type=RecognizeInputType.SPEECH,
play_prompt=FileSource(url=sound_url),
speech_language=call.lang.short_code,
- target_participant=PhoneNumberIdentifier(call.phone_number), # type: ignore
+ target_participant=PhoneNumberIdentifier(call.initiate.phone_number), # type: ignore
)
except ResourceNotFoundError:
_logger.debug(f"Call hung up before recognizing")
@@ -257,7 +257,7 @@ async def handle_recognize_ivr(
interrupt_prompt=True,
play_prompt=_audio_from_text(text, MessageStyleEnum.NONE, call),
speech_language=call.lang.short_code,
- target_participant=PhoneNumberIdentifier(call.phone_number), # type: ignore
+ target_participant=PhoneNumberIdentifier(call.initiate.phone_number), # type: ignore
)
except ResourceNotFoundError:
_logger.debug(f"Call hung up before recognizing")
diff --git a/helpers/config_models/prompts.py b/helpers/config_models/prompts.py
index fff1428..83a63e4 100644
--- a/helpers/config_models/prompts.py
+++ b/helpers/config_models/prompts.py
@@ -1,5 +1,6 @@
from azure.core.exceptions import HttpResponseError
from datetime import datetime, UTC
+from fastapi.encoders import jsonable_encoder
from functools import cached_property
from logging import Logger
from models.call import CallStateModel
@@ -10,6 +11,7 @@ from models.training import TrainingModel
from pydantic import TypeAdapter, BaseModel
from textwrap import dedent
from typing import Optional
+import json
class SoundModel(BaseModel):
@@ -39,16 +41,16 @@ class LlmModel(BaseModel):
"""
default_system_tpl: str = """
- Assistant is called {bot_name} and is working in a call center for company {bot_company} as an expert with 20 years of experience. {bot_company} is a well-known and trusted insurance company in France. Assistant is proud to work for {bot_company}. Take a deep breath. This is critical for the customer.
+ Assistant is called {bot_name} and is working in a call center for company {bot_company} as an expert with 20 years of experience. {bot_company} is a well-known and trusted company. Assistant is proud to work for {bot_company}.
- Always assist with care, respect, and truth. Respond with utmost utility yet securely. Avoid harmful, unethical, prejudiced, or negative content. Ensure replies promote fairness and positivity.
+ Take a deep breath. This is critical for the customer. Always assist with care, respect, and truth. Respond with utmost utility yet securely. Avoid harmful, unethical, prejudiced, or negative content. Ensure replies promote fairness and positivity.
# Context
Today is {date}. The customer is calling from {phone_number}. The call center number is {bot_phone_number}.
"""
chat_system_tpl: str = """
# Objective
- Assistant will help the customer with their insurance claim. Assistant requires data from the customer to fill the claim. The latest claim data will be given. Assistant role is not over until all the relevant data is gathered.
+ {task}
# Rules
- Answer directly to the customer's questions
@@ -76,16 +78,14 @@ class LlmModel(BaseModel):
- Use trusted data to answer the customer's questions
- Welcome the customer when they call
- 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 PARIS" -> "Paris", "My name is John JOHN" -> "John", "My email is Clemence CLEMENCE at gmail GMAIL dot com COM" -> "[email protected]")
- - Will answer the customer's questions if they are related to their contract, claim, or insurance
+ - Will answer the customer's questions if they are related to the objective or the claim
- Work for {bot_company}, not someone else
# 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
+ - Mean of contact (e.g. phone number)
# General process to follow
1. Quickly introduce yourself, if the customer is not already familiar with you, and recall the last conversation, if any
@@ -146,7 +146,6 @@ class LlmModel(BaseModel):
- 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
- 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")
@@ -155,6 +154,9 @@ class LlmModel(BaseModel):
- Use simple and short sentences
- Won't make any assumptions
+ # Initial objective of the call
+ {task}
+
# Claim status
{claim}
@@ -187,12 +189,8 @@ class LlmModel(BaseModel):
- Prefix the answer with a determiner (e.g., "the theft of your car", "your broken window")
- Won't make any assumptions
- # 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"
+ # Initial objective of the call
+ {task}
# Claim status
{claim}
@@ -200,8 +198,12 @@ class LlmModel(BaseModel):
# Reminders
{reminders}
- # Conversation history
- {messages}
+ # 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"
"""
synthesis_long_system_tpl: str = """
# Objective
@@ -219,6 +221,9 @@ class LlmModel(BaseModel):
- Use Markdown syntax to format the message with paragraphs, bold text, and URL
- Won't make any assumptions
+ # Initial objective of the call
+ {task}
+
# Claim status
{claim}
@@ -247,9 +252,6 @@ class LlmModel(BaseModel):
# Reminders
{reminders}
- # Conversation history
- {messages}
-
# Response format
[source text]\\n
*[extract from text]: "citation from claim, reminders, or messages"
@@ -280,6 +282,9 @@ class LlmModel(BaseModel):
- Won't make any assumptions
- Write no more than a few sentences as justification
+ # Initial objective of the call
+ {task}
+
# Allowed actions
{actions}
@@ -289,9 +294,6 @@ class LlmModel(BaseModel):
# Reminders
{reminders}
- # Conversation history
- {messages}
-
# Response format
{{
"action": "[action]",
@@ -329,26 +331,25 @@ class LlmModel(BaseModel):
}}
"""
- def default_system(self, phone_number: str) -> str:
+ def default_system(self, call: CallStateModel) -> 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._return(
self.default_system_tpl.format(
- bot_company=CONFIG.workflow.bot_company,
- bot_name=CONFIG.workflow.bot_name,
+ bot_company=call.initiate.bot_company,
+ bot_name=call.initiate.bot_name,
bot_phone_number=CONFIG.communication_service.phone_number,
date=datetime.now(UTC)
.astimezone()
.strftime(
"%Y-%m-%d %H:%M"
), # Don't include seconds to enhance cache during unit tests. Example: "2024-02-01 18:58".
- phone_number=phone_number,
+ phone_number=call.initiate.phone_number,
)
)
def chat_system(self, call: CallStateModel, trainings: list[TrainingModel]) -> str:
- from helpers.config import CONFIG
from models.message import (
ActionEnum as MessageActionEnum,
StyleEnum as MessageStyleEnum,
@@ -357,49 +358,54 @@ class LlmModel(BaseModel):
return self._return(
self.chat_system_tpl,
actions=", ".join([action.value for action in MessageActionEnum]),
- bot_company=CONFIG.workflow.bot_company,
- claim=call.claim.model_dump_json(),
+ bot_company=call.initiate.bot_company,
+ claim=json.dumps(jsonable_encoder(call.claim, exclude_none=True)),
default_lang=call.lang.human_name,
reminders=TypeAdapter(list[ReminderModel])
- .dump_json(call.reminders)
+ .dump_json(call.reminders, exclude_none=True)
.decode(),
styles=", ".join([style.value for style in MessageStyleEnum]),
+ task=call.initiate.task,
trainings=trainings,
)
def sms_summary_system(self, call: CallStateModel) -> str:
- from helpers.config import CONFIG
-
return self._return(
self.sms_summary_system_tpl,
- bot_company=CONFIG.workflow.bot_company,
- bot_name=CONFIG.workflow.bot_name,
- claim=call.claim.model_dump_json(),
+ bot_company=call.initiate.bot_company,
+ bot_name=call.initiate.bot_name,
+ claim=json.dumps(jsonable_encoder(call.claim, exclude_none=True)),
default_lang=call.lang.human_name,
- messages=TypeAdapter(list[MessageModel]).dump_json(call.messages).decode(),
+ messages=TypeAdapter(list[MessageModel])
+ .dump_json(call.messages, exclude_none=True)
+ .decode(),
reminders=TypeAdapter(list[ReminderModel])
- .dump_json(call.reminders)
+ .dump_json(call.reminders, exclude_none=True)
.decode(),
+ task=call.initiate.task,
)
def synthesis_short_system(self, call: CallStateModel) -> str:
return self._return(
self.synthesis_short_system_tpl,
- claim=call.claim.model_dump_json(),
- messages=TypeAdapter(list[MessageModel]).dump_json(call.messages).decode(),
+ claim=json.dumps(jsonable_encoder(call.claim, exclude_none=True)),
reminders=TypeAdapter(list[ReminderModel])
- .dump_json(call.reminders)
+ .dump_json(call.reminders, exclude_none=True)
.decode(),
+ task=call.initiate.task,
)
def synthesis_long_system(self, call: CallStateModel) -> str:
return self._return(
self.synthesis_long_system_tpl,
- claim=call.claim.model_dump_json(),
- messages=TypeAdapter(list[MessageModel]).dump_json(call.messages).decode(),
+ claim=json.dumps(jsonable_encoder(call.claim, exclude_none=True)),
+ messages=TypeAdapter(list[MessageModel])
+ .dump_json(call.messages, exclude_none=True)
+ .decode(),
reminders=TypeAdapter(list[ReminderModel])
- .dump_json(call.reminders)
+ .dump_json(call.reminders, exclude_none=True)
.decode(),
+ task=call.initiate.task,
)
def citations_system(
@@ -410,26 +416,14 @@ class LlmModel(BaseModel):
The citations system is only used if `text` param is not empty, otherwise `None` is returned.
"""
- from models.message import PersonaEnum as MessagePersonaEnum
-
if not text:
return None
return self._return(
self.citations_system_tpl,
- claim=call.claim.model_dump_json(),
- messages=TypeAdapter(list[MessageModel])
- .dump_json(
- [
- message
- for message in call.messages
- if message.persona != MessagePersonaEnum.TOOL
- ],
- exclude={"tool_calls"},
- )
- .decode(), # Filter out tool messages, to avoid LLM to cite itself
+ claim=json.dumps(jsonable_encoder(call.claim, exclude_none=True)),
reminders=TypeAdapter(list[ReminderModel])
- .dump_json(call.reminders)
+ .dump_json(call.reminders, exclude_none=True)
.decode(),
text=text,
)
@@ -438,11 +432,11 @@ class LlmModel(BaseModel):
return self._return(
self.next_system_tpl,
actions=", ".join([action.value for action in NextActionEnum]),
- claim=call.claim.model_dump_json(),
- messages=TypeAdapter(list[MessageModel]).dump_json(call.messages).decode(),
+ claim=json.dumps(jsonable_encoder(call.claim, exclude_none=True)),
reminders=TypeAdapter(list[ReminderModel])
- .dump_json(call.reminders)
+ .dump_json(call.reminders, exclude_none=True)
.decode(),
+ task=call.initiate.task,
)
def _return(
@@ -451,8 +445,8 @@ class LlmModel(BaseModel):
trainings: Optional[list[TrainingModel]] = None,
**kwargs: str,
) -> str:
- # Build template
- res = dedent(prompt_tpl.format(**kwargs))
+ # Remove possible indentation then render the template
+ res = dedent(prompt_tpl.format(**kwargs)).strip()
# Format trainings, if any
if trainings:
@@ -491,17 +485,13 @@ class TtsModel(BaseModel):
"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 = """
- 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.
+ Hello, I'm {bot_name}, the virtual assistant {bot_company}! I can't work and listen at the same time.
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.
- 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".
-
During the conversation, you can also send me text messages. I'll get back to you by phone.
- May I ask what your problem is?
+ How can I help you today?
"""
timeout_silence_tpl: str = (
"I'm sorry, I didn't hear anything. If you need help, let me know how I can help you."
@@ -527,22 +517,18 @@ class TtsModel(BaseModel):
return await self._translate(self.error_tpl, call)
async def goodbye(self, call: CallStateModel) -> str:
- from helpers.config import CONFIG
-
return await self._translate(
self.goodbye_tpl,
call,
- bot_company=CONFIG.workflow.bot_company,
+ bot_company=call.initiate.bot_company,
)
async def hello(self, call: CallStateModel) -> str:
- from helpers.config import CONFIG
-
return await self._translate(
self.hello_tpl,
call,
- bot_company=CONFIG.workflow.bot_company,
- bot_name=CONFIG.workflow.bot_name,
+ bot_company=call.initiate.bot_company,
+ bot_name=call.initiate.bot_name,
)
async def timeout_silence(self, call: CallStateModel) -> str:
@@ -554,8 +540,8 @@ class TtsModel(BaseModel):
return await self._translate(
self.welcome_back_tpl,
call,
- bot_company=CONFIG.workflow.bot_company,
- bot_name=CONFIG.workflow.bot_name,
+ bot_company=call.initiate.bot_company,
+ bot_name=call.initiate.bot_name,
conversation_timeout_hour=CONFIG.workflow.conversation_timeout_hour,
)
@@ -563,10 +549,8 @@ class TtsModel(BaseModel):
return await self._translate(self.timeout_loading_tpl, call)
async def ivr_language(self, call: CallStateModel) -> str:
- from helpers.config import CONFIG
-
res = ""
- for i, lang in enumerate(CONFIG.workflow.lang.availables):
+ for i, lang in enumerate(call.initiate.lang.availables):
res += (
self._return(
self.ivr_language_tpl,
@@ -578,6 +562,9 @@ class TtsModel(BaseModel):
return await self._translate(res.strip(), call)
def _return(self, prompt_tpl: str, **kwargs) -> str:
+ """
+ Remove possible indentation in a string.
+ """
return dedent(prompt_tpl.format(**kwargs)).strip()
async def _translate(self, prompt_tpl: str, call: CallStateModel, **kwargs) -> str:
diff --git a/helpers/config_models/workflow.py b/helpers/config_models/workflow.py
index 476d54c..5159cda 100644
--- a/helpers/config_models/workflow.py
+++ b/helpers/config_models/workflow.py
@@ -1,6 +1,9 @@
-from functools import cached_property
-from pydantic import BaseModel
+from datetime import datetime
from helpers.pydantic_types.phone_numbers import PhoneNumber
+from models.claim import ClaimFieldModel, ClaimTypeEnum
+from pydantic import BaseModel, EmailStr, Field, create_model, ConfigDict
+from pydantic.fields import FieldInfo
+from typing import Annotated, Any, Optional, Tuple, Union
class LanguageEntryModel(BaseModel):
@@ -61,7 +64,7 @@ class LanguageModel(BaseModel):
),
]
- @cached_property
+ @property
def default_lang(self) -> LanguageEntryModel:
return next(
(
@@ -73,11 +76,97 @@ class LanguageModel(BaseModel):
)
-class WorkflowModel(BaseModel):
+class WorkflowInitiateModel(BaseModel):
agent_phone_number: PhoneNumber
bot_company: str
bot_name: str
+ claim: list[ClaimFieldModel] = [
+ ClaimFieldModel(name="extra_details", type=ClaimTypeEnum.TEXT),
+ ClaimFieldModel(name="incident_datetime", type=ClaimTypeEnum.DATETIME),
+ ClaimFieldModel(name="incident_description", type=ClaimTypeEnum.TEXT),
+ ClaimFieldModel(name="incident_location", type=ClaimTypeEnum.TEXT),
+ ClaimFieldModel(name="injuries", type=ClaimTypeEnum.TEXT),
+ ClaimFieldModel(name="medical_records", type=ClaimTypeEnum.TEXT),
+ ClaimFieldModel(name="parties", type=ClaimTypeEnum.TEXT),
+ ClaimFieldModel(name="policy_number", type=ClaimTypeEnum.TEXT),
+ ClaimFieldModel(name="pre_existing_damages", type=ClaimTypeEnum.TEXT),
+ ClaimFieldModel(name="witnesses", type=ClaimTypeEnum.TEXT),
+ ] # Configured like in v4 for compatibility
+ lang: LanguageModel = LanguageModel() # Object is fully defined by default
+ task: str = """
+ Assistant will help the customer with their insurance claim. Assistant requires data from the customer to fill the claim. Claim data is located in the customer file. Assistant role is not over until all the relevant data is gathered.
+ """
+
+ def claim_model(self) -> type[BaseModel]:
+ return _fields_to_pydantic(
+ name="ClaimEntryModel",
+ fields=[
+ *self.claim,
+ ClaimFieldModel(
+ description="Email of the customer",
+ name="policyholder_email",
+ type=ClaimTypeEnum.EMAIL,
+ ),
+ ClaimFieldModel(
+ description="First and last name of the customer",
+ name="policyholder_name",
+ type=ClaimTypeEnum.TEXT,
+ ),
+ ClaimFieldModel(
+ description="Phone number of the customer",
+ name="policyholder_phone",
+ type=ClaimTypeEnum.PHONE_NUMBER,
+ ),
+ ClaimFieldModel(
+ description="Relevant details gathered in the conversation than can be useful to solve the task",
+ name="extra_details",
+ type=ClaimTypeEnum.TEXT,
+ ),
+ ],
+ )
+
+
+class WorkflowModel(BaseModel):
conversation_timeout_hour: int = 72 # 3 days
+ initiate: WorkflowInitiateModel
intelligence_hard_timeout_sec: int = 180 # 3 minutes
intelligence_soft_timeout_sec: int = 30 # 30 seconds
- lang: LanguageModel = LanguageModel() # Object is fully defined by default
+
+
+def _fields_to_pydantic(name: str, fields: list[ClaimFieldModel]) -> type[BaseModel]:
+ field_definitions = {field.name: _field_to_pydantic(field) for field in fields}
+ return create_model(
+ name,
+ **field_definitions, # type: ignore
+ __config__=ConfigDict(
+ extra="ignore", # Avoid validation errors, just ignore data
+ ),
+ )
+
+
+def _field_to_pydantic(
+ field: ClaimFieldModel,
+) -> Union[Annotated[Any, ...], Tuple[type, FieldInfo]]:
+ type = _type_to_pydantic(field.type)
+ return (
+ Optional[type],
+ Field(
+ default=None,
+ description=field.description,
+ ),
+ )
+
+
+def _type_to_pydantic(
+ data: ClaimTypeEnum,
+) -> Union[type, Annotated[Any, ...]]:
+ if data == ClaimTypeEnum.DATETIME:
+ return datetime
+ elif data == ClaimTypeEnum.EMAIL:
+ return EmailStr
+ elif data == ClaimTypeEnum.PHONE_NUMBER:
+ return PhoneNumber
+ elif data == ClaimTypeEnum.TEXT:
+ return str
+ else:
+ raise ValueError(f"Unsupported data: {data}")
diff --git a/helpers/llm_tools.py b/helpers/llm_tools.py
index 3abea45..7b0cc63 100644
--- a/helpers/llm_tools.py
+++ b/helpers/llm_tools.py
@@ -5,7 +5,6 @@ from helpers.llm_utils import function_schema
from helpers.logging import build_logger
from inspect import getmembers, isfunction
from models.call import CallStateModel
-from models.claim import ClaimModel
from models.message import (
ActionEnum as MessageActionEnum,
MessageModel,
@@ -100,7 +99,7 @@ class LlmPlugins:
# Store the last message and use it at first message of the new claim
last_message = self.call.messages[-1]
call = CallStateModel(
- phone_number=self.call.phone_number,
+ initiate=self.call.initiate.model_copy(),
voice_id=self.call.voice_id,
)
call.messages += [
@@ -187,7 +186,13 @@ class LlmPlugins:
The field to update, in English.
# Available fields
- {{ call.claim.editable_fields() | join(', ') }}
+ {% for name, info in call.initiate.claim_model().model_fields.items() %}
+ {% if not info.description %}
+ - {{ name }}
+ {% else %}
+ - '{{ name }}', {{ info.description }}
+ {% endif %}
+ {% endfor %}
# Data format
- For dates, use YYYY-MM-DD HH:MM format (e.g. 2024-02-01 18:58)
@@ -222,17 +227,14 @@ class LlmPlugins:
def _update_claim_field(self, update: UpdateClaimDict) -> str:
field = update["field"]
- value = update["value"]
- # Check if field is editable
- if not field in self.call.claim.editable_fields():
- return f'Failed to update a non-editable field "{field}".'
+ new_value = update["value"]
try:
- # Define the field and force to trigger validation
- copy = self.call.claim.model_dump()
- copy[field] = value
- self.call.claim = ClaimModel.model_validate(copy)
- return f'Updated claim field "{field}" with value "{value}".'
- except ValidationError as e: # Catch error to inform LLM
+ old_value = self.call.claim.get(field, None)
+ self.call.claim[field] = new_value
+ CallStateModel.model_validate(self.call) # Force a re-validation
+ return f'Updated claim field "{field}" with value "{new_value}".'
+ except ValidationError as e: # Catch error to inform LLM and rollback changes
+ self.call.claim[field] = old_value
return f'Failed to edit field "{field}": {e.json()}'
async def talk_to_human(self) -> str:
@@ -364,7 +366,7 @@ class LlmPlugins:
await self.user_callback(customer_response, self.style)
success = await _sms.asend(
content=message,
- phone_number=self.call.phone_number,
+ phone_number=self.call.initiate.phone_number,
)
if not success:
return "Failed to send SMS"
diff --git a/main.py b/main.py
index f1e485d..a43cadf 100644
--- a/main.py
+++ b/main.py
@@ -32,7 +32,7 @@ from fastapi import (
)
from fastapi.responses import JSONResponse, HTMLResponse
from jinja2 import Environment, FileSystemLoader
-from models.call import CallStateModel, CallGetModel
+from models.call import CallStateModel, CallGetModel, CallInitiateModel
from models.next import ActionEnum as NextActionEnum
from urllib.parse import quote_plus, urljoin
import asyncio
@@ -197,8 +197,8 @@ async def report_single_get(call_id: UUID) -> HTMLResponse:
template = _jinja.get_template("single.html.jinja")
render = await template.render_async(
application_insights_connection_string=CONFIG.monitoring.application_insights.connection_string.get_secret_value(),
- bot_company=CONFIG.workflow.bot_company,
- bot_name=CONFIG.workflow.bot_name,
+ bot_company=call.initiate.bot_company,
+ bot_name=call.initiate.bot_name,
call=call,
next_actions=[action for action in NextActionEnum],
version=CONFIG.version,
@@ -239,13 +239,13 @@ async def call_get(call_id: UUID) -> CallGetModel:
description="Initiate a call to a phone number.",
name="Create call",
)
-async def call_post(phone_number: PhoneNumber) -> CallGetModel:
- url, call = await _communicationservices_event_url(phone_number)
+async def call_post(initiate: CallInitiateModel) -> CallGetModel:
+ url, call = await _communicationservices_event_url(initiate.phone_number, initiate)
call_connection_properties = _automation_client.create_call(
callback_url=url,
cognitive_services_endpoint=CONFIG.cognitive_service.endpoint,
source_caller_id_number=_source_caller,
- target_participant=PhoneNumberIdentifier(phone_number), # type: ignore
+ target_participant=PhoneNumberIdentifier(initiate.phone_number), # type: ignore
)
_logger.info(
f"Created call with connection id: {call_connection_properties.call_connection_id}"
@@ -475,7 +475,7 @@ async def _communicationservices_event_worker(
async def _communicationservices_event_url(
- phone_number: PhoneNumber,
+ phone_number: PhoneNumber, initiate: Optional[CallInitiateModel] = None
) -> tuple[str, CallStateModel]:
"""
Generate the callback URL for a call.
@@ -484,7 +484,13 @@ async def _communicationservices_event_url(
"""
call = await _db.call_asearch_one(phone_number)
if not call:
- call = CallStateModel(phone_number=phone_number)
+ call = CallStateModel(
+ initiate=initiate
+ or CallInitiateModel(
+ **CONFIG.workflow.initiate.model_dump(),
+ phone_number=phone_number,
+ )
+ )
await _db.call_aset(call) # Create for the first time
url = _COMMUNICATIONSERVICES_EVENT_TPL.format(
callback_secret=call.callback_secret,
diff --git a/models/call.py b/models/call.py
index 7819912..6358eab 100644
--- a/models/call.py
+++ b/models/call.py
@@ -1,30 +1,35 @@
from datetime import datetime, UTC, tzinfo
from helpers.config_models.workflow import LanguageEntryModel
+from helpers.config_models.workflow import WorkflowInitiateModel
from helpers.pydantic_types.phone_numbers import PhoneNumber
-from models.claim import ClaimModel
from models.message import MessageModel, ActionEnum as MessageActionEnum
from models.next import NextModel
from models.reminder import ReminderModel
from models.synthesis import SynthesisModel
from models.training import TrainingModel
-from pydantic import BaseModel, Field, computed_field
-from typing import Optional
+from pydantic import BaseModel, Field, computed_field, field_validator, ValidationInfo
+from typing import Any, Optional
from uuid import UUID, uuid4
import asyncio
import random
import string
+class CallInitiateModel(WorkflowInitiateModel):
+ phone_number: PhoneNumber
+
+
class CallGetModel(BaseModel):
# Immutable fields
call_id: UUID = Field(default_factory=uuid4, frozen=True)
created_at: datetime = Field(default_factory=lambda: datetime.now(UTC), frozen=True)
# Editable fields
- claim: ClaimModel = Field(default_factory=ClaimModel)
+ initiate: CallInitiateModel = Field(frozen=True)
+ claim: dict[str, Any] = Field(
+ default={}
+ ) # Place after "initiate" as it depends on it for validation
messages: list[MessageModel] = []
next: Optional[NextModel] = None
- phone_number: PhoneNumber
- recognition_retry: int = Field(default=0)
reminders: list[ReminderModel] = []
synthesis: Optional[SynthesisModel] = None
voice_id: Optional[str] = None
@@ -49,8 +54,18 @@ class CallGetModel(BaseModel):
# Otherwise, we assume the call is completed
return False
- def tz(self) -> tzinfo:
- return PhoneNumber.tz(self.phone_number)
+ @field_validator("claim")
+ def _validate_claim(
+ cls, claim: Optional[dict[str, Any]], info: ValidationInfo
+ ) -> dict[str, Any]:
+ initiate: Optional[CallInitiateModel] = info.data.get("initiate", None)
+ if not initiate:
+ return {}
+ return (
+ initiate.claim_model()
+ .model_validate(claim, strict=True)
+ .model_dump(exclude_none=True)
+ )
class CallStateModel(CallGetModel):
@@ -73,16 +88,18 @@ class CallStateModel(CallGetModel):
def lang(self) -> LanguageEntryModel: # type: ignore
from helpers.config import CONFIG
+ lang = CONFIG.workflow.initiate.lang
+ default = lang.default_lang
if self.lang_short_code:
return next(
(
lang
- for lang in CONFIG.workflow.lang.availables
+ for lang in lang.availables
if lang.short_code == self.lang_short_code
),
- CONFIG.workflow.lang.default_lang,
+ default,
)
- return CONFIG.workflow.lang.default_lang
+ return default
@lang.setter
def lang(self, short_code: str) -> None:
@@ -111,3 +128,6 @@ class CallStateModel(CallGetModel):
set(training for trainings in tasks for training in trainings or [])
) # Flatten, remove duplicates, and sort by score
return trainings
+
+ def tz(self) -> tzinfo:
+ return PhoneNumber.tz(self.initiate.phone_number)
diff --git a/models/claim.py b/models/claim.py
index 08eee2b..eae1e20 100644
--- a/models/claim.py
+++ b/models/claim.py
@@ -1,46 +1,16 @@
-from datetime import datetime, UTC
-from pydantic import BaseModel, Field
-from pydantic import EmailStr
-from helpers.pydantic_types.phone_numbers import PhoneNumber
-from typing import Optional, Set
-import random
-import string
+from enum import Enum
+from pydantic import BaseModel
+from typing import Optional
-class ClaimModel(BaseModel):
- # Immutable fields
- claim_id: str = Field(
- default_factory=(
- lambda: "".join(
- random.choice(string.ascii_lowercase + string.digits) for _ in range(6)
- )
- ),
- frozen=True,
- )
- created_at: datetime = Field(default_factory=lambda: datetime.now(UTC), frozen=True)
- # Editable fields
- extra_details: Optional[str] = None
- incident_date_time: Optional[datetime] = None
- incident_description: Optional[str] = None
- incident_location: Optional[str] = None
- injuries_description: Optional[str] = None
- insurance_type: Optional[str] = None
- involved_parties: Optional[str] = None
- medical_records: Optional[str] = None
- police_report_number: Optional[str] = None
- policy_number: Optional[str] = None
- policyholder_email: Optional[EmailStr] = None
- policyholder_name: Optional[str] = None
- policyholder_phone: Optional[PhoneNumber] = None
- pre_existing_damage_description: Optional[str] = None
- property_damage_description: Optional[str] = None
- repair_replacement_estimates: Optional[str] = None
- stolen_lost_items: Optional[str] = None
- vehicle_info: Optional[str] = None
- witnesses: Optional[str] = None
+class ClaimTypeEnum(str, Enum):
+ DATETIME = "datetime"
+ EMAIL = "email"
+ PHONE_NUMBER = "phone_number"
+ TEXT = "text"
- def editable_fields(self) -> Set[str]:
- return self.model_json_schema()["properties"].keys() - [
- "id",
- "created_at",
- ]
+
+class ClaimFieldModel(BaseModel):
+ description: Optional[str] = None
+ name: str
+ type: ClaimTypeEnum
diff --git a/persistence/cosmos_db.py b/persistence/cosmos_db.py
index ad0826e..abb6fa4 100644
--- a/persistence/cosmos_db.py
+++ b/persistence/cosmos_db.py
@@ -34,7 +34,9 @@ class CosmosDbStore(IStore):
test_partition = "+33612345678"
test_dict = {
"id": test_id, # unique id
- "phone_number": test_partition, # partition key
+ "initiate": {
+ "phone_number": test_partition, # partition key
+ },
"test": "test",
}
try:
@@ -114,7 +116,7 @@ class CosmosDbStore(IStore):
async with self._use_db() as db:
items = db.query_items(
max_item_count=1,
- query=f"SELECT * FROM c WHERE (STRINGEQUALS(c.phone_number, @phone_number, true) OR STRINGEQUALS(c.claim.policyholder_phone, @phone_number, true)) AND c.created_at >= DATETIMEADD('hh', -{CONFIG.workflow.conversation_timeout_hour}, GETCURRENTDATETIME()) ORDER BY c.created_at DESC",
+ query=f"SELECT * FROM c WHERE (STRINGEQUALS(c.initiate.phone_number, @phone_number, true) OR STRINGEQUALS(c.claim.policyholder_phone, @phone_number, true)) AND c.created_at >= DATETIMEADD('hh', -{CONFIG.workflow.conversation_timeout_hour}, GETCURRENTDATETIME()) ORDER BY c.created_at DESC",
parameters=[
{
"name": "@phone_number",
@@ -154,7 +156,7 @@ class CosmosDbStore(IStore):
try:
async with self._use_db() as db:
items = db.query_items(
- query=f"SELECT * FROM c {"WHERE STRINGEQUALS(c.phone_number, @phone_number, true) OR STRINGEQUALS(c.claim.policyholder_phone, @phone_number, true)" if phone_number else ""} ORDER BY c.created_at DESC OFFSET 0 LIMIT @count",
+ query=f"SELECT * FROM c {"WHERE STRINGEQUALS(c.initiate.phone_number, @phone_number, true) OR STRINGEQUALS(c.claim.policyholder_phone, @phone_number, true)" if phone_number else ""} ORDER BY c.created_at DESC OFFSET 0 LIMIT @count",
parameters=[
{
"name": "@phone_number",
@@ -184,7 +186,7 @@ class CosmosDbStore(IStore):
try:
async with self._use_db() as db:
items = db.query_items(
- query=f"SELECT VALUE COUNT(1) FROM c {"WHERE STRINGEQUALS(c.phone_number, @phone_number, true) OR STRINGEQUALS(c.claim.policyholder_phone, @phone_number, true)" if phone_number else ""}",
+ query=f"SELECT VALUE COUNT(1) FROM c {"WHERE STRINGEQUALS(c.initiate.phone_number, @phone_number, true) OR STRINGEQUALS(c.claim.policyholder_phone, @phone_number, true)" if phone_number else ""}",
parameters=[
{
"name": "@phone_number",
diff --git a/persistence/sqlite.py b/persistence/sqlite.py
index 8687653..a1f2129 100644
--- a/persistence/sqlite.py
+++ b/persistence/sqlite.py
@@ -79,9 +79,9 @@ class SqliteStore(IStore):
call = None
async with self._use_db() as db:
cursor = await db.execute(
- f"SELECT data FROM {self._config.table} WHERE (JSON_EXTRACT(data, '$.phone_number') LIKE ? OR JSON_EXTRACT(data, '$.claim.policyholder_phone') LIKE ?) AND DATETIME(JSON_EXTRACT(data, '$.created_at')) >= DATETIME('now', '-{CONFIG.workflow.conversation_timeout_hour} hours') ORDER BY DATETIME(JSON_EXTRACT(data, '$.created_at')) DESC LIMIT 1",
+ f"SELECT data FROM {self._config.table} WHERE (JSON_EXTRACT(data, '$.initiate.phone_number') LIKE ? OR JSON_EXTRACT(data, '$.claim.policyholder_phone') LIKE ?) AND DATETIME(JSON_EXTRACT(data, '$.created_at')) >= DATETIME('now', '-{CONFIG.workflow.conversation_timeout_hour} hours') ORDER BY DATETIME(JSON_EXTRACT(data, '$.created_at')) DESC LIMIT 1",
(
- phone_number, # data.phone_number
+ phone_number, # data.initiate.phone_number
phone_number, # data.claim.policyholder_phone
),
)
@@ -113,13 +113,15 @@ class SqliteStore(IStore):
calls: list[CallStateModel] = []
async with self._use_db() as db:
cursor = await db.execute(
- f"SELECT data FROM {self._config.table} {"WHERE (JSON_EXTRACT(data, '$.phone_number') LIKE ? OR JSON_EXTRACT(data, '$.claim.policyholder_phone') LIKE ?)" if phone_number else ""} ORDER BY DATETIME(JSON_EXTRACT(data, '$.created_at')) DESC LIMIT ?",
+ f"SELECT data FROM {self._config.table} {"WHERE (JSON_EXTRACT(data, '$.initiate.phone_number') LIKE ? OR JSON_EXTRACT(data, '$.claim.policyholder_phone') LIKE ?)" if phone_number else ""} ORDER BY DATETIME(JSON_EXTRACT(data, '$.created_at')) DESC LIMIT ?",
(
- phone_number, # data.phone_number
- phone_number, # data.claim.policyholder_phone
- count, # limit
- ) if phone_number else (
- count, # limit
+ (
+ phone_number, # data.initiate.phone_number
+ phone_number, # data.claim.policyholder_phone
+ count, # limit
+ )
+ if phone_number
+ else (count,) # limit
),
)
rows = await cursor.fetchall()
@@ -138,11 +140,15 @@ class SqliteStore(IStore):
) -> int:
async with self._use_db() as db:
cursor = await db.execute(
- f"SELECT COUNT(*) FROM {self._config.table} {"WHERE (JSON_EXTRACT(data, '$.phone_number') LIKE ? OR JSON_EXTRACT(data, '$.claim.policyholder_phone') LIKE ?)" if phone_number else ""}",
+ f"SELECT COUNT(*) FROM {self._config.table} {"WHERE (JSON_EXTRACT(data, '$.initiate.phone_number') LIKE ? OR JSON_EXTRACT(data, '$.claim.policyholder_phone') LIKE ?)" if phone_number else ""}",
(
- phone_number, # data.phone_number
- phone_number, # data.claim.policyholder_phone
- ) if phone_number else (),
+ (
+ phone_number, # data.initiate.phone_number
+ phone_number, # data.claim.policyholder_phone
+ )
+ if phone_number
+ else ()
+ ),
)
row = await cursor.fetchone()
return int(row[0]) if row else 0
@@ -162,7 +168,7 @@ class SqliteStore(IStore):
)
# Create indexes
await db.execute(
- f"CREATE INDEX IF NOT EXISTS {self._config.table}_data_phone_number ON {self._config.table} (JSON_EXTRACT(data, '$.phone_number'))"
+ f"CREATE INDEX IF NOT EXISTS {self._config.table}_data_initiate_phone_number ON {self._config.table} (JSON_EXTRACT(data, '$.initiate.phone_number'))"
)
await db.execute(
f"CREATE INDEX IF NOT EXISTS {self._config.table}_data_created_at ON {self._config.table} (DATETIME(JSON_EXTRACT(data, '$.created_at')))"
diff --git a/public_website/list.html.jinja b/public_website/list.html.jinja
index 26bd04e..2ace20c 100644
--- a/public_website/list.html.jinja
+++ b/public_website/list.html.jinja
@@ -25,8 +25,8 @@ History for {{ phone_number or 'all numbers' }}
<div class="p-4 truncate col-span-2">📝 Short summary</div>
</div>
{% for call in calls %}
- <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 (%Z)') }}" 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>
+ <a href="/report/{{ call.call_id }}" title="Call from {{ call.initiate.phone_number }} the {{ call.created_at.astimezone(call.tz()).strftime('%d %b %Y, %H:%M (%Z)') }}" 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.initiate.phone_number }}</div>
<div class="p-4 truncate">{{ call.created_at.astimezone(call.tz()).strftime('%d %b %Y, %H:%M (%Z)') }}</div>
<div class="col-span-2 p-4 truncate">{{ call.synthesis.short | lower }}</div>
</a>
diff --git a/public_website/single.html.jinja b/public_website/single.html.jinja
index c8d3e61..dca7b0f 100644
--- a/public_website/single.html.jinja
+++ b/public_website/single.html.jinja
@@ -1,20 +1,20 @@
{% extends "templates/base.html.jinja" %}
{% block title %}
-Claim {{ call.claim.claim_id }} ({{ call.phone_number }})
+Claim ({{ call.initiate.phone_number }})
{% endblock %}
{% block content %}
<!-- Top introduction -->
<header class="col-span-full mx-4 mb-4">
<div class="my-4 text-neutral-600 dark:text-neutral-400">
- <a class="hover:underline" href="/report?phone_number={{ call.phone_number | quote_plus }}">
+ <a class="hover:underline" href="/report?phone_number={{ call.initiate.phone_number | quote_plus }}">
⬅ Go back to your call history
</a>
</div>
<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) if call.synthesis.short }} is being processed.</p>
+ <p class="text-2xl">Your claim {{ ('about ' ~ call.synthesis.short | lower) if call.synthesis.short }} is being processed.</p>
</header>
<!-- Long synthesis -->
@@ -165,7 +165,7 @@ Claim {{ call.claim.claim_id }} ({{ call.phone_number }})
},
{
'title': 'Phone used',
- 'value': call.phone_number or 'N/A'
+ 'value': call.initiate.phone_number or 'N/A'
}
]
%}
@@ -179,5 +179,13 @@ Claim {{ call.claim.claim_id }} ({{ call.phone_number }})
</tbody>
</table>
</div>
+
+ <!-- Task -->
+ <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">🫡 Task</h2>
+ <p class="text-neutral-600 dark:text-neutral-400">
+ {{ call.initiate.task }}
+ </p>
+ </div>
</div>
{% endblock %}
diff --git a/tests/conftest.py b/tests/conftest.py
index 64fa24d..780c714 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -5,7 +5,7 @@ from helpers.config import CONFIG
from helpers.logging import build_logger
from langchain_core.language_models import BaseChatModel
from langchain_openai import AzureChatOpenAI
-from models.call import CallStateModel
+from models.call import CallStateModel, CallInitiateModel
from textwrap import dedent
from typing import Any, Callable, Optional, Tuple, Union
import hashlib
@@ -96,7 +96,11 @@ def random_text() -> str:
@pytest.fixture
def call() -> CallStateModel:
call = CallStateModel(
- phone_number="+33612345678", # type: ignore
+ initiate=CallInitiateModel(
+ **CONFIG.workflow.initiate.model_dump(),
+ phone_number="+33612345678", # type: ignore
+ ),
+ voice_id="dummy",
)
return call
diff --git a/tests/llm.py b/tests/llm.py
index 8b79743..4312cdc 100644
--- a/tests/llm.py
+++ b/tests/llm.py
@@ -19,6 +19,7 @@ from models.reminder import ReminderModel
from models.training import TrainingModel
from pydantic import TypeAdapter
from pytest import assume
+import json
import pytest
from tests.conftest import CallConnectionClientMock
@@ -34,7 +35,7 @@ _logger = build_logger(__name__)
[
"Hello hello!",
],
- f"Hello, it is {CONFIG.workflow.bot_name}, from {CONFIG.workflow.bot_company}. How can I help you?",
+ f"Hello, it is {CONFIG.workflow.initiate.bot_name}, from {CONFIG.workflow.initiate.bot_company}. How can I help you?",
{
# No claim test inclusions
},
@@ -68,7 +69,7 @@ _logger = build_logger(__name__)
"Ok I understood, my house is located at 11 rue des Citronniers 75001 Paris.",
"Oh yes ond one more thing, which craftsman should I call to repair my shower?",
],
- f"My name is {CONFIG.workflow.bot_name}, from {CONFIG.workflow.bot_company}. I'm truly sorry to hear that. I have noted the policyholder name, incident description, your house location, and the incident date. If you need, I can create a reminder to follow up on a repair appointment?",
+ f"My name is {CONFIG.workflow.initiate.bot_name}, from {CONFIG.workflow.initiate.bot_company}. I'm truly sorry to hear that. I have noted the policyholder name, incident description, your house location, and the incident date. If you need, I can create a reminder to follow up on a repair appointment?",
[
"incident_date_time",
"incident_description",
@@ -202,12 +203,12 @@ async def test_llm(
# Log for dev review
_logger.info(f"actual_output: {actual_output}")
- _logger.info(f"claim: {call.claim.model_dump(exclude_none=True)}")
+ _logger.info(f"claim: {call.claim}")
_logger.info(f"full_input: {full_input}")
# Test claim data
for field in claim_tests_incl:
- assume(getattr(call.claim, field) is not None, f"Claim field {field} is None")
+ assume(call.claim.get(field, None), f"Claim field {field} is missing")
# Configure LLM tests
test_case = LLMTestCase(
@@ -215,7 +216,7 @@ async def test_llm(
expected_output=expected_output,
input=full_input,
retrieval_context=[
- call.claim.model_dump_json(exclude_none=True),
+ json.dumps(call.claim),
TypeAdapter(list[ReminderModel]).dump_json(call.reminders).decode(),
TypeAdapter(list[TrainingModel]).dump_json(await call.trainings()).decode(),
],
diff --git a/tests/store.py b/tests/store.py
index e27cf3b..792228d 100644
--- a/tests/store.py
+++ b/tests/store.py
@@ -38,11 +38,15 @@ async def test_acid(call: CallStateModel, database_mode: DatabaseModeEnum) -> No
# Check not exists
assume(not await db.call_aget(call.call_id))
- assume(await db.call_asearch_one(call.phone_number) != call)
+ assume(await db.call_asearch_one(call.initiate.phone_number) != call)
assume(
call
not in (
- (await db.call_asearch_all(phone_number=call.phone_number, count=1))[0]
+ (
+ await db.call_asearch_all(
+ phone_number=call.initiate.phone_number, count=1
+ )
+ )[0]
or []
)
)
@@ -53,12 +57,16 @@ async def test_acid(call: CallStateModel, database_mode: DatabaseModeEnum) -> No
# Check point read
assume(await db.call_aget(call.call_id) == call)
# Check search one
- assume(await db.call_asearch_one(call.phone_number) == call)
+ assume(await db.call_asearch_one(call.initiate.phone_number) == call)
# Check search all
assume(
call
in (
- (await db.call_asearch_all(phone_number=call.phone_number, count=1))[0]
+ (
+ await db.call_asearch_all(
+ phone_number=call.initiate.phone_number, count=1
+ )
+ )[0]
or []
)
)