-
Notifications
You must be signed in to change notification settings - Fork 83
Add support for Twilio #42
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 2 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,7 +2,7 @@ | |
| | [](https://codespaces.new/Azure-Samples/call-center-voice-agent-accelerator) | [](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). | ||
|
|
||
|
|
@@ -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). | ||
| - **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 | ||
| || | ||
| || | ||
| |---| | ||
|
|
||
| <br/> | ||
|
|
@@ -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. | ||
|
|
||
|
|
@@ -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)**. | ||
|
|
||
|
|
@@ -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. | ||
|
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. | ||
|
|
||
|
|
@@ -254,7 +306,9 @@ azd deploy | |
|
|
||
| <br/> | ||
|
|
||
| ## Optional Features | ||
|
|
||
|
|
||
| ## Optional feature | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit: "features" instead of "feature" since there is more than one?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Updated. Thanks. |
||
|
|
||
| ### 🎧 Ambient Scenes | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.