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: Record calls automatically

Clémence Lesnéb2ec860df122
diff --git a/README.md b/README.md
index 1a572b1..e7f9d38 100644
--- a/README.md
+++ b/README.md
@@ -298,6 +298,7 @@ conversation:
communication_services:
# Phone number purshased from Communication Services
phone_number: "+33612345678"
+ recording_enabled: false
sms: {}
@@ -366,6 +367,7 @@ communication_services:
endpoint: https://xxx.france.communication.azure.com
phone_number: "+33612345678"
post_queue_name: post-33612345678
+ recording_enabled: false
resource_id: xxx
sms_queue_name: sms-33612345678
@@ -457,6 +459,22 @@ make dev
## Advanced usage
+## Enable call recording
+
+Call recording is disabled by default. To enable it:
+
+1. Create a new container in the Azure Storage account (i.e. `recordings`), it is already done if you deployed the solution on Azure
+2. Update the configuration
+
+Configuration is the following:
+
+```yaml
+# config.yaml
+communication_services:
+ recording_container_url: https://xxx.blob.core.windows.net/recordings # Only needed for local deployment
+ recording_enabled: true
+```
+
### Add my custom training data with AI Search
Training data is stored on AI Search to be retrieved by the bot, on demand.
diff --git a/bicep/app.bicep b/bicep/app.bicep
index fc9d63d..6e348df 100644
--- a/bicep/app.bicep
+++ b/bicep/app.bicep
@@ -59,6 +59,8 @@ var config = {
endpoint: communicationServices.properties.hostName
phone_number: localConfig.communication_services.phone_number
post_queue_name: postQueue.name
+ recording_container_url: '${storageAccount.properties.primaryEndpoints.blob}${recordingsBlob.name}'
+ recording_enabled: localConfig.communication_services.recording_enabled
resource_id: communicationServices.properties.immutableResourceId
sms_queue_name: smsQueue.name
trainings_queue_name: trainingsQueue.name
@@ -273,6 +275,11 @@ resource publicBlob 'Microsoft.Storage/storageAccounts/blobServices/containers@2
name: '$web'
}
+resource recordingsBlob 'Microsoft.Storage/storageAccounts/blobServices/containers@2023-05-01' = {
+ parent: blobService
+ name: 'recordings'
+}
+
resource functionAppBlob 'Microsoft.Storage/storageAccounts/blobServices/containers@2023-05-01' = {
parent: blobService
name: toLower(functionAppName)
@@ -283,6 +290,16 @@ resource roleDataContributor 'Microsoft.Authorization/roleDefinitions@2022-04-01
name: 'ba92f5b4-2d11-453d-a403-e96b0029c9fe'
}
+resource assignmentCommunicationServicesContributor 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
+ name: guid(subscription().id, prefix, storageAccount.name, 'assignmentCommunicationServicesContributor')
+ scope: storageAccount
+ properties: {
+ principalId: communicationServices.identity.principalId
+ principalType: 'ServicePrincipal'
+ roleDefinitionId: roleDataContributor.id
+ }
+}
+
resource assignmentFunctionAppContributor 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
name: guid(subscription().id, prefix, communicationServices.name, 'assignmentFunctionAppContributor')
scope: communicationServices
diff --git a/function_app.py b/function_app.py
index d793b9e..23ee4d9 100644
--- a/function_app.py
+++ b/function_app.py
@@ -673,9 +673,11 @@ async def _communicationservices_event_worker( # noqa: PLR0912, PLR0915
_trigger_trainings_event(call=_call, trainings=trainings)
if event_type == "Microsoft.Communication.CallConnected": # Call answered
+ server_call_id = event.data["serverCallId"]
await on_call_connected(
call=call,
client=automation_client,
+ server_call_id=server_call_id,
)
elif event_type == "Microsoft.Communication.CallDisconnected": # Call hung up
diff --git a/helpers/call_events.py b/helpers/call_events.py
index c19d87a..309f1fc 100644
--- a/helpers/call_events.py
+++ b/helpers/call_events.py
@@ -1,7 +1,14 @@
import asyncio
from collections.abc import Awaitable, Callable
-from azure.communication.callautomation import DtmfTone, RecognitionChoice
+from azure.communication.callautomation import (
+ AzureBlobContainerRecordingStorage,
+ DtmfTone,
+ RecognitionChoice,
+ RecordingChannel,
+ RecordingContent,
+ RecordingFormat,
+)
from azure.communication.callautomation.aio import CallAutomationClient
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError
from pydantic import ValidationError
@@ -81,6 +88,7 @@ async def on_new_call(
async def on_call_connected(
call: CallStateModel,
client: CallAutomationClient,
+ server_call_id: str,
) -> None:
logger.info("Call connected, asking for language")
call.recognition_retry = 0 # Reset recognition retry counter
@@ -97,7 +105,12 @@ async def on_call_connected(
), # First, every time a call is answered, confirm the language
_db.call_aset(
call
- ), # save in DB allowing SMS answers to be more "in-sync", should be quick enough to be in sync with the next message
+ ), # Second, save in DB allowing SMS answers to be more "in-sync", should be quick enough to be in sync with the next message
+ _handle_recording(
+ call=call,
+ client=client,
+ server_call_id=server_call_id,
+ ), # Third, start recording the call
)
@@ -592,3 +605,28 @@ async def _handle_ivr_language(
context=CallContextEnum.IVR_LANG_SELECT,
text=await CONFIG.prompts.tts.ivr_language(call),
)
+
+
+async def _handle_recording(
+ call: CallStateModel,
+ client: CallAutomationClient,
+ server_call_id: str,
+) -> None:
+ if not CONFIG.communication_services.recording_enabled:
+ return
+
+ assert CONFIG.communication_services.recording_container_url
+ recording = await client.start_recording(
+ recording_channel_type=RecordingChannel.UNMIXED,
+ recording_content_type=RecordingContent.AUDIO,
+ recording_format_type=RecordingFormat.WAV,
+ server_call_id=server_call_id,
+ recording_storage=AzureBlobContainerRecordingStorage(
+ CONFIG.communication_services.recording_container_url
+ ),
+ )
+ logger.info(
+ "Recording started for %s (%s)",
+ call.initiate.phone_number,
+ recording.recording_id,
+ )
diff --git a/helpers/config_models/communication_services.py b/helpers/config_models/communication_services.py
index 79fe49e..ee0b0b2 100644
--- a/helpers/config_models/communication_services.py
+++ b/helpers/config_models/communication_services.py
@@ -1,4 +1,4 @@
-from pydantic import BaseModel, SecretStr
+from pydantic import BaseModel, SecretStr, ValidationInfo, field_validator
from helpers.pydantic_types.phone_numbers import PhoneNumber
@@ -9,6 +9,19 @@ class CommunicationServicesModel(BaseModel):
endpoint: str
phone_number: PhoneNumber
post_queue_name: str
+ recording_container_url: str | None = None
+ recording_enabled: bool
resource_id: str
sms_queue_name: str
trainings_queue_name: str
+
+ @field_validator("recording_container_url")
+ @classmethod
+ def _validate_recording_container_url(
+ cls,
+ recording_container_url: str | None,
+ info: ValidationInfo,
+ ) -> str | None:
+ if not recording_container_url and info.data.get("recording_enabled", False):
+ raise ValueError("Recording container URL required")
+ return recording_container_url