Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 61 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
| [![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/Azure-Samples/call-center-voice-agent-accelerator) | [![Open in Dev Containers](https://img.shields.io/static/v1?style=for-the-badge&label=Dev%20Containers&message=Open&color=blue&logo=visualstudiocode)](https://vscode.dev/redirect?url=vscode://ms-vscode-remote.remote-containers/cloneInVolume?url=https://github.com/Azure-Samples/call-center-voice-agent-accelerator)
|---|---|

Welcome to the *Call Center Real-time Voice Agent* solution accelerator. It's a lightweight template to create speech-to-speech voice agents that deliver personalized self-service experiences and natural-sounding voices, seamlessly integrated with telephony systems. This solution accelerator uses **Azure Voice Live API** and **Azure Communication Services** — Start locally, deploy later to Azure Web App. No PSTN number needed.
Welcome to the *Call Center Real-time Voice Agent* solution accelerator a lightweight template for building speech-to-speech voice agents powered by **Azure Voice Live API**. It supports multiple telephony providers out of the box, including **Azure Communication Services (ACS)** and **Twilio**, plus a **web browser** client for quick testing. Bring your own telephony provider or use the built-in options. Start locally, deploy to Azure Container Apps.

The Azure voice live API is a solution enabling low-latency, high-quality speech to speech interactions for voice agents. The API is designed for developers seeking scalable and efficient voice-driven experiences as it eliminates the need to manually orchestrate multiple components. By integrating speech recognition, generative AI, and text to speech functionalities into a single, unified interface, it provides an end-to-end solution for creating seamless experiences. Learn more about [Azure Voice Live API](https://learn.microsoft.com/azure/ai-services/speech-service/voice-live).

Expand All @@ -26,15 +26,20 @@ This sample demonstrates how to build a real-time voice agent using the [Azure S

The solution includes:
- A backend service that connects to the **Voice Live API** for real-time ASR, LLM and TTS
- Two client options: **Web browser** (microphone/speaker) and **Azure Communication Services (ACS)** phone calls
- **Multiple client options:** The web browser client is always available. For telephony, choose **one** provider:
- **Web browser** — microphone/speaker via WebSocket (always available, great for testing)
- **Azure Communication Services (ACS)** — enterprise PSTN with Call Automation (default)
- **Twilio** — PSTN via Twilio Media Streams with webhook signature validation

> **Telephony selection:** Only one telephony provider is active at a time. The server auto-detects based on which credentials are configured (e.g. `TWILIO_AUTH_TOKEN` present → Twilio, otherwise → ACS).
Comment thread
Emma-ms marked this conversation as resolved.
- **Ambient Scenes** (optional): Add realistic background audio (office, call center) or use custom audio files to simulate real-world environments
- Flexible configuration to customize prompts, ASR, TTS, and behavior
- Easy extension to other client types such as [Audiohook](https://learn.microsoft.com/azure/ai-services/speech-service/how-to-use-audiohook)

> You can also try the Voice Live API via [Azure AI Foundry](https://ai.azure.com/foundry) for quick experimentation before deploying this template to your own Azure subscription.

### Architecture diagram
|![Architecture Diagram](./docs/images/architecture_v0.0.2.png)|
|![Architecture Diagram](./docs/images/architecture_v0.0.3.png)|
|---|

<br/>
Expand Down Expand Up @@ -176,7 +181,7 @@ To change the `azd` parameters from the default values, follow the steps [here](

After deployment, you can verify that your Voice Agent is running correctly using either the Web Client (for quick testing) or the ACS Phone Client (for simulating a real-world call center scenario).

🌐 Web Client (Test Mode)
### 🌐 Web Client (Test Mode)

Use this browser-based client to confirm your Container App is up and responding.

Expand All @@ -191,7 +196,7 @@ Use this browser-based client to confirm your Container App is up and responding



📞 ACS Client (Call Center Scenario)
### 📞 Telephony with ACS Client (Call Center Scenario)

This simulates a real inbound phone call to your voice agent using **Azure Communication Services (ACS)**.

Expand Down Expand Up @@ -229,8 +234,55 @@ Once your event subscription is configured and the phone number is active:
- Dial the ACS number.
- Your call will connect to the real-time voice agent powered by Azure Voice Live.

### 📞 Telephony with Twilio Client (Call Center Scenario)

You can switch the telephony provider from ACS to **Twilio** by setting `TWILIO_AUTH_TOKEN`. When this token is configured, the server registers Twilio routes (`/voice` and `/twilio/ws`) instead of ACS routes. Inbound calls are handled via [Twilio Media Streams](https://www.twilio.com/docs/voice/media-streams) — the server validates the request, connects the caller's audio to the AI agent via a real-time WebSocket, and bridges it to Azure Voice Live.

> To switch back to ACS, simply remove or unset `TWILIO_AUTH_TOKEN` and redeploy.
Comment thread
Emma-ms marked this conversation as resolved.

**Prerequisites:**
- A [Twilio account](https://www.twilio.com/try-twilio) with a phone number
- Your **Twilio Auth Token** (found in the [Twilio Console](https://www.twilio.com/console))

**Setup with `azd`:**

```bash
# Set your Twilio Auth Token before deploying
azd env set TWILIO_AUTH_TOKEN <your-twilio-auth-token>

# Then deploy:
azd up
# or redeploy:
azd provision
azd deploy
```

The token is stored securely in Azure Key Vault and injected into the Container App as a secret reference.

#### Local execution
**Configure Twilio Webhook:**

1. In the [Twilio Console](https://console.twilio.com), go to your phone number's configuration.
2. Under **PhoneNumber → A Call Comes In**, set:
- **Webhook URL:** `https://<your-container-app-url>/voice`
- **HTTP Method:** `POST`
3. Save changes.

**What happens when a call comes in:**
1. Twilio sends a request to `/voice` — the server validates it and returns instructions (TwiML) to start a media stream
2. Twilio opens a WebSocket to `/twilio/ws` — the server verifies the embedded token, then bridges the caller's audio to Azure Voice Live in real time
3. The AI agent hears the caller, generates a response, and the audio is streamed back through the same connection

**Local development:**

For local testing, set `TWILIO_AUTH_TOKEN` in your `.env` file:
```
TWILIO_AUTH_TOKEN=your_auth_token_here
```

> **Note:** `TWILIO_AUTH_TOKEN` is required for both local and deployed environments. Without it, incoming calls will be rejected.

---
### Local execution

Once the environment has been deployed with `azd up` you can also run the application locally.

Expand All @@ -254,7 +306,9 @@ azd deploy

<br/>

## Optional Features


## Optional feature
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: "features" instead of "feature" since there is more than one?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated. Thanks.


### 🎧 Ambient Scenes

Expand Down
3 changes: 2 additions & 1 deletion azure.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,5 @@ pipeline:
- AZURE_RESOURCE_GROUP
- AZURE_CONTAINER_REGISTRY_ENDPOINT
- SERVICE_API_ENDPOINTS
- AZURE_VOICE_LIVE_ENDPOINT
- AZURE_VOICE_LIVE_ENDPOINT
- TWILIO_AUTH_TOKEN
Binary file added docs/images/architecture_v0.0.3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
16 changes: 12 additions & 4 deletions infra/main.bicep
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ param appExists bool
param modelName string = ' gpt-4o-mini'
@description('Id of the user or app to assign application roles. If ommited will be generated from the user assigned identity.')
param principalId string = ''
@secure()
@description('Twilio Auth Token for webhook signature validation')
param twilioAuthToken string = ''

var useTwilio = !empty(twilioAuthToken)

var uniqueSuffix = substring(uniqueString(subscription().id, environmentName), 0, 5)
var tags = {'azd-env-name': environmentName }
Expand Down Expand Up @@ -82,7 +87,7 @@ module aiServices 'modules/aiservices.bicep' = {
dependsOn: [ appIdentity ]
}

module acs 'modules/acs.bicep' = {
module acs 'modules/acs.bicep' = if (!useTwilio) {
name: 'acs-deployment'
scope: rg
params: {
Expand All @@ -101,9 +106,11 @@ module keyvault 'modules/keyvault.bicep' = {
location: location
keyVaultName: sanitizedKeyVaultName
tags: tags
acsConnectionString: acs.outputs.acsConnectionString
#disable-next-line BCP327
acsConnectionString: !useTwilio ? acs.outputs.acsConnectionString : ''
twilioAuthToken: twilioAuthToken
}
dependsOn: [ appIdentity, acs ]
dependsOn: [ appIdentity ]
}

// Add role assignments
Expand Down Expand Up @@ -133,6 +140,7 @@ module containerapp 'modules/containerapp.bicep' = {
aiServicesEndpoint: aiServices.outputs.aiServicesEndpoint
modelDeploymentName: modelName
acsConnectionStringSecretUri: keyvault.outputs.acsConnectionStringUri
twilioAuthTokenSecretUri: keyvault.outputs.twilioAuthTokenUri
logAnalyticsWorkspaceName: logAnalyticsName
imageName: 'mcr.microsoft.com/azuredocs/containerapps-helloworld:latest'
}
Expand All @@ -148,6 +156,6 @@ output AZURE_USER_ASSIGNED_IDENTITY_ID string = appIdentity.outputs.identityId
output AZURE_USER_ASSIGNED_IDENTITY_CLIENT_ID string = appIdentity.outputs.clientId

output AZURE_CONTAINER_REGISTRY_ENDPOINT string = registry.outputs.loginServer
output SERVICE_API_ENDPOINTS array = ['${containerapp.outputs.containerAppFqdn}/acs/incomingcall']
output SERVICE_API_ENDPOINTS array = !useTwilio ? ['https://${containerapp.outputs.containerAppFqdn}/acs/incomingcall'] : ['https://${containerapp.outputs.containerAppFqdn}/voice']
output AZURE_VOICE_LIVE_ENDPOINT string = aiServices.outputs.aiServicesEndpoint
output AZURE_VOICE_LIVE_MODEL string = modelName
3 changes: 3 additions & 0 deletions infra/main.parameters.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@
},
"appExists": {
"value": "${SERVICE_APP_RESOURCE_EXISTS=false}"
},
"twilioAuthToken": {
"value": "${TWILIO_AUTH_TOKEN}"
}
}
}
33 changes: 24 additions & 9 deletions infra/modules/containerapp.bicep
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ param containerRegistryName string
param aiServicesEndpoint string
param modelDeploymentName string
param acsConnectionStringSecretUri string
param twilioAuthTokenSecretUri string = ''
param logAnalyticsWorkspaceName string
@description('The name of the container image')
param imageName string = ''
Expand Down Expand Up @@ -67,20 +68,28 @@ resource containerApp 'Microsoft.App/containerApps@2024-10-02-preview' = {
identity: identityId
}
]
secrets: [
{
name: 'acs-connection-string'
keyVaultUrl: acsConnectionStringSecretUri
secrets: concat(
!empty(acsConnectionStringSecretUri) ? [
{
name: 'acs-connection-string'
keyVaultUrl: acsConnectionStringSecretUri
identity: identityId
}
] : [],
!empty(twilioAuthTokenSecretUri) ? [
{
name: 'twilio-auth-token'
keyVaultUrl: twilioAuthTokenSecretUri
identity: identityId
}
]
] : [])
}
template: {
containers: [
{
name: 'main'
image: !empty(imageName) ? imageName : 'mcr.microsoft.com/azuredocs/containerapps-helloworld:latest'
env: [
env: concat([
{
name: 'AZURE_VOICE_LIVE_ENDPOINT'
value: aiServicesEndpoint
Expand All @@ -93,15 +102,21 @@ resource containerApp 'Microsoft.App/containerApps@2024-10-02-preview' = {
name: 'VOICE_LIVE_MODEL'
value: modelDeploymentName
}
{
name: 'DEBUG_MODE'
value: 'true'
}
], !empty(acsConnectionStringSecretUri) ? [
{
name: 'ACS_CONNECTION_STRING'
secretRef: 'acs-connection-string'
}
] : [], !empty(twilioAuthTokenSecretUri) ? [
{
name: 'DEBUG_MODE'
value: 'true'
name: 'TWILIO_AUTH_TOKEN'
secretRef: 'twilio-auth-token'
}
]
] : [])
resources: {
cpu: json('2.0')
memory: '4.0Gi'
Expand Down
15 changes: 13 additions & 2 deletions infra/modules/keyvault.bicep
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ param keyVaultName string
param tags object
@secure()
param acsConnectionString string
@secure()
param twilioAuthToken string = ''

var sanitizedKeyVaultName = take(toLower(replace(replace(replace(replace(keyVaultName, '--', '-'), '_', '-'), '[^a-zA-Z0-9-]', ''), '-$', '')), 24)

Expand All @@ -25,7 +27,7 @@ resource keyVault 'Microsoft.KeyVault/vaults@2023-02-01' = {
}


resource acsConnectionStringSecret 'Microsoft.KeyVault/vaults/secrets@2023-07-01' = {
resource acsConnectionStringSecret 'Microsoft.KeyVault/vaults/secrets@2023-07-01' = if (!empty(acsConnectionString)) {
parent: keyVault
name: 'ACS-CONNECTION-STRING'
properties: {
Expand All @@ -35,6 +37,15 @@ resource acsConnectionStringSecret 'Microsoft.KeyVault/vaults/secrets@2023-07-01

var keyVaultDnsSuffix = environment().suffixes.keyvaultDns

output acsConnectionStringUri string = 'https://${keyVault.name}${keyVaultDnsSuffix}/secrets/${acsConnectionStringSecret.name}'
resource twilioAuthTokenSecret 'Microsoft.KeyVault/vaults/secrets@2023-07-01' = if (!empty(twilioAuthToken)) {
parent: keyVault
name: 'TWILIO-AUTH-TOKEN'
properties: {
value: twilioAuthToken
}
}

output acsConnectionStringUri string = !empty(acsConnectionString) ? 'https://${keyVault.name}${keyVaultDnsSuffix}/secrets/${acsConnectionStringSecret.name}' : ''
output twilioAuthTokenUri string = !empty(twilioAuthToken) ? 'https://${keyVault.name}${keyVaultDnsSuffix}/secrets/TWILIO-AUTH-TOKEN' : ''
output keyVaultId string = keyVault.id
output keyVaultName string = keyVault.name
1 change: 1 addition & 0 deletions server/.env-sample.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ AZURE_VOICE_LIVE_ENDPOINT=<Find the endpoint from your AI foundry resource>
VOICE_LIVE_MODEL=gpt-4o-mini
ACS_CONNECTION_STRING=<Find the connection string from your Communication Service resource>
ACS_DEV_TUNNEL=<Optional, only set it when you run local ACS test>
TWILIO_AUTH_TOKEN=<Optional, Twilio Auth Token for webhook signature validation>

# Ambient Scenes (Optional)
# Adds realistic background audio to simulate real-world call environments
Expand Down
78 changes: 78 additions & 0 deletions server/app/handler/twilio_event_handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
"""Handler for Twilio webhook validation and incoming call TwiML generation."""

import hashlib
import hmac
import logging
import time
from urllib.parse import urlparse, urlunparse

from twilio.request_validator import RequestValidator
from twilio.twiml.voice_response import VoiceResponse

logger = logging.getLogger(__name__)

# Token validity period in seconds
_TOKEN_TTL = 60


class TwilioEventHandler:
"""Validates Twilio webhook signatures and generates TwiML responses."""

def __init__(self, config):
self.auth_token = config.get("TWILIO_AUTH_TOKEN", "")

def _reconstruct_url(self, raw_url: str) -> str:
"""Reconstruct URL as Twilio sees it (https, no port for voice HTTPS)."""
parsed = urlparse(raw_url)
return urlunparse(("https", parsed.hostname, parsed.path, parsed.params, parsed.query, ""))

def _generate_ws_token(self) -> str:
"""Generate a short-lived HMAC token for WebSocket authentication."""
timestamp = str(int(time.time()))
sig = hmac.new(
self.auth_token.encode(), timestamp.encode(), hashlib.sha256
).hexdigest()
return f"{timestamp}.{sig}"

def verify_ws_token(self, token: str) -> bool:
"""Verify a WebSocket token is valid and not expired."""
if not self.auth_token or not token:
return False
parts = token.split(".", 1)
if len(parts) != 2:
return False
timestamp_str, sig = parts
try:
timestamp = int(timestamp_str)
except ValueError:
return False
# Check expiry
if time.time() - timestamp > _TOKEN_TTL:
return False
# Verify signature
expected = hmac.new(
self.auth_token.encode(), timestamp_str.encode(), hashlib.sha256
).hexdigest()
return hmac.compare_digest(sig, expected)

def validate_request(self, url: str, params: dict, signature: str) -> bool:
"""Validate a Twilio HTTP webhook request signature.

Returns True if valid, False if invalid, None if auth token not configured.
"""
if not self.auth_token:
return None
validator = RequestValidator(self.auth_token)
reconstructed_url = self._reconstruct_url(url)
return validator.validate(reconstructed_url, params, signature)

def generate_stream_twiml(self, ws_url: str) -> str:
"""Generate TwiML response that connects the call to a media stream with auth token."""
token = self._generate_ws_token()
resp = VoiceResponse()
resp.say("Please wait while we connect you to our AI assistant.")
connect = resp.connect()
stream = connect.stream(url=ws_url)
stream.parameter(name="token", value=token)
logger.info("Returning TwiML with stream URL: %s", ws_url)
return str(resp)
Loading
Loading