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

feat: Receive SMS during a call with Communication Services or Twilio

Clémence Lesné6f79bdbc1614
diff --git a/Makefile b/Makefile
index 740aebc..d138620 100644
--- a/Makefile
+++ b/Makefile
@@ -18,6 +18,7 @@ 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')
# Bicep outputs
app_url ?= $(shell az deployment sub show --name $(name) | yq '.properties.outputs["appUrl"].value')
blob_storage_public_name ?= $(shell az deployment sub show --name $(name) | yq '.properties.outputs["blobStoragePublicName"].value')
@@ -37,6 +38,9 @@ install:
@echo "➡️ Installing Allure..."
allure --version || brew install allure
+ @echo "➡️ Installing Twilio CLI..."
+ twilio --version || brew tap twilio/brew && brew install twilio
+
@echo "➡️ Installing Python app dependencies..."
python3 -m pip install -r requirements.txt
@@ -101,6 +105,7 @@ dev:
--reload \
--reload-extra-file .env \
--reload-extra-file config.yaml \
+ --workers 2 \
--worker-class uvicorn.workers.UvicornWorker
build:
@@ -140,18 +145,21 @@ deploy:
--template-file bicep/main.bicep \
--name $(name)
- $(MAKE) post-deploy name=$(name)
+ @$(MAKE) post-deploy name=$(name)
post-deploy:
- $(MAKE) copy-resources \
+ @$(MAKE) copy-resources \
name=$(blob_storage_public_name)
- $(MAKE) eventgrid-register \
+ @$(MAKE) eventgrid-register \
endpoint=$(app_url) \
source=$(communication_id)
+ @$(MAKE) twilio-register \
+ endpoint=$(app_url)
+
@echo "🚀 Claim AI is running on $(app_url)"
- $(MAKE) logs name=$(name)
+ @$(MAKE) logs name=$(name)
destroy:
@echo "🧐 Are you sure you want to delete? Type 'delete now $(name)' to confirm."
@@ -179,20 +187,51 @@ logs-history:
--workspace $(log_analytics_workspace_customer_id)
eventgrid-register:
- @echo "⚙️ Deleting previous Event Grid webhook..."
- az eventgrid event-subscription delete --name $(event_subscription_name) || true
-
- @echo "⚙️ Registering Event Grid webhook..."
+ @$(MAKE) eventgrid-subscription-delete \
+ event_source=$(source) \
+ event_subscription_name=$(event_subscription_name)
+
+ @$(MAKE) eventgrid-subscription-create \
+ event_filter="data.to.PhoneNumber.Value" \
+ event_phone_number=$(bot_phone_number) \
+ event_source=$(source) \
+ event_subscription_name=$(event_subscription_name) \
+ event_types="Microsoft.Communication.IncomingCall"
+
+ @$(MAKE) eventgrid-subscription-delete \
+ event_source=$(source) \
+ event_subscription_name=$(event_subscription_name)-sms
+
+ @$(MAKE) eventgrid-subscription-create \
+ event_filter="data.to" \
+ event_phone_number=$(bot_phone_number) \
+ event_source=$(source) \
+ event_subscription_name=$(event_subscription_name)-sms \
+ event_types="Microsoft.Communication.SMSReceived"
+
+eventgrid-subscription-create:
+ @echo "⚙️ Registering Event Grid webhook $(event_subscription_name)..."
az eventgrid event-subscription create \
- --advanced-filter data.to.PhoneNumber.Value StringBeginsWith $(bot_phone_number) \
+ --advanced-filter $(event_filter) StringBeginsWith $(event_phone_number) \
--enable-advanced-filtering-on-arrays true \
--endpoint $(endpoint)/eventgrid/event \
--event-delivery-schema eventgridschema \
--event-ttl 3 \
- --included-event-types Microsoft.Communication.IncomingCall \
+ --included-event-types "$(event_types)" \
--max-delivery-attempts 8 \
--name $(event_subscription_name) \
- --source-resource-id $(source)
+ --source-resource-id $(event_source)
+
+eventgrid-subscription-delete:
+ @echo "⚙️ Deleting Event Grid webhook $(event_subscription_name)..."
+ az eventgrid event-subscription delete \
+ --name $(event_subscription_name) \
+ --source-resource-id $(event_source)
+
+twilio-register:
+ @echo "⚙️ Registering Twilio webhook..."
+ twilio phone-numbers:update $(twilio_phone_number) \
+ --sms-url $(endpoint)/twilio/sms
copy-resources:
@echo "📦 Copying resources to Azure storage account..."
diff --git a/README.md b/README.md
index 1a375ec..adb21d1 100644
--- a/README.md
+++ b/README.md
@@ -48,6 +48,7 @@ Extract of the data stored during the call:
- [x] Access the claim on a public website
- [x] Access to customer conversation history
- [x] Allow user to change the language of the conversation
+- [x] Assistant can send SMS to the user for futher information
- [x] Bot can be called from a phone number
- [x] Bot use multiple voice tones (e.g. happy, sad, neutral) to keep the conversation engaging
- [x] Company products (= lexicon) can be understood by the bot (e.g. a name of a specific insurance product)
@@ -61,6 +62,7 @@ Extract of the data stored during the call:
- [x] Help the user to find the information needed to complete the claim
- [x] Lower AI Search cost by usign a Redis cache
- [x] Monitoring and tracing with Application Insights
+- [x] Receive SMS during a conversation for explicit wordings
- [x] Responses are streamed from the LLM to the user, to avoid long pauses
- [x] Send a SMS report after the call
- [x] Take back a conversation after a disengagement
diff --git a/helpers/call_events.py b/helpers/call_events.py
index cf4b0cf..7a081fc 100644
--- a/helpers/call_events.py
+++ b/helpers/call_events.py
@@ -1,16 +1,13 @@
from azure.communication.callautomation import (
CallAutomationClient,
- CallConnectionClient,
DtmfTone,
RecognitionChoice,
- PhoneNumberIdentifier,
)
from helpers.config import CONFIG
from helpers.logging import build_logger, TRACER
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
- ResourceNotFoundError,
)
from models.synthesis import SynthesisModel
from models.call import CallStateModel
@@ -23,9 +20,11 @@ from models.message import (
)
from helpers.call_utils import (
ContextEnum as CallContextEnum,
+ handle_hangup,
handle_play,
handle_recognize_ivr,
handle_recognize_text,
+ handle_transfer,
)
from fastapi import BackgroundTasks
import asyncio
@@ -40,7 +39,10 @@ _db = CONFIG.database.instance()
@TRACER.start_as_current_span("on_new_call")
async def on_new_call(
- client: CallAutomationClient, context: str, phone_number: str, callback_url: str
+ callback_url: str,
+ client: CallAutomationClient,
+ context: str,
+ phone_number: str,
) -> bool:
_logger.debug(f"Incoming call handler caller ID: {phone_number}")
@@ -75,11 +77,10 @@ async def on_new_call(
@TRACER.start_as_current_span("on_call_connected")
async def on_call_connected(
call: CallStateModel,
- client: CallConnectionClient,
+ client: CallAutomationClient,
) -> None:
_logger.info("Call connected")
call.recognition_retry = 0 # Reset recognition retry counter
-
call.messages.append(
MessageModel(
action=MessageActionEnum.CALL,
@@ -87,7 +88,9 @@ async def on_call_connected(
persona=MessagePersonaEnum.HUMAN,
)
)
-
+ await _db.call_aset(
+ call
+ ) # Save ASAP in DB allowing SMS answers to be more "in-sync"
await _handle_ivr_language(
call=call, client=client
) # Every time a call is answered, confirm the language
@@ -97,7 +100,7 @@ async def on_call_connected(
async def on_call_disconnected(
background_tasks: BackgroundTasks,
call: CallStateModel,
- client: CallConnectionClient,
+ client: CallAutomationClient,
) -> None:
_logger.info("Call disconnected")
await _handle_hangup(background_tasks, client, call)
@@ -107,11 +110,14 @@ async def on_call_disconnected(
async def on_speech_recognized(
background_tasks: BackgroundTasks,
call: CallStateModel,
- client: CallConnectionClient,
+ client: CallAutomationClient,
text: str,
) -> None:
_logger.info(f"Voice recognition: {text}")
call.messages.append(MessageModel(content=text, persona=MessagePersonaEnum.HUMAN))
+ await _db.call_aset(
+ call
+ ) # Save ASAP in DB allowing SMS answers to be more "in-sync"
call = await load_llm_chat(
background_tasks=background_tasks,
call=call,
@@ -123,7 +129,7 @@ async def on_speech_recognized(
@TRACER.start_as_current_span("on_speech_timeout_error")
async def on_speech_timeout_error(
call: CallStateModel,
- client: CallConnectionClient,
+ client: CallAutomationClient,
) -> None:
if call.recognition_retry < 10:
await handle_recognize_text(
@@ -146,7 +152,7 @@ async def on_speech_timeout_error(
@TRACER.start_as_current_span("on_speech_unknown_error")
async def on_speech_unknown_error(
call: CallStateModel,
- client: CallConnectionClient,
+ client: CallAutomationClient,
error_code: int,
) -> None:
if error_code == 8511: # Failure while trying to play the prompt
@@ -167,7 +173,7 @@ async def on_speech_unknown_error(
async def on_play_completed(
background_tasks: BackgroundTasks,
call: CallStateModel,
- client: CallConnectionClient,
+ client: CallAutomationClient,
context: str,
) -> None:
_logger.debug("Play completed")
@@ -180,9 +186,10 @@ async def on_play_completed(
elif context == CallContextEnum.CONNECT_AGENT: # Call transfer
_logger.info("Initiating transfer call initiated")
- agent_caller = PhoneNumberIdentifier(str(CONFIG.workflow.agent_phone_number))
- client.transfer_call_to_participant(
- target_participant=agent_caller, # type: ignore
+ await handle_transfer(
+ call=call,
+ client=client,
+ target=CONFIG.workflow.agent_phone_number,
)
@@ -208,7 +215,7 @@ async def on_play_error(
@TRACER.start_as_current_span("on_ivr_recognized")
async def on_ivr_recognized(
- client: CallConnectionClient,
+ client: CallAutomationClient,
call: CallStateModel,
label: str,
background_tasks: BackgroundTasks,
@@ -258,7 +265,7 @@ async def on_transfer_completed() -> None:
@TRACER.start_as_current_span("on_transfer_error")
async def on_transfer_error(
call: CallStateModel,
- client: CallConnectionClient,
+ client: CallAutomationClient,
error_code: int,
) -> None:
_logger.info(f"Error during call transfer, subCode {error_code}")
@@ -270,22 +277,44 @@ async def on_transfer_error(
)
[email protected]_as_current_span("on_sms_received")
+async def on_sms_received(
+ background_tasks: BackgroundTasks,
+ call: CallStateModel,
+ client: CallAutomationClient,
+ message: str,
+) -> bool:
+ _logger.info(f"SMS received from {call.phone_number}: {message}")
+ call.messages.append(
+ MessageModel(
+ action=MessageActionEnum.SMS,
+ content=message,
+ persona=MessagePersonaEnum.HUMAN,
+ )
+ )
+ await _db.call_aset(
+ call
+ ) # Save ASAP in DB allowing SMS answers to be more "in-sync"
+ if not call.in_progress:
+ _logger.info("Call not in progress, answering with SMS")
+ else:
+ _logger.info("Call in progress, answering with voice")
+ await load_llm_chat(
+ background_tasks=background_tasks,
+ call=call,
+ client=client,
+ post_call_intelligence=_post_call_intelligence,
+ then_recognize=False,
+ )
+ return True
+
+
async def _handle_hangup(
background_tasks: BackgroundTasks,
- client: CallConnectionClient,
+ client: CallAutomationClient,
call: CallStateModel,
) -> None:
- _logger.debug("Hanging up call")
- try:
- client.hang_up(is_for_everyone=True)
- except ResourceNotFoundError:
- _logger.debug("Call already hung up")
- except HttpResponseError as e:
- if "call already terminated" in e.message.lower():
- _logger.debug("Call hung up before playing")
- else:
- raise e
-
+ await handle_hangup(client=client, call=call)
call.messages.append(
MessageModel(
content="",
@@ -293,7 +322,6 @@ async def _handle_hangup(
action=MessageActionEnum.HANGUP,
)
)
-
_post_call_intelligence(call, background_tasks)
@@ -347,7 +375,6 @@ async def _post_call_sms(call: CallStateModel) -> None:
success = True
if success:
- # Store the SMS in the call messages
call.messages.append(
MessageModel(
action=MessageActionEnum.SMS,
@@ -415,7 +442,7 @@ async def _post_call_next(call: CallStateModel) -> None:
async def _handle_ivr_language(
- client: CallConnectionClient,
+ client: CallAutomationClient,
call: CallStateModel,
) -> None:
tones = [
diff --git a/helpers/call_llm.py b/helpers/call_llm.py
index 4268f5d..cea8915 100644
--- a/helpers/call_llm.py
+++ b/helpers/call_llm.py
@@ -1,7 +1,5 @@
from typing import Awaitable, Callable, Optional, Tuple, Type
-from azure.communication.callautomation import (
- CallConnectionClient,
-)
+from azure.communication.callautomation import CallAutomationClient
from helpers.config import CONFIG
from helpers.logging import build_logger
from models.call import CallStateModel
@@ -117,8 +115,9 @@ def _llm_completion_system(
async def load_llm_chat(
background_tasks: BackgroundTasks,
call: CallStateModel,
- client: CallConnectionClient,
+ client: CallAutomationClient,
post_call_intelligence: Callable[[CallStateModel, BackgroundTasks], None],
+ then_recognize: bool = True,
_iterations_remaining: int = 3,
) -> CallStateModel:
"""
@@ -182,10 +181,12 @@ async def load_llm_chat(
# Clean up
soft_timeout_task.cancel()
hard_timeout_task.cancel()
- # Store updated chat model
- is_error, continue_chat, should_user_answer, call = chat_task.result()
- # Save in DB for new claims and allowing demos to be more "real-time"
- await _db.call_aset(call)
+ is_error, continue_chat, should_user_answer, call = (
+ chat_task.result()
+ ) # Store updated chat model
+ await _db.call_aset(
+ call
+ ) # Save ASAP in DB allowing SMS answers to be more "in-sync"
break
if hard_timeout_task.done(): # Break when hard timeout is reached
@@ -260,7 +261,7 @@ async def load_llm_chat(
_iterations_remaining=_iterations_remaining - 1,
)
- if should_user_answer:
+ if then_recognize and should_user_answer:
await handle_recognize_text(
call=call,
client=client,
@@ -272,7 +273,7 @@ async def load_llm_chat(
async def _execute_llm_chat(
background_tasks: BackgroundTasks,
call: CallStateModel,
- client: CallConnectionClient,
+ client: CallAutomationClient,
post_call_intelligence: Callable[[CallStateModel, BackgroundTasks], None],
use_tools: bool,
user_callback: Callable[[str, MessageStyleEnum], Awaitable],
diff --git a/helpers/call_utils.py b/helpers/call_utils.py
index f41a40e..ea9654f 100644
--- a/helpers/call_utils.py
+++ b/helpers/call_utils.py
@@ -1,16 +1,18 @@
+from contextlib import asynccontextmanager
from enum import Enum
from helpers.config import CONFIG
from helpers.logging import build_logger
from models.call import CallStateModel
from models.message import StyleEnum as MessageStyleEnum
-from typing import Generator, Optional
+from typing import AsyncGenerator, Generator, Optional
from azure.communication.callautomation import (
+ CallAutomationClient,
+ CallConnectionClient,
FileSource,
PhoneNumberIdentifier,
RecognitionChoice,
RecognizeInputType,
SsmlSource,
- CallConnectionClient,
)
from azure.core.exceptions import ResourceNotFoundError, HttpResponseError
from models.message import (
@@ -60,7 +62,7 @@ def tts_sentence_split(text: str, include_last: bool) -> Generator[str, None, No
# TODO: Disable or lower profanity filter. The filter seems enabled by default, it replaces words like "holes in my roof" by "*** in my roof". This is not acceptable for a call center.
async def _handle_recognize_media(
- client: CallConnectionClient,
+ client: CallAutomationClient,
call: CallStateModel,
sound_url: str,
) -> None:
@@ -69,13 +71,15 @@ async def _handle_recognize_media(
"""
_logger.debug(f"Recognizing media")
try:
- client.start_recognizing_media(
- end_silence_timeout=3, # Sometimes user includes breaks in their speech
- input_type=RecognizeInputType.SPEECH,
- play_prompt=FileSource(url=sound_url),
- speech_language=call.lang.short_code,
- target_participant=PhoneNumberIdentifier(call.phone_number), # type: ignore
- )
+ assert call.voice_id, "Voice ID is required for recognizing media"
+ async with _use_call_client(client, call.voice_id) as call_client:
+ call_client.start_recognizing_media(
+ end_silence_timeout=3, # Sometimes user includes breaks in their speech
+ input_type=RecognizeInputType.SPEECH,
+ play_prompt=FileSource(url=sound_url),
+ speech_language=call.lang.short_code,
+ target_participant=PhoneNumberIdentifier(call.phone_number), # type: ignore
+ )
except ResourceNotFoundError:
_logger.debug(f"Call hung up before recognizing")
except HttpResponseError as e:
@@ -86,7 +90,7 @@ async def _handle_recognize_media(
async def handle_media(
- client: CallConnectionClient,
+ client: CallAutomationClient,
call: CallStateModel,
sound_url: str,
context: Optional[str] = None,
@@ -97,10 +101,12 @@ async def handle_media(
If `context` is provided, it will be used to track the operation.
"""
try:
- client.play_media(
- operation_context=context,
- play_source=FileSource(url=sound_url),
- )
+ assert call.voice_id, "Voice ID is required for recognizing media"
+ async with _use_call_client(client, call.voice_id) as call_client:
+ call_client.play_media(
+ operation_context=context,
+ play_source=FileSource(url=sound_url),
+ )
except ResourceNotFoundError:
_logger.debug(f"Call hung up before playing")
except HttpResponseError as e:
@@ -111,7 +117,7 @@ async def handle_media(
async def handle_recognize_text(
- client: CallConnectionClient,
+ client: CallAutomationClient,
call: CallStateModel,
style: MessageStyleEnum = MessageStyleEnum.NONE,
text: Optional[str] = None,
@@ -139,7 +145,7 @@ async def handle_recognize_text(
async def handle_play(
- client: CallConnectionClient,
+ client: CallAutomationClient,
call: CallStateModel,
text: str,
style: MessageStyleEnum = MessageStyleEnum.NONE,
@@ -184,12 +190,14 @@ async def handle_play(
# Play each chunk
try:
- for chunk in chunks:
- _logger.info(f"Playing text: {text} ({style})")
- client.play_media(
- operation_context=context,
- play_source=_audio_from_text(chunk, style, call),
- )
+ assert call.voice_id, "Voice ID is required for recognizing media"
+ async with _use_call_client(client, call.voice_id) as call_client:
+ for chunk in chunks:
+ _logger.info(f"Playing text: {text} ({style})")
+ call_client.play_media(
+ operation_context=context,
+ play_source=_audio_from_text(chunk, style, call),
+ )
except ResourceNotFoundError:
_logger.debug(f"Call hung up before playing")
except HttpResponseError as e:
@@ -227,7 +235,7 @@ def _audio_from_text(
async def handle_recognize_ivr(
- client: CallConnectionClient,
+ client: CallAutomationClient,
call: CallStateModel,
text: str,
choices: list[RecognitionChoice],
@@ -240,14 +248,64 @@ async def handle_recognize_ivr(
_logger.info(f"Playing text before IVR: {text}")
_logger.debug(f"Recognizing IVR")
try:
- client.start_recognizing_media(
- choices=choices,
- end_silence_timeout=20,
- input_type=RecognizeInputType.CHOICES,
- 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
- )
+ assert call.voice_id, "Voice ID is required for recognizing media"
+ async with _use_call_client(client, call.voice_id) as call_client:
+ call_client.start_recognizing_media(
+ choices=choices,
+ end_silence_timeout=20,
+ input_type=RecognizeInputType.CHOICES,
+ 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
+ )
except ResourceNotFoundError:
_logger.debug(f"Call hung up before recognizing")
+
+
+async def handle_hangup(
+ client: CallAutomationClient,
+ call: CallStateModel,
+) -> None:
+ _logger.debug("Hanging up call")
+ try:
+ assert call.voice_id, "Voice ID is required for recognizing media"
+ async with _use_call_client(client, call.voice_id) as call_client:
+ call_client.hang_up(is_for_everyone=True)
+ except ResourceNotFoundError:
+ _logger.debug("Call already hung up")
+ except HttpResponseError as e:
+ if "call already terminated" in e.message.lower():
+ _logger.debug("Call hung up before playing")
+ else:
+ raise e
+
+
+async def handle_transfer(
+ client: CallAutomationClient,
+ call: CallStateModel,
+ target: str,
+ context: Optional[str] = None,
+) -> None:
+ _logger.debug(f"Transferring call to {target}")
+ try:
+ assert call.voice_id, "Voice ID is required for recognizing media"
+ async with _use_call_client(client, call.voice_id) as call_client:
+ call_client.transfer_call_to_participant(
+ operation_context=context,
+ target_participant=PhoneNumberIdentifier(target),
+ )
+ except ResourceNotFoundError:
+ _logger.debug(f"Call hung up before transferring")
+ except HttpResponseError as e:
+ if "call already terminated" in e.message.lower():
+ _logger.debug(f"Call hung up before transferring")
+ else:
+ raise e
+
+
+@asynccontextmanager
+async def _use_call_client(
+ client: CallAutomationClient, voice_id: str
+) -> AsyncGenerator[CallConnectionClient, None]:
+ yield client.get_call_connection(call_connection_id=voice_id)
diff --git a/helpers/config_models/prompts.py b/helpers/config_models/prompts.py
index 09cda24..fff1428 100644
--- a/helpers/config_models/prompts.py
+++ b/helpers/config_models/prompts.py
@@ -55,9 +55,10 @@ class LlmModel(BaseModel):
- Answers in {default_lang}, even if the customer speaks another language
- Aways answer with at least one full sentence
- Be proactive in the reminders you create, customer assistance is your priority
+ - Customer can send SMS in addition to the call, answers will be made by phone
- Do not ask for something which is already stored in the claim
- Do not ask the customer more than 2 questions in a row
- - Don't have access to any other means of communication with the customer (e.g., email, SMS, chat, web portal), only the phone call
+ - Don't have access to any other means of communication (e.g., email, web portal), only the phone (now) and SMS (during the call)
- Each message from the history is prefixed from where it has been said ({actions})
- If user calls multiple times, continue the discussion from the previous call
- If you don't know how to answer, say "I don't know"
@@ -67,7 +68,9 @@ class LlmModel(BaseModel):
- Keep the sentences short and simple
- Messages from the customer are generated with a speech-to-text tool, so they may contain errors, do your best to understand them
- Only use bullet points and numbered lists as formatting, never use other Markdown syntax
+ - Reception of SMS can be out of order, do your best to understand them
- Rephrase the customer's questions as statements and answer them
+ - SMS can contain additional information or clarifications, use them
- Update the claim as soon as possible with the information gathered
- Use styles as often as possible, to add emotions to the conversation
- Use trusted data to answer the customer's questions
@@ -128,6 +131,12 @@ class LlmModel(BaseModel):
## Example 5
User: action=call
Assistant: style=none Hello, we talked yesterday about the car accident you had in Paris. We planned an appointment with the garage for tomorrow. What can I do for you today?
+
+ ## Example 6
+ User: action=talk I had an accident this morning, I was shopping. Let me send the exact location by SMS.
+ User: action=sms At the corner of Rue de la Paix and Rue de Rivoli.
+ Tools: update incident location
+ Assistant: style=sad I understand you had an accident this morning while shopping. style=none I have updated your file with the location you sent me by SMS.
"""
sms_summary_system_tpl: str = """
# Objective
@@ -490,6 +499,8 @@ class TtsModel(BaseModel):
- "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?
"""
timeout_silence_tpl: str = (
diff --git a/helpers/llm_tools.py b/helpers/llm_tools.py
index 1c79761..406d1f8 100644
--- a/helpers/llm_tools.py
+++ b/helpers/llm_tools.py
@@ -1,4 +1,4 @@
-from azure.communication.callautomation import CallConnectionClient
+from azure.communication.callautomation import CallAutomationClient
from helpers.call_utils import ContextEnum as CallContextEnum, handle_play
from helpers.config import CONFIG
from helpers.llm_utils import function_schema
@@ -6,7 +6,12 @@ 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 StyleEnum as MessageStyleEnum
+from models.message import (
+ ActionEnum as MessageActionEnum,
+ MessageModel,
+ PersonaEnum as MessagePersonaEnum,
+ StyleEnum as MessageStyleEnum,
+)
from models.reminder import ReminderModel
from openai.types.chat import ChatCompletionToolParam
from pydantic import ValidationError
@@ -16,6 +21,7 @@ import asyncio
_logger = build_logger(__name__)
_search = CONFIG.ai_search.instance()
+_sms = CONFIG.sms.instance()
class UpdateClaimDict(TypedDict):
@@ -26,7 +32,7 @@ class UpdateClaimDict(TypedDict):
class LlmPlugins:
call: CallStateModel
cancellation_callback: Callable[[], Awaitable]
- client: CallConnectionClient
+ client: CallAutomationClient
post_call_intelligence: Callable[[CallStateModel], None]
style: MessageStyleEnum = MessageStyleEnum.NONE
user_callback: Callable[[str, MessageStyleEnum], Awaitable]
@@ -35,7 +41,7 @@ class LlmPlugins:
self,
call: CallStateModel,
cancellation_callback: Callable[[], Awaitable],
- client: CallConnectionClient,
+ client: CallAutomationClient,
post_call_intelligence: Callable[[CallStateModel], None],
user_callback: Callable[[str, MessageStyleEnum], Awaitable],
):
@@ -325,6 +331,41 @@ class LlmPlugins:
)
return f"Notifying {service} for {reason}."
+ async def send_sms(
+ self,
+ customer_response: Annotated[
+ str,
+ "Phrase used to confirm the action. This phrase will be spoken to the user. Describe what you're doing in one sentence. Example: 'I am sending a SMS to your phone number.', 'SMS with the details is sent.'.",
+ ],
+ message: Annotated[
+ str,
+ "The message to send to the customer.",
+ ],
+ ) -> str:
+ """
+ Use when there is a real need to send a SMS to the customer.
+
+ # Usage examples
+ - Ask a question, if the call quality is bad
+ - Confirm a detail like a reference number, if there is a misunderstanding
+ - Send a confirmation, if the customer wants to have a written proof
+ """
+ await self.user_callback(customer_response, self.style)
+ success = await _sms.asend(
+ content=message,
+ phone_number=self.call.phone_number,
+ )
+ if not success:
+ return "Failed to send SMS"
+ self.call.messages.append(
+ MessageModel(
+ action=MessageActionEnum.SMS,
+ content=message,
+ persona=MessagePersonaEnum.ASSISTANT,
+ )
+ )
+ return "SMS sent"
+
@staticmethod
async def to_openai(call: CallStateModel) -> list[ChatCompletionToolParam]:
return await asyncio.gather(
diff --git a/main.py b/main.py
index dfe4643..f1e485d 100644
--- a/main.py
+++ b/main.py
@@ -21,7 +21,15 @@ from azure.communication.callautomation import (
from azure.core.credentials import AzureKeyCredential
from azure.core.messaging import CloudEvent
from azure.eventgrid import EventGridEvent, SystemEventNames
-from fastapi import FastAPI, status, Request, HTTPException, BackgroundTasks, Response
+from fastapi import (
+ BackgroundTasks,
+ FastAPI,
+ Form,
+ HTTPException,
+ Request,
+ Response,
+ status,
+)
from fastapi.responses import JSONResponse, HTMLResponse
from jinja2 import Environment, FileSystemLoader
from models.call import CallStateModel, CallGetModel
@@ -31,6 +39,7 @@ import asyncio
from uuid import UUID
import mistune
from helpers.pydantic_types.phone_numbers import PhoneNumber
+from twilio.twiml.messaging_response import MessagingResponse
from helpers.call_events import (
on_call_connected,
on_call_disconnected,
@@ -38,6 +47,7 @@ from helpers.call_events import (
on_new_call,
on_play_completed,
on_play_error,
+ on_sms_received,
on_speech_recognized,
on_speech_timeout_error,
on_speech_unknown_error,
@@ -63,7 +73,7 @@ _jinja.filters["markdown"] = lambda x: mistune.create_markdown(plugins=["abbr",
_source_caller = PhoneNumberIdentifier(CONFIG.communication_service.phone_number)
_logger.info(f"Using phone number {str(CONFIG.communication_service.phone_number)}")
# Cannot place calls with RBAC, need to use access key (see: https://learn.microsoft.com/en-us/azure/communication-services/concepts/authentication#authentication-options)
-_call_client = CallAutomationClient(
+_automation_client = CallAutomationClient(
endpoint=CONFIG.communication_service.endpoint,
credential=AzureKeyCredential(
CONFIG.communication_service.access_key.get_secret_value()
@@ -231,7 +241,7 @@ async def call_get(call_id: UUID) -> CallGetModel:
)
async def call_post(phone_number: PhoneNumber) -> CallGetModel:
url, call = await _communicationservices_event_url(phone_number)
- call_connection_properties = _call_client.create_call(
+ call_connection_properties = _automation_client.create_call(
callback_url=url,
cognitive_services_endpoint=CONFIG.cognitive_service.endpoint,
source_caller_id_number=_source_caller,
@@ -249,9 +259,18 @@ async def call_post(phone_number: PhoneNumber) -> CallGetModel:
description="Handle incoming call from a Azure Event Grid event originating from Azure Communication Services.",
name="Receive Event Grid event",
)
-async def eventgrid_event_post(request: Request) -> Response:
+async def eventgrid_event_post(
+ background_tasks: BackgroundTasks,
+ request: Request,
+) -> Response:
responses = await asyncio.gather(
- *[_eventgrid_event_worker(event_dict) for event_dict in await request.json()]
+ *[
+ _eventgrid_event_worker(
+ background_tasks=background_tasks,
+ event_dict=event_dict,
+ )
+ for event_dict in await request.json()
+ ]
)
for response in responses:
if response:
@@ -260,7 +279,8 @@ async def eventgrid_event_post(request: Request) -> Response:
async def _eventgrid_event_worker(
- event_dict: dict[str, Any]
+ background_tasks: BackgroundTasks,
+ event_dict: dict[str, Any],
) -> Optional[Union[JSONResponse, Response]]:
event = EventGridEvent.from_dict(event_dict)
event_type = event.event_type
@@ -277,24 +297,39 @@ async def _eventgrid_event_worker(
elif event_type == SystemEventNames.AcsIncomingCallEventName:
call_context: str = event.data["incomingCallContext"]
- if event.data["from"]["kind"] == "phoneNumber":
- phone_number = event.data["from"]["phoneNumber"]["value"]
- else:
- phone_number = event.data["from"]["rawId"]
+ phone_number = event.data["from"]["phoneNumber"]["value"]
phone_number = PhoneNumber(phone_number)
url, _ = await _communicationservices_event_url(phone_number)
event_status = await on_new_call(
callback_url=url,
- client=_call_client,
+ client=_automation_client,
context=call_context,
phone_number=phone_number,
)
+ if not event_status:
+ return Response(
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ )
+ elif event_type == SystemEventNames.AcsSmsReceivedEventName:
+ message: str = event.data["message"]
+ phone_number: str = event.data["from"]
+ call = await _db.call_asearch_one(phone_number)
+ if not call:
+ _logger.warning(f"Call for phone number {phone_number} not found")
+ return Response(
+ status_code=status.HTTP_404_NOT_FOUND,
+ )
+ event_status = await on_sms_received(
+ background_tasks=background_tasks,
+ call=call,
+ client=_automation_client,
+ message=message,
+ )
if not event_status:
return Response(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
)
- return None
@api.post(
@@ -336,9 +371,12 @@ async def _communicationservices_event_worker(
event = CloudEvent.from_dict(event_dict)
assert isinstance(event.data, dict)
+ # Store connection ID
connection_id = event.data["callConnectionId"]
+ call.voice_id = connection_id
+
+ # Extract event context
operation_context = event.data.get("operationContext", None)
- client = _call_client.get_call_connection(call_connection_id=connection_id)
event_type = event.type
_logger.debug(f"Call event received {event_type} for call {call}")
@@ -347,14 +385,14 @@ async def _communicationservices_event_worker(
if event_type == "Microsoft.Communication.CallConnected": # Call answered
await on_call_connected(
call=call,
- client=client,
+ client=_automation_client,
)
elif event_type == "Microsoft.Communication.CallDisconnected": # Call hung up
await on_call_disconnected(
background_tasks=background_tasks,
call=call,
- client=client,
+ client=_automation_client,
)
elif (
@@ -367,7 +405,7 @@ async def _communicationservices_event_worker(
await on_speech_recognized(
background_tasks=background_tasks,
call=call,
- client=client,
+ client=_automation_client,
text=speech_text,
)
@@ -376,7 +414,7 @@ async def _communicationservices_event_worker(
await on_ivr_recognized(
background_tasks=background_tasks,
call=call,
- client=client,
+ client=_automation_client,
label=label_detected,
)
@@ -393,12 +431,12 @@ async def _communicationservices_event_worker(
if error_code in (8510, 8532): # Timeout retry
await on_speech_timeout_error(
call=call,
- client=client,
+ client=_automation_client,
)
else: # Unknown error
await on_speech_unknown_error(
call=call,
- client=client,
+ client=_automation_client,
error_code=error_code,
)
@@ -406,7 +444,7 @@ async def _communicationservices_event_worker(
await on_play_completed(
background_tasks=background_tasks,
call=call,
- client=client,
+ client=_automation_client,
context=operation_context,
)
@@ -427,7 +465,7 @@ async def _communicationservices_event_worker(
sub_code: int = result_information["subCode"]
await on_transfer_error(
call=call,
- client=client,
+ client=_automation_client,
error_code=sub_code,
)
@@ -453,3 +491,49 @@ async def _communicationservices_event_url(
call_id=str(call.call_id),
)
return url, call
+
+
+# TODO: Secure this endpoint with a secret, either in the Authorization header or in the URL
+ "/twilio/sms",
+ description="Handle incoming SMS event from Twilio.",
+ name="Receive Twilio SMS event",
+ responses={
+ status.HTTP_200_OK: {
+ "content": {
+ "application/xml": {
+ "example": str(MessagingResponse()),
+ },
+ },
+ },
+ },
+)
+async def twilio_sms(
+ background_tasks: BackgroundTasks,
+ Body: str = Form(alias="Body"),
+ From: str = Form(alias="From"),
+) -> Response:
+ """
+ Handle incoming SMS event from Twilio.
+ """
+ phone_number = PhoneNumber(From)
+ call = await _db.call_asearch_one(phone_number)
+ if not call:
+ _logger.warning(f"Call for phone number {phone_number} not found")
+ else:
+ event_status = await on_sms_received(
+ call=call,
+ message=Body,
+ client=_automation_client,
+ background_tasks=background_tasks,
+ )
+ if not event_status:
+ return Response(
+ background=background_tasks,
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ )
+ return Response(
+ background=background_tasks,
+ content=str(MessagingResponse()), # Twilio expects an empty response everytime
+ media_type="application/xml",
+ )
diff --git a/models/call.py b/models/call.py
index a4e97ad..b14524b 100644
--- a/models/call.py
+++ b/models/call.py
@@ -2,7 +2,7 @@ from datetime import datetime, UTC, tzinfo
from helpers.config_models.workflow import LanguageEntryModel
from helpers.pydantic_types.phone_numbers import PhoneNumber
from models.claim import ClaimModel
-from models.message import MessageModel
+from models.message import MessageModel, ActionEnum as MessageActionEnum
from models.next import NextModel
from models.reminder import ReminderModel
from models.synthesis import SynthesisModel
@@ -27,6 +27,27 @@ class CallGetModel(BaseModel):
recognition_retry: int = Field(default=0)
reminders: list[ReminderModel] = []
synthesis: Optional[SynthesisModel] = None
+ voice_id: Optional[str] = None
+
+ @computed_field
+ @property
+ def in_progress(self) -> bool:
+ """
+ Check if the call is in progress.
+
+ The call is in progress if the most recent message action status (CALL or HANGUP) is CALL. Otherwise, it is not in progress.
+ """
+ # Reverse
+ inverted_messages = self.messages.copy()
+ inverted_messages.reverse()
+ # Search for the first action we want
+ for message in inverted_messages:
+ if message.action == MessageActionEnum.CALL:
+ return True
+ elif message.action == MessageActionEnum.HANGUP:
+ return False
+ # Otherwise, we assume the call is completed
+ return False
def tz(self) -> tzinfo:
return PhoneNumber.tz(self.phone_number)
diff --git a/public_website/single.html.jinja b/public_website/single.html.jinja
index 44ac4a4..4efdebb 100644
--- a/public_website/single.html.jinja
+++ b/public_website/single.html.jinja
@@ -68,7 +68,7 @@ Claim {{ call.claim.claim_id }} ({{ call.phone_number }})
{% elif message.action == 'hangup' %}
hung up
{% elif message.action == 'sms' %}
- sent a text
+ sent a SMS
{% elif message.action == 'talk' %}
said
{% endif %}