Baseten Realtime Voice is in Private Preview. Join the waitlist
to get it enabled for your organization.
audio/pcmu (μ-law) or audio/pcma (A-law). The relay passes each base64 payload through unchanged, so it never decodes or resamples audio.
This guide builds the relay for Twilio Media Streams. For another provider, keep the Realtime half and replace the Twilio messages, as described in Use another telephony provider.
Build a Twilio relay
The example runs a FastAPI server with two routes. Twilio sends an HTTP request to/incoming-call when your number rings, and then opens a WebSocket to /media-stream that carries the call.
Prerequisites
- Your Realtime Voice WebSocket URL and a Baseten API key.
- A Twilio account with a phone number that has Voice capabilities.
- Python 3.10 or later.
- A public HTTPS address for the relay. This guide uses ngrok to expose a relay running on your machine, which is for local development and testing only. In production, deploy the relay to a host with its own public address.
1
Save the relay
Install the dependencies:Save this file as
twilio_relay.py:twilio_relay.py
2
Run the relay
Set your WebSocket URL and API key, then start the server:The relay listens on port 5050. To test from your machine, open a second terminal and give it a temporary public address with ngrok:Copy the
https:// forwarding address that ngrok prints.3
Point your Twilio number at the relay
In the Twilio Console, open your phone number’s voice settings. Set A call comes in to a webhook, enter
https://<your-address>/incoming-call, select HTTP POST, and save.4
Call the number
Call your Twilio number. The agent greets you, and the relay prints both sides of the conversation, for example:Talk over the agent to confirm that its audio stops, and say goodbye to confirm that it hangs up.
How the relay works
Answer the call
/incoming-call returns TwiML that connects the call to a bidirectional stream. The stream’s start message has no field for the caller’s number, and the stream URL can’t carry query parameters. The TwiML passes the number as a <Parameter>, which arrives in start under customParameters:
instructions before you send session.update. The name and value of each <Parameter> must total under 500 characters.
Open the session
The relay sends onesession.update as soon as the agent’s WebSocket opens, then a response.create so that the agent speaks first. Both audio formats are audio/pcmu, the μ-law encoding Twilio uses.
Twilio’s messages wait in the relay’s WebSocket until the session is configured, so the caller’s first words reach the agent.
Copy audio
Twilio sends the caller’s audio as a stream of shortmedia messages. The relay copies media.payload into input_audio_buffer.append without decoding it, and keeps forwarding while the agent talks: the agent needs the caller’s audio to detect interruptions.
In the other direction, the relay copies each response.output_audio.delta into a Twilio media message. Twilio buffers the audio and plays it in the order received.
Handle interruptions
When the caller interrupts, the agent cancels its reply and sendsresponse.done with status: "cancelled" and status_details.reason: "turn_detected". Audio that the relay already sent is still in Twilio’s queue, so the relay does two things:
- Stop playback. Send Twilio a
clearmessage, which discards the queued audio. - Report what the caller heard. Send
conversation.item.truncatewith the milliseconds of the reply that Twilio played, so that the conversation history ends where the caller stopped listening.
mark message after each chunk of audio, named with the reply’s item ID and the milliseconds sent so far. Twilio returns each mark when the audio before it finishes playing, so the last mark returned is the playback position. Read the position before you send clear, because Twilio then returns the marks for the audio it discarded.
Wait for the cancelled response.done before you send clear. input_audio_buffer.speech_started also arrives for short acknowledgments such as “mm-hmm”, which don’t interrupt the agent.
End the call
- The caller hangs up. Twilio sends
stop. The relay closes the Realtime session. - The agent hangs up. The example gives the agent an
end_callfunction tool and tells it to say goodbye first. The tool call arrives before the goodbye’s audio, so the relay waits for that reply’sresponse.doneand for Twilio to return the last mark, then closes the session and Twilio’s WebSocket. With no TwiML after<Connect>, Twilio ends the call. Ifinput_audio_buffer.speech_startedarrives while the goodbye is still playing, the relay cancels the hangup and answers the tool call instead, and the call continues. The reply has already ended by then, so no cancelledresponse.donefollows. - The session closes. A session closes after 300 seconds without speech from either side. To change that, set
x_idle_timeout_secs. The relay closes Twilio’s WebSocket when the session closes.
Prepare for production
The ngrok address in this guide is for local development and testing. It only works while your machine and ngrok are running. For production, deploy the relay to a host with a stable public HTTPS address and point your Twilio number at that address. The example accepts requests from anyone who has its address. Before you take production calls, validate theX-Twilio-Signature header on /incoming-call and on the WebSocket handshake, so that only Twilio can open sessions with your API key. See Twilio’s request validation guide.
For retries, relay placement, bandwidth, and latency, follow the best practices.
Use another telephony provider
Any provider that streams G.711 over a WebSocket works with the same relay structure. Replace the Twilio half with your provider’s equivalents:
Set both audio formats to the codec your provider streams:
audio/pcmu for μ-law or audio/pcma for A-law. If your provider streams 16-bit pulse-code modulation (PCM), set audio/pcm with its sample rate, for example {"type": "audio/pcm", "rate": 8000}. If your provider doesn’t report playback progress, estimate the position from the time since you sent the reply’s first audio.
Next steps
- Write
instructionsfor a phone agent with the prompting guide. - Add tools, delegation, and key terms from the recipes.
- Refer to the API reference for every event and
session.updatefield.