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.mdindex 1a572b1..e7f9d38 100644--- a/README.md+++ b/README.md@@ -298,6 +298,7 @@ conversation:communication_services:# Phone number purshased from Communication Servicesphone_number: "+33612345678"+ recording_enabled: falsesms: {}@@ -366,6 +367,7 @@ communication_services:endpoint: https://xxx.france.communication.azure.comphone_number: "+33612345678"post_queue_name: post-33612345678+ recording_enabled: falseresource_id: xxxsms_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 SearchTraining data is stored on AI Search to be retrieved by the bot, on demand.diff --git a/bicep/app.bicep b/bicep/app.bicepindex fc9d63d..6e348df 100644--- a/bicep/app.bicep+++ b/bicep/app.bicep@@ -59,6 +59,8 @@ var config = {endpoint: communicationServices.properties.hostNamephone_number: localConfig.communication_services.phone_numberpost_queue_name: postQueue.name+ recording_container_url: '${storageAccount.properties.primaryEndpoints.blob}${recordingsBlob.name}'+ recording_enabled: localConfig.communication_services.recording_enabledresource_id: communicationServices.properties.immutableResourceIdsms_queue_name: smsQueue.nametrainings_queue_name: trainingsQueue.name@@ -273,6 +275,11 @@ resource publicBlob 'Microsoft.Storage/storageAccounts/blobServices/containers@2name: '$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: blobServicename: toLower(functionAppName)@@ -283,6 +290,16 @@ resource roleDataContributor 'Microsoft.Authorization/roleDefinitions@2022-04-01name: '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: communicationServicesdiff --git a/function_app.py b/function_app.pyindex 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 updiff --git a/helpers/call_events.py b/helpers/call_events.pyindex c19d87a..309f1fc 100644--- a/helpers/call_events.py+++ b/helpers/call_events.py@@ -1,7 +1,14 @@import asynciofrom 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 CallAutomationClientfrom azure.core.exceptions import ClientAuthenticationError, HttpResponseErrorfrom 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.pyindex 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_validatorfrom helpers.pydantic_types.phone_numbers import PhoneNumber@@ -9,6 +9,19 @@ class CommunicationServicesModel(BaseModel):endpoint: strphone_number: PhoneNumberpost_queue_name: str+ recording_container_url: str | None = None+ recording_enabled: boolresource_id: strsms_queue_name: strtrainings_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