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: Add Twilio as an optional SMS backend

Clémence Lesné2ae85595a0f1
diff --git a/README.md b/README.md
index 0d702cc..237dabe 100644
--- a/README.md
+++ b/README.md
@@ -223,6 +223,8 @@ workflow:
communication_service:
phone_number: "+33612345678"
+sms: {}
+
prompts:
llm: {}
tts: {}
@@ -493,3 +495,26 @@ class ClaimModel(BaseModel):
# Built-in functions
[...]
+```
+
+### Use Twilio for SMS
+
+To use Twilio for SMS, you need to create an account and get the following information:
+
+- Account SID
+- Auth Token
+- Phone number
+
+Then, add the following in the `config.yaml` file:
+
+```yaml
+# config.yaml
+[...]
+
+sms:
+ mode: twilio
+ twilio:
+ account_sid: xxx
+ auth_token: xxx
+ phone_number: "+33612345678"
+```
diff --git a/bicep/app.bicep b/bicep/app.bicep
index 45318cf..1d64401 100644
--- a/bicep/app.bicep
+++ b/bicep/app.bicep
@@ -54,6 +54,7 @@ var config = {
endpoint: communication.properties.hostName
phone_number: botPhoneNumber
}
+ sms: loadYamlContent('../config.yaml').sms
cognitive_service: {
endpoint: cognitiveCommunication.properties.endpoint
}
diff --git a/helpers/call_events.py b/helpers/call_events.py
index 5ffe0cf..234fc98 100644
--- a/helpers/call_events.py
+++ b/helpers/call_events.py
@@ -27,16 +27,12 @@ from helpers.call_utils import (
)
from fastapi import BackgroundTasks
import asyncio
-from azure.communication.sms import SmsClient
from models.next import NextModel
from helpers.call_llm import llm_completion, llm_model, load_llm_chat
_logger = build_logger(__name__)
-_sms_client = SmsClient(
- credential=CONFIG.communication_service.access_key.get_secret_value(),
- endpoint=CONFIG.communication_service.endpoint,
-)
+_sms = CONFIG.sms.instance()
_db = CONFIG.database.instance()
@@ -320,37 +316,21 @@ async def _post_call_sms(call: CallModel) -> None:
return
_logger.info(f"SMS report: {content}")
- try:
- responses = _sms_client.send(
- from_=str(CONFIG.communication_service.phone_number),
- message=content,
- to=call.phone_number,
- )
- response = responses[0]
-
- if response.successful:
- _logger.debug(f"SMS report sent {response.message_id} to {response.to}")
- call.messages.append(
- MessageModel(
- action=MessageActionEnum.SMS,
- content=content,
- persona=MessagePersonaEnum.ASSISTANT,
- )
- )
- await _db.call_aset(call)
- else:
- _logger.warning(
- f"Failed SMS to {response.to}, status {response.http_status_code}, error {response.error_message}"
- )
+ success = await _sms.asend(content, call.phone_number)
- except ClientAuthenticationError:
- _logger.error(
- "Authentication error for SMS, check the credentials", exc_info=True
+ if not success:
+ _logger.warning("Failed sending SMS report")
+ return
+
+ # Store the SMS in the call messages
+ call.messages.append(
+ MessageModel(
+ action=MessageActionEnum.SMS,
+ content=content,
+ persona=MessagePersonaEnum.ASSISTANT,
)
- except HttpResponseError as e:
- _logger.error(f"Error sending SMS: {e}")
- except Exception:
- _logger.warning(f"Failed SMS to {call.phone_number}", exc_info=True)
+ )
+ await _db.call_aset(call)
async def _post_call_synthesis(call: CallModel) -> None:
diff --git a/helpers/config_models/prompts.py b/helpers/config_models/prompts.py
index 0a84eb4..d9d8116 100644
--- a/helpers/config_models/prompts.py
+++ b/helpers/config_models/prompts.py
@@ -154,6 +154,18 @@ class LlmModel(BaseModel):
# Conversation history
{messages}
+
+ # Response format
+ Hello, I understand [customer's situation]. I confirm [next steps]. [Salutation]. {bot_name} from {bot_company}.
+
+ ## Example 1
+ Hello, I understand you had a car accident in Paris yesterday. I confirm the appointment with the garage is planned for tomorrow. Have a nice day! {bot_name} from {bot_company}.
+
+ ## Example 2
+ Hello, I understand your roof has holes since yesterday's big storm. I confirm the appointment with the roofer is planned for tomorrow. Best wishes for recovery! {bot_name} from {bot_company}.
+
+ ## Example 3
+ Hello, I had difficulties to hear you. If you need help, let me know how I can help you. Have a nice day! {bot_name} from {bot_company}.
"""
synthesis_short_system_tpl: str = """
# Objective
@@ -345,8 +357,12 @@ class LlmModel(BaseModel):
)
def sms_summary_system(self, call: CallModel) -> 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(),
default_lang=call.lang.human_name,
messages=TypeAdapter(list[MessageModel]).dump_json(call.messages).decode(),
diff --git a/helpers/config_models/root.py b/helpers/config_models/root.py
index 549801a..24bbc76 100644
--- a/helpers/config_models/root.py
+++ b/helpers/config_models/root.py
@@ -10,6 +10,7 @@ from helpers.config_models.llm import LlmModel
from helpers.config_models.monitoring import MonitoringModel
from helpers.config_models.prompts import PromptsModel
from helpers.config_models.resources import ResourcesModel
+from helpers.config_models.sms import SmsModel
from helpers.config_models.workflow import WorkflowModel
from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict
@@ -38,4 +39,5 @@ class RootModel(BaseSettings):
monitoring: MonitoringModel
prompts: PromptsModel = PromptsModel() # Object is fully defined by default
resources: ResourcesModel
+ sms: SmsModel = SmsModel() # Object is fully defined by default
workflow: WorkflowModel
diff --git a/helpers/config_models/sms.py b/helpers/config_models/sms.py
new file mode 100644
index 0000000..5da78eb
--- /dev/null
+++ b/helpers/config_models/sms.py
@@ -0,0 +1,78 @@
+from enum import Enum
+from functools import cache
+from helpers.pydantic_types.phone_numbers import PhoneNumber
+from persistence.isms import ISms
+from persistence.istore import IStore
+from pydantic import field_validator, SecretStr, Field, BaseModel, ValidationInfo
+from typing import Optional
+
+
+class ModeEnum(str, Enum):
+ COMMUNICATION_SERVICES = "communication_services"
+ TWILIO = "twilio"
+
+
+class CommunicationServiceModel(BaseModel, frozen=True):
+ """
+ Represents the configuration for the Communication Services API.
+
+ Model is purely empty to fit to the `ISms` interface and the "mode" enum code organization. As the Communication Services is also used as the only call interface, it is not necessary to duplicate the models.
+ """
+
+ @cache
+ def instance(self) -> ISms:
+ from persistence.communication_services import CommunicationServicesSms
+ from helpers.config import CONFIG
+
+ return CommunicationServicesSms(CONFIG.communication_service)
+
+
+class TwilioModel(BaseModel, frozen=True):
+ account_sid: str
+ auth_token: SecretStr
+ phone_number: PhoneNumber
+
+ @cache
+ def instance(self) -> ISms:
+ from persistence.twilio import TwilioSms
+
+ return TwilioSms(self)
+
+
+class SmsModel(BaseModel):
+ communication_services: Optional[CommunicationServiceModel] = (
+ CommunicationServiceModel()
+ ) # Object is fully defined by default
+ mode: ModeEnum = ModeEnum.COMMUNICATION_SERVICES
+ twilio: Optional[TwilioModel] = None
+
+ @field_validator("communication_services")
+ def validate_communication_services(
+ cls,
+ communication_services: Optional[CommunicationServiceModel],
+ info: ValidationInfo,
+ ) -> Optional[CommunicationServiceModel]:
+ if (
+ not communication_services
+ and info.data.get("mode", None) == ModeEnum.COMMUNICATION_SERVICES
+ ):
+ raise ValueError("Communication Services config required")
+ return communication_services
+
+ @field_validator("twilio")
+ def validate_twilio(
+ cls,
+ twilio: Optional[TwilioModel],
+ info: ValidationInfo,
+ ) -> Optional[TwilioModel]:
+ if not twilio and info.data.get("mode", None) == ModeEnum.TWILIO:
+ raise ValueError("Twilio config required")
+ return twilio
+
+ def instance(self) -> ISms:
+ if self.mode == ModeEnum.COMMUNICATION_SERVICES:
+ assert self.communication_services
+ return self.communication_services.instance()
+
+ assert self.twilio
+ return self.twilio.instance()
diff --git a/persistence/communication_services.py b/persistence/communication_services.py
new file mode 100644
index 0000000..8f853e7
--- /dev/null
+++ b/persistence/communication_services.py
@@ -0,0 +1,61 @@
+from azure.communication.sms import SmsSendResult
+from azure.communication.sms.aio import SmsClient
+from azure.core.exceptions import ClientAuthenticationError, HttpResponseError
+from contextlib import asynccontextmanager
+from helpers.config_models.communication_service import CommunicationServiceModel
+from helpers.logging import build_logger
+from helpers.pydantic_types.phone_numbers import PhoneNumber
+from persistence.isms import ISms
+from typing import AsyncGenerator
+
+
+_logger = build_logger(__name__)
+
+
+class CommunicationServicesSms(ISms):
+ _config: CommunicationServiceModel
+
+ def __init__(self, config: CommunicationServiceModel):
+ _logger.info(f"Using Communication Services from number {config.phone_number}")
+ self._config = config
+
+ async def asend(self, content: str, phone_number: PhoneNumber) -> bool:
+ _logger.info(f"Sending SMS to {phone_number}")
+ success = False
+ _logger.info(f"SMS content: {content}")
+ try:
+ async with self._use_client() as client:
+ responses: list[SmsSendResult] = await client.send(
+ from_=str(self._config.phone_number),
+ message=content,
+ to=str(phone_number),
+ )
+ response = responses[0]
+ if response.successful:
+ _logger.debug(f"SMS sent {response.message_id} to {response.to}")
+ success = True
+ else:
+ _logger.warning(
+ f"Failed SMS to {response.to}, status {response.http_status_code}, error {response.error_message}"
+ )
+ except ClientAuthenticationError:
+ _logger.error(
+ "Authentication error for SMS, check the credentials", exc_info=True
+ )
+ except HttpResponseError as e:
+ _logger.error(f"Error sending SMS: {e}")
+ except Exception:
+ _logger.warning(f"Failed SMS to {phone_number}", exc_info=True)
+ return success
+
+ @asynccontextmanager
+ async def _use_client(self) -> AsyncGenerator[SmsClient, None]:
+ client = SmsClient(
+ credential=self._config.access_key.get_secret_value(),
+ endpoint=self._config.endpoint,
+ )
+
+ try:
+ yield client
+ finally:
+ await client.close()
diff --git a/persistence/isms.py b/persistence/isms.py
new file mode 100644
index 0000000..c9d26ca
--- /dev/null
+++ b/persistence/isms.py
@@ -0,0 +1,8 @@
+from abc import ABC, abstractmethod
+from helpers.pydantic_types.phone_numbers import PhoneNumber
+
+
+class ISms(ABC):
+ @abstractmethod
+ async def asend(self, content: str, phone_number: PhoneNumber) -> bool:
+ pass
diff --git a/persistence/twilio.py b/persistence/twilio.py
new file mode 100644
index 0000000..20e31f8
--- /dev/null
+++ b/persistence/twilio.py
@@ -0,0 +1,48 @@
+from helpers.config_models.sms import TwilioModel
+from helpers.logging import build_logger
+from helpers.pydantic_types.phone_numbers import PhoneNumber
+from persistence.isms import ISms
+from twilio.base.exceptions import TwilioRestException
+from twilio.http.async_http_client import AsyncTwilioHttpClient
+from twilio.rest import Client
+
+
+_logger = build_logger(__name__)
+
+
+class TwilioSms(ISms):
+ _client: Client
+ _config: TwilioModel
+
+ def __init__(self, config: TwilioModel):
+ _logger.info(f"Using Twilio from number {config.phone_number}")
+ self._config = config
+ self._client = Client(
+ http_client=AsyncTwilioHttpClient(),
+ password=config.auth_token.get_secret_value(),
+ username=config.account_sid,
+ )
+
+ async def asend(self, content: str, phone_number: PhoneNumber) -> bool:
+ _logger.info(f"Sending SMS to {phone_number}")
+ success = False
+ _logger.info(f"SMS content: {content}")
+ try:
+ res = await self._client.messages.create_async(
+ body=content,
+ from_=str(self._config.phone_number),
+ to=str(phone_number),
+ )
+ # TODO: How to check the delivery status? Seems present in "res.status" but not documented
+ if res.error_message:
+ _logger.warning(
+ f"Failed SMS to {phone_number}, status {res.error_code}, error {res.error_message}"
+ )
+ else:
+ _logger.debug(f"SMS sent to {phone_number}")
+ success = True
+ except TwilioRestException as e:
+ _logger.error(f"Error sending SMS: {e}")
+ except Exception:
+ _logger.warning(f"Failed SMS to {phone_number}", exc_info=True)
+ return success
diff --git a/requirements.txt b/requirements.txt
index 9b3e1fa..971ad4a 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -30,5 +30,6 @@ pyyaml==6.0.1
redis==5.0.3
tenacity==8.2.3
tiktoken==0.6.0
+twilio==9.0.5
typing-extensions==4.11.0
uvicorn[standard]==0.28.0