> ## Documentation Index
> Fetch the complete documentation index at: https://docs.baseten.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Connect phone calls to Baseten Realtime Voice

> Answer phone calls with a Baseten Realtime Voice agent by relaying G.711 audio between your telephony provider and the agent, with Twilio as the example.

> [!NOTE]
>
> Baseten Realtime Voice is in **Private Preview**. [Join the waitlist](https://www.baseten.co/talk-to-us/realtime-voice-private-preview/)
> to get it enabled for your organization.

To answer phone calls with a Realtime Voice agent, run a relay between your telephony provider and the agent's WebSocket. Providers such as Twilio stream a call's audio to a WebSocket that you host, in their own message format, and can't send your Baseten API key. The relay holds the key, opens one Realtime session per call, and copies audio in both directions.

Phone audio is G.711 at 8 kHz, and the agent sends and receives it directly as `audio/pcmu` (μ-law) or `audio/pcma` (A-law). The relay passes each base64 payload through unchanged, so it never decodes or resamples audio.

```mermaid theme={"system"}
flowchart LR
    Caller["Caller"] -->|"Phone network"| Provider["Telephony provider"]
    Provider <-->|"Media stream, G.711"| Relay["Your relay"]
    Relay <-->|"Realtime events, audio/pcmu"| Agent["Realtime Voice"]
    classDef endpoint fill:#ecfdf5,stroke:#00a35a,color:#14532d
    class Caller,Provider,Relay,Agent endpoint
```

This guide builds the relay for [Twilio Media Streams](https://www.twilio.com/docs/voice/media-streams). For another provider, keep the Realtime half and replace the Twilio messages, as described in [Use another telephony provider](#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](https://docs.baseten.co/organization/api-keys.md).
* A [Twilio account](https://www.twilio.com/try-twilio) with a phone number that has Voice capabilities.
* Python 3.10 or later.
* A public HTTPS address for the relay. This guide uses [ngrok](https://ngrok.com/) 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:

```sh theme={"system"}
pip install fastapi python-multipart uvicorn websockets
```

Save this file as `twilio_relay.py`:

```python twilio_relay.py theme={"system"}
#!/usr/bin/env python3
"""Put a voice agent behind a Twilio phone number.

Twilio Media Streams and the Realtime Voice WebSocket both carry base64 audio in
JSON messages, but in different envelopes, and Twilio can't send the
`Authorization` header. This relay sits between them: it answers Twilio's
webhook with TwiML, opens one Realtime session per call, and copies audio both
ways. The audio is G.711 mu-law at 8 kHz end to end, so nothing is transcoded.

It reads BASETEN_WSS_URL and BASETEN_API_KEY from the environment and listens
on port 5050. Twilio's "A call comes in" webhook goes to `/incoming-call`.

Any provider that streams mu-law over a WebSocket works the same way: only
`incoming_call`, `twilio_to_agent` and the `send_twilio` messages are Twilio's.
"""

from __future__ import annotations

import asyncio
import base64
import json
import os
from xml.sax.saxutils import quoteattr

import uvicorn
import websockets
from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect
from fastapi.responses import Response

BASETEN_WSS_URL = os.environ["BASETEN_WSS_URL"]
BASETEN_API_KEY = os.environ["BASETEN_API_KEY"]
PORT = int(os.environ.get("PORT", "5050"))

INSTRUCTIONS = """\
You are Riley, a support agent for Northwind Fiber, a home internet provider, on a live phone call.
Plans: Fiber 300 at $49.99 a month, Fiber Gig at $69.99, Fiber Max at $99.99. No contracts or data caps.
When the caller has nothing else, say goodbye and then call end_call.
"""
GREETING = (
    "Greet the caller: say you're Riley from Northwind Fiber support and ask how "
    "you can help. One short sentence."
)

SESSION = {
    "type": "realtime",
    "instructions": INSTRUCTIONS,
    "audio": {
        # Twilio's own format, both ways: the relay never decodes the audio.
        "input": {
            "format": {"type": "audio/pcmu"},
            "turn_detection": {
                "type": "server_vad",
                "create_response": True,
                "interrupt_response": True,
            },
        },
        "output": {"format": {"type": "audio/pcmu"}},
    },
    "tools": [{
        "type": "function",
        "name": "end_call",
        "description": "Hang up the phone. Call it after you have said goodbye.",
        "parameters": {"type": "object", "properties": {}},
    }],
}

MULAW_BYTES_PER_MS = 8  # 8,000 one-byte samples a second

app = FastAPI()


@app.post("/incoming-call")
async def incoming_call(request: Request) -> Response:
    """Twilio calls this when the number rings. Answer with a media stream."""
    form = await request.form()
    host = request.headers["host"]
    # <Parameter> values arrive in the stream's `start` message; the caller's
    # number isn't there otherwise.
    twiml = (
        '<?xml version="1.0" encoding="UTF-8"?>'
        "<Response><Connect>"
        f'<Stream url="wss://{host}/media-stream">'
        f'<Parameter name="from" value={quoteattr(str(form.get("From", "")))} />'
        "</Stream></Connect></Response>"
    )
    return Response(twiml, media_type="text/xml")


@app.websocket("/media-stream")
async def media_stream(twilio: WebSocket) -> None:
    """One phone call: a Twilio media stream on one side, a Realtime session on the other."""
    await twilio.accept()
    headers = {"Authorization": f"Bearer {BASETEN_API_KEY}"}
    async with websockets.connect(BASETEN_WSS_URL, additional_headers=headers) as agent:
        # Configure the session before any audio. Twilio's messages wait in
        # the socket meanwhile, so the caller's first words aren't lost.
        await agent.send(json.dumps({"type": "session.update", "session": SESSION}))
        # The agent speaks first.
        await agent.send(json.dumps(
            {"type": "response.create", "response": {"instructions": GREETING}}
        ))
        call = Call(twilio, agent)
        tasks = [asyncio.create_task(call.twilio_to_agent()),
                 asyncio.create_task(call.agent_to_twilio())]
        # Either side ending ends the call: the caller hung up, or the session closed.
        await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
        for task in [*tasks, call.hanging_up]:
            if task:
                task.cancel()
        await asyncio.gather(*tasks, return_exceptions=True)
    try:
        # With nothing after <Connect> in the TwiML, closing the stream hangs up.
        await twilio.close()
    except (RuntimeError, WebSocketDisconnect):
        pass  # Twilio closed it first


class Call:
    def __init__(self, twilio: WebSocket, agent) -> None:
        self.twilio = twilio
        self.agent = agent
        self.stream_sid: str | None = None
        # Milliseconds of each reply sent to Twilio, and played by it.
        self.sent_ms: dict[str, int] = {}
        self.played_ms: dict[str, int] = {}
        # The reply Twilio is playing, and whether everything sent has played.
        self.playing: str | None = None
        self.played_all = asyncio.Event()
        self.played_all.set()
        # The end_call the agent made in the reply still being spoken, and the
        # hangup waiting for that reply to finish playing.
        self.end_call_id: str | None = None
        self.hanging_up: asyncio.Task | None = None

    async def send_twilio(self, message: dict) -> None:
        await self.twilio.send_text(json.dumps({**message, "streamSid": self.stream_sid}))

    async def twilio_to_agent(self) -> None:
        try:
            async for raw in self.twilio.iter_text():
                message = json.loads(raw)
                kind = message["event"]
                if kind == "start":
                    self.stream_sid = message["start"]["streamSid"]
                    print("call from", message["start"]["customParameters"].get("from"))
                elif kind == "media":
                    # Already base64 mu-law: pass the payload through as it is.
                    await self.agent.send(json.dumps({
                        "type": "input_audio_buffer.append",
                        "audio": message["media"]["payload"],
                    }))
                elif kind == "mark":
                    # Twilio played the audio sent before this mark.
                    item_id, _, ms = message["mark"]["name"].rpartition(":")
                    if item_id == self.playing:
                        self.played_ms[item_id] = int(ms)
                        if int(ms) >= self.sent_ms.get(item_id, 0):
                            self.played_all.set()
                elif kind == "stop":
                    return  # the caller hung up
        except (WebSocketDisconnect, websockets.ConnectionClosed):
            return

    async def agent_to_twilio(self) -> None:
        try:
            await self._agent_to_twilio()
        except websockets.ConnectionClosed as closed:
            # 1013: the deployment is warming up or full. A production relay retries.
            print("session closed:", closed)

    async def _agent_to_twilio(self) -> None:
        async for raw in self.agent:
            event = json.loads(raw)
            kind = event["type"]
            if kind == "response.output_audio.delta":
                await self.play(event["item_id"], event["delta"])
            elif kind == "response.function_call_arguments.done":
                # The call is reported before the audio of the goodbye said in
                # the same reply, so hang up after that reply's response.done.
                if event["name"] == "end_call":
                    self.end_call_id = event["call_id"]
            elif kind == "response.done":
                details = event["response"].get("status_details") or {}
                if details.get("reason") == "turn_detected":
                    await self.interrupted()
                elif self.end_call_id:
                    # The reply is complete, but Twilio is still playing it.
                    self.hanging_up = asyncio.create_task(self.hang_up())
            elif kind == "input_audio_buffer.speech_started":
                if self.hanging_up:
                    # The caller spoke while the goodbye was playing.
                    self.hanging_up.cancel()
                    self.hanging_up = None
                    await self.interrupted()
            elif kind == "conversation.item.input_audio_transcription.completed":
                print("caller:", event["transcript"])
            elif kind == "response.output_audio_transcript.done":
                print("agent: ", event["transcript"])
            elif kind == "error":
                print("error: ", event["error"])

    async def play(self, item_id: str, delta: str) -> None:
        """Queue a chunk of the agent's audio on the call, then a mark after it."""
        if self.stream_sid is None:
            return
        ms = len(base64.b64decode(delta)) // MULAW_BYTES_PER_MS
        self.sent_ms[item_id] = self.sent_ms.get(item_id, 0) + ms
        self.playing = item_id
        self.played_all.clear()
        await self.send_twilio({"event": "media", "media": {"payload": delta}})
        # Twilio echoes the mark once the audio before it has played, which is
        # how the relay knows how much of a reply the caller heard.
        await self.send_twilio(
            {"event": "mark", "mark": {"name": f"{item_id}:{self.sent_ms[item_id]}"}}
        )

    async def interrupted(self) -> None:
        """The caller talked over the agent: stop its audio and report what was heard."""
        item_id, self.playing = self.playing, None
        self.played_all.set()
        if self.end_call_id:
            # The caller spoke over the goodbye: stay on the line.
            await self.tool_result("The caller kept talking, so the call is still connected.")
        if item_id is None or self.played_ms.get(item_id, 0) >= self.sent_ms[item_id]:
            return  # nothing was still queued
        await self.send_twilio({"event": "clear"})
        await self.agent.send(json.dumps({
            "type": "conversation.item.truncate",
            "item_id": item_id,
            "content_index": 0,
            "audio_end_ms": self.played_ms.get(item_id, 0),
        }))

    async def tool_result(self, output: str) -> None:
        call_id, self.end_call_id = self.end_call_id, None
        await self.agent.send(json.dumps({
            "type": "conversation.item.create",
            "item": {"type": "function_call_output", "call_id": call_id, "output": output},
        }))

    async def hang_up(self) -> None:
        """The agent called end_call: let its goodbye finish playing, then end the call."""
        try:
            await asyncio.wait_for(self.played_all.wait(), timeout=10)
        except asyncio.TimeoutError:
            pass
        await self.tool_result("ok")
        # Closing the session ends agent_to_twilio, which ends the call.
        await self.agent.close()


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=PORT)
```

**2. Run the relay**

Set your WebSocket URL and API key, then start the server:

```sh theme={"system"}
export BASETEN_WSS_URL="wss://chain-<chain_id>.api.baseten.co/environments/production/websocket"
export BASETEN_API_KEY="<BASETEN_API_KEY>"
python twilio_relay.py
```

The relay listens on port 5050. To test from your machine, open a second terminal and give it a temporary public address with ngrok:

```sh theme={"system"}
ngrok http 5050
```

Copy the `https://` forwarding address that ngrok prints.

**3. Point your Twilio number at the relay**

In the [Twilio Console](https://console.twilio.com/), 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:

```text theme={"system"}
call from +15550100
agent:  Hi, I'm Riley from Northwind Fiber support, how can I help you today?
caller: What plans do you have?
agent:  We have Fiber 300 for $49.99 a month, Fiber Gig for $69.99, and Fiber Max for $99.99. Would you like more details on any of those?
caller: That's all. Bye.
agent:  Goodbye!
```

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`:

```xml theme={"system"}
<Response>
  <Connect>
    <Stream url="wss://<your-address>/media-stream">
      <Parameter name="from" value="+15550100" />
    </Stream>
  </Connect>
</Response>
```

Pass any other value your agent needs the same way, such as an account ID you looked up from the number, and add it to `instructions` before you send `session.update`. The name and value of each `<Parameter>` must total under 500 characters.

### Open the session

The relay sends one `session.update` as soon as the agent's WebSocket opens, then a `response.create` so that the agent speaks first. Both [audio formats](https://docs.baseten.co/inference/audio/realtime-voice/recipes.md#telephony-audio) 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 short `media` 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 sends `response.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 `clear` message, which discards the queued audio.
* **Report what the caller heard.** Send `conversation.item.truncate` with the milliseconds of the reply that Twilio played, so that the conversation history ends where the caller stopped listening.

To know how much Twilio played, the relay sends a `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_call` function tool and tells it to say goodbye first. The tool call arrives before the goodbye's audio, so the relay waits for that reply's `response.done` and for Twilio to return the last mark, then closes the session and Twilio's WebSocket. With no TwiML after `<Connect>`, Twilio ends the call. If `input_audio_buffer.speech_started` arrives 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 cancelled `response.done` follows.
* **The session closes.** A session closes after 300 seconds without speech from either side. To change that, set [`x_idle_timeout_secs`](https://docs.baseten.co/reference/inference-api/predict-endpoints/realtime-voice-api#param-session-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 the `X-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](https://www.twilio.com/docs/usage/security#validating-requests).

For retries, relay placement, bandwidth, and latency, follow the [best practices](https://docs.baseten.co/inference/audio/realtime-voice/best-practices.md).

## 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:

| The relay needs | Twilio Media Streams |
| - | - |
| A way to start a bidirectional stream | TwiML `<Connect><Stream>` |
| Caller audio packets | `media` messages, base64 μ-law |
| A way to send audio to the call | `media` messages |
| A way to discard queued audio | `clear` |
| Playback progress | `mark` |
| The end of the call | `stop` |

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 `instructions` for a phone agent with the [prompting guide](https://docs.baseten.co/inference/audio/realtime-voice/prompting-guide.md).
* Add tools, delegation, and key terms from the [recipes](https://docs.baseten.co/inference/audio/realtime-voice/recipes.md).
* Refer to the [API reference](https://docs.baseten.co/reference/inference-api/predict-endpoints/realtime-voice-api.md) for every event and `session.update` field.
