> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.rasen.ai/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.rasen.ai/_mcp/server.

# Connect your own call leg to an agent

> Run an agent on a call that your own switch, dialer or app already holds, with the right media settings, continuous audio and a clean end.

## Summary

An agent session runs an agent's live version on a call leg that you already own, over a media
WebSocket. This guide starts a session, streams audio both ways, follows the call and ends it, and
lists the setup mistakes that make a session fail or sound wrong. It does not cover calls that
Rasen dials; see [Place calls and read results](/guides/calls).

## Facts

| Item                | Value                                                                                                                                                                                                                   |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Operations          | `createAgentSession`, `getCall`, `endCall`                                                                                                                                                                              |
| Paths               | `POST /agent-sessions`, `GET /calls/{call_id}`, `POST /calls/{call_id}/end`                                                                                                                                             |
| Capability          | `calls.write` for `createAgentSession` and `endCall`; `calls.read` for `getCall`                                                                                                                                        |
| Required headers    | `Authorization` on every request; `Idempotency-Key` on `createAgentSession` and `endCall`                                                                                                                               |
| Agent               | Runs its live published version. An agent that was never published is refused                                                                                                                                           |
| Request body        | `agent_id` is the only required field. Optional: `direction`, `expected_version_id`, `media`, `dynamic_variables`, `metadata`. Rasen refuses any other field, such as a number or caller ID, with `400 invalid_request` |
| `media.transport`   | `binary` (default): raw audio in binary WebSocket frames. `json`: base64 audio in `media` events in text frames                                                                                                         |
| `media.encoding`    | `pcm16` (default): signed 16-bit, little-endian, mono. `mulaw`: G.711 mu-law, 8000 Hz only                                                                                                                              |
| `media.sample_rate` | `8000` (default) or `16000`. The same rate in both directions                                                                                                                                                           |
| Answer              | `201` with `call_id`, `published_version_id`, `state: admitted`, `media`, `websocket_url`, `expires_at`                                                                                                                 |
| `websocket_url`     | A credential for one call. Connect to it exactly as returned. One socket for each call                                                                                                                                  |
| Connect window      | Connect and send audio before `expires_at`, 120 seconds after admission. Otherwise the call ends with `end_reason` `never_connected`                                                                                    |
| Agent audio         | On the same socket, in the declared `media`, in packets of 20 ms (320 bytes for `pcm16` at 8000 Hz, 640 bytes at 16000 Hz, 160 bytes for `mulaw`)                                                                       |
| Call limits         | Agent sessions share the call-start rate limit and the concurrent calls of the workspace with `createCall`. See [Rate limits](/concepts/rate-limits) and [Limits and quotas](/concepts/limits)                          |
| `dynamic_variables` | At most 64 keys, 4096 characters per value, 16 KiB in total; string values only                                                                                                                                         |
| `metadata`          | At most 16 keys matching `^[a-z][a-z0-9_]{0,63}$`, values of at most 512 characters, 4 KiB in total                                                                                                                     |
| Environment         | `RASEN_API_BASE` (the base URL, ending in `/v1`), `RASEN_API_KEY`, `AGENT_ID`, `CALL_ID`, `WEBSOCKET_URL`                                                                                                               |
| Python              | 3.10 or later, with the `httpx` and `websockets` packages                                                                                                                                                               |
| TypeScript          | Node.js 22 or later (built-in `fetch` and `WebSocket`)                                                                                                                                                                  |

## Steps

Set `AGENT_ID` to the `id` of an agent with a live published version.

### 1. Start the session

Declare in `media` the exact format of the audio that your call leg carries. The sample declares
raw 16 kHz PCM16 in binary frames.

**`curl`**

```bash curl
curl -sS -X POST "$RASEN_API_BASE/agent-sessions" \
  -H "Authorization: Bearer $RASEN_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Content-Type: application/json" \
  -d "{\"agent_id\": \"$AGENT_ID\", \"direction\": \"inbound\",
       \"media\": {\"transport\": \"binary\", \"encoding\": \"pcm16\", \"sample_rate\": 16000},
       \"metadata\": {\"external_call_id\": \"pbx-4411\"}}"
```

**`Python`**

```python Python
import os
import uuid

import httpx

BASE = os.environ["RASEN_API_BASE"]
KEY = os.environ["RASEN_API_KEY"]
AGENT_ID = os.environ["AGENT_ID"]

response = httpx.post(
    f"{BASE}/agent-sessions",
    headers={"Authorization": f"Bearer {KEY}", "Idempotency-Key": str(uuid.uuid4())},
    json={
        "agent_id": AGENT_ID,
        "direction": "inbound",
        "media": {"transport": "binary", "encoding": "pcm16", "sample_rate": 16000},
        "metadata": {"external_call_id": "pbx-4411"},
    },
)
response.raise_for_status()
session = response.json()
print(session["call_id"], session["state"], session["media"], session["expires_at"])
```

**`TypeScript`**

```typescript TypeScript
const { RASEN_API_BASE, RASEN_API_KEY, AGENT_ID } = process.env;

const response = await fetch(`${RASEN_API_BASE}/agent-sessions`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${RASEN_API_KEY}`,
    "Idempotency-Key": crypto.randomUUID(),
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    agent_id: AGENT_ID,
    direction: "inbound",
    media: { transport: "binary", encoding: "pcm16", sample_rate: 16000 },
    metadata: { external_call_id: "pbx-4411" },
  }),
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const session = await response.json();
console.log(session.call_id, session.state, session.media, session.expires_at);
```

The answer is `201` with the session. Check that `media` is the format you meant: Rasen freezes
it on the call. Set `CALL_ID` to `call_id` and `WEBSOCKET_URL` to `websocket_url`. Do not print or
log `websocket_url` in production: it is a credential.

If the answer is lost, send the same request with the same `Idempotency-Key`. You get the same
call, `websocket_url` and `expires_at`. A replay never extends `expires_at`.

### 2. Connect the socket and stream audio

Connect to `websocket_url` before `expires_at`. Then send the caller's audio all the time, in real
time: one frame of 20 ms every 20 ms, with silence when the caller is quiet. The agent's audio
comes back on the same socket. The call becomes `active` when your first audio frame arrives.

This step talks to the media socket, not to the REST API. The samples read a raw file,
`caller.raw` (16 kHz PCM16 mono), as a stand-in for your call leg, send silence after it, and save
the agent's audio to `agent.raw`.

**`Python`**

```python Python
import asyncio
import os

import websockets

WEBSOCKET_URL = os.environ["WEBSOCKET_URL"]
SAMPLE_RATE = 16000
FRAME_BYTES = SAMPLE_RATE * 20 // 1000 * 2  # 20 ms of 16-bit mono audio: 640 bytes
SILENCE = bytes(FRAME_BYTES)


async def send_caller_audio(socket, pcm: bytes, seconds_after: float) -> None:
    frames = [pcm[i : i + FRAME_BYTES].ljust(FRAME_BYTES, b"\0") for i in range(0, len(pcm), FRAME_BYTES)]
    frames += [SILENCE] * int(seconds_after * 50)
    loop = asyncio.get_running_loop()
    start = loop.time()
    for number, frame in enumerate(frames):
        await socket.send(frame)  # binary frame: raw audio, no envelope
        # Pace by the clock, not by the loop: frame n leaves at n x 20 ms.
        await asyncio.sleep(max(0.0, start + (number + 1) * 0.02 - loop.time()))


async def save_agent_audio(socket, path: str) -> None:
    with open(path, "wb") as out:
        async for message in socket:
            if isinstance(message, bytes):
                out.write(message)  # 20 ms packets in the declared media


async def main() -> None:
    with open("caller.raw", "rb") as source:
        pcm = source.read()
    async with websockets.connect(WEBSOCKET_URL, max_size=None) as socket:
        receiver = asyncio.create_task(save_agent_audio(socket, "agent.raw"))
        await send_caller_audio(socket, pcm, seconds_after=20)
        await socket.close()  # closing the socket ends the call
        await receiver


asyncio.run(main())
```

**`TypeScript`**

```typescript TypeScript
import { readFileSync, appendFileSync } from "node:fs";

const { WEBSOCKET_URL } = process.env;
const SAMPLE_RATE = 16000;
const FRAME_BYTES = (SAMPLE_RATE * 20) / 1000 * 2; // 20 ms of 16-bit mono audio: 640 bytes

const pcm = readFileSync("caller.raw");
const frames: Buffer[] = [];
for (let i = 0; i < pcm.length; i += FRAME_BYTES) {
  const frame = Buffer.alloc(FRAME_BYTES);
  pcm.copy(frame, 0, i, Math.min(i + FRAME_BYTES, pcm.length));
  frames.push(frame);
}
for (let i = 0; i < 20 * 50; i++) frames.push(Buffer.alloc(FRAME_BYTES)); // 20 s of silence

const socket = new WebSocket(WEBSOCKET_URL!);
socket.binaryType = "arraybuffer"; // the default "blob" gives Blob objects, not bytes

socket.onmessage = (event) => {
  if (event.data instanceof ArrayBuffer) appendFileSync("agent.raw", Buffer.from(event.data));
};

socket.onopen = () => {
  const start = performance.now();
  let next = 0;
  const tick = () => {
    // Pace by the clock: send every frame that is due, then wait for the next one.
    while (next < frames.length && start + next * 20 <= performance.now()) {
      socket.send(frames[next]);
      next += 1;
    }
    if (next < frames.length) setTimeout(tick, 5);
    else socket.close(); // closing the socket ends the call
  };
  tick();
};
```

With `media.transport` `json`, send each frame as a text frame instead:

```json
{"event": "media", "media": {"payload": "<base64 of one 20 ms frame>", "timestamp": 1240}}
```

* `media.timestamp` is optional: the milliseconds of the frame since your stream started. With it,
  the recording places each frame at its own time.
* A keypad digit is `{"event": "dtmf", "dtmf": {"digit": "5"}}`.
* Rasen sends the agent's audio as `{"event": "media", "streamId": "...", "media": {"payload": "...", "encoding": "pcm16", "sampleRate": 16000}}`.
  When the caller talks over the agent, Rasen sends `{"event": "clear", "streamId": "..."}`: drop
  the agent audio that you have buffered and not played yet.

### 3. Follow the call

Read the call while it runs, and after it ends, as any other call. Set `CALL_ID` to the `call_id`
from step 1.

**`curl`**

```bash curl
curl -sS "$RASEN_API_BASE/calls/$CALL_ID" \
  -H "Authorization: Bearer $RASEN_API_KEY"
```

**`Python`**

```python Python
import os

import httpx

BASE = os.environ["RASEN_API_BASE"]
KEY = os.environ["RASEN_API_KEY"]
CALL_ID = os.environ["CALL_ID"]

response = httpx.get(f"{BASE}/calls/{CALL_ID}", headers={"Authorization": f"Bearer {KEY}"})
response.raise_for_status()
call = response.json()
print(call["state"], call["terminal"], call["end_reason"], call["poll_after_seconds"])
```

**`TypeScript`**

```typescript TypeScript
const { RASEN_API_BASE, RASEN_API_KEY, CALL_ID } = process.env;

const response = await fetch(`${RASEN_API_BASE}/calls/${CALL_ID}`, {
  headers: { Authorization: `Bearer ${RASEN_API_KEY}` },
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const call = await response.json();
console.log(call.state, call.terminal, call.end_reason, call.poll_after_seconds);
```

The call is `admitted` until your first audio frame arrives, then `active`. After it ends, read it
until `terminal` is `true`, and wait `poll_after_seconds` between reads. The transcript, the
recording and the results work as for any call. To follow the words live, see
[Follow a call's transcript live](/guides/live-transcript).

### 4. End the session

End the call from your side in one of two ways:

* Close the socket when your call leg hangs up. Closing the socket ends the call.
* Call `endCall` when you want the agent to stop but your leg stays up, for example to hand the
  caller to a person.

**`curl`**

```bash curl
curl -sS -X POST "$RASEN_API_BASE/calls/$CALL_ID/end" \
  -H "Authorization: Bearer $RASEN_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)"
```

**`Python`**

```python Python
import os
import uuid

import httpx

BASE = os.environ["RASEN_API_BASE"]
KEY = os.environ["RASEN_API_KEY"]
CALL_ID = os.environ["CALL_ID"]

response = httpx.post(
    f"{BASE}/calls/{CALL_ID}/end",
    headers={"Authorization": f"Bearer {KEY}", "Idempotency-Key": str(uuid.uuid4())},
)
response.raise_for_status()
print(response.json())
```

**`TypeScript`**

```typescript TypeScript
const { RASEN_API_BASE, RASEN_API_KEY, CALL_ID } = process.env;

const response = await fetch(`${RASEN_API_BASE}/calls/${CALL_ID}/end`, {
  method: "POST",
  headers: { Authorization: `Bearer ${RASEN_API_KEY}`, "Idempotency-Key": crypto.randomUUID() },
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
console.log(await response.json());
```

A live call answers `{"terminal": false, "end_requested": true}`, and the call ends shortly. When
the call ends, for any reason, Rasen stops the agent's audio. Treat a socket that Rasen closes as
the end of the call, and hang up your leg.

## Common mistakes

| What you see                                                              | Cause                                                                                                | Fix                                                                                        |
| ------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| The agent sounds too fast and high, or too slow and low                   | `media.sample_rate` is not the rate of the audio you send or play                                    | Declare the real rate of your leg. Resample to 8000 or 16000 Hz before you send            |
| Loud noise instead of speech                                              | The audio is not `media.encoding`: for example mu-law sent as `pcm16`, big-endian samples, or stereo | Send mono audio in the declared encoding: `pcm16` is signed 16-bit little-endian           |
| The agent hears nothing                                                   | With `transport: json` you send binary frames, or with `transport: binary` you send base64 text      | Send the frame type of the declared `transport`                                            |
| The call ends with `end_reason` `never_connected`                         | The socket did not connect and send audio within 120 seconds of admission                            | Connect right after the answer. Start the session only when the leg is ready               |
| The agent answers late, misses a line or talks over the end of a sentence | Your client holds audio back and sends it in bursts, or sends audio only while the caller speaks     | Send one 20 ms frame every 20 ms, with silence between words, paced by a clock             |
| Clicks or gaps in the agent's audio                                       | Your side plays packets as they arrive, with no buffer                                               | Play the agent's audio through a jitter buffer, so that a late packet does not leave a gap |
| In a browser, `event.data` is a `Blob`                                    | The browser `WebSocket` default `binaryType` is `blob`                                               | Set `binaryType = "arraybuffer"` before the first message                                  |
| A second session starts for one call                                      | A retry after a lost answer used a new `Idempotency-Key`                                             | Persist the key before you send. Retry with the same key and the same body                 |
| The agent runs old settings                                               | The agent's changes are in its draft, not published                                                  | Publish the agent. Send `expected_version_id` to refuse a version that you do not expect   |

## Rules

* MUST create the session on your server. MUST NOT put `RASEN_API_KEY` in browser or mobile code.
  Give the browser only the `websocket_url` of its own call.
* MUST declare `media` as the exact format of the leg, and MUST send and play audio in that
  format in both directions.
* MUST connect to `websocket_url` exactly as returned, before `expires_at`, with one socket for
  each call. MUST NOT log it.
* MUST send audio continuously in real time, including silence, in frames of 20 ms. MUST NOT
  buffer the caller's audio and send it in bursts.
* MUST drop buffered agent audio on a `clear` event when you use `transport: json`. A switch that
  buffers the agent's audio deeply SHOULD use `json`, because `binary` has no `clear` event.
* MUST send a new `Idempotency-Key` for each new session, and the same key and body to retry a
  lost answer.
* MUST wait `Retry-After` seconds after `503 at_capacity`, `429 workspace_concurrency_full` or
  `429 quota_exceeded`, then send the identical request with the same key. Double the wait on each
  new refusal, with a random part, and stop after a few minutes.
* MUST close the socket when your leg hangs up, so that the call ends and its capacity is free.

## Verify

```bash
curl -sS "$RASEN_API_BASE/calls/$CALL_ID" \
  -H "Authorization: Bearer $RASEN_API_KEY"
```

Expected output after the call: `terminal` is `true`, and `end_reason` is not `never_connected`.

```json
{"call_id": "call_01j00000000000000000000000", "state": "complete", "terminal": true, "direction": "inbound", "end_reason": "caller_hangup", "metadata": {"external_call_id": "pbx-4411"}, "poll_after_seconds": null}
```

## Errors

| Code                                                  | Cause                                                                                                                                | Fix                                                                                           |
| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------- |
| `invalid_request`                                     | A field is not allowed (a number, caller ID or provider), `mulaw` with `16000`, or a value is out of range. `details.field` names it | Remove or fix the field, and send it with a new `Idempotency-Key`                             |
| `agent_not_published`                                 | The agent has no published version                                                                                                   | Publish the agent, then start the session                                                     |
| `agent_not_live`                                      | The agent is not live, for example archived or paused (`details.state`)                                                              | Make the agent live, then start the session                                                   |
| `conflict` (`details.reason` `live_version_mismatch`) | `expected_version_id` is not the live version. `details.current_live_version_id` is the live one                                     | Check that the live version is the one you want, then send its ID or no `expected_version_id` |
| `at_capacity`                                         | No line is free: your workspace (`details.reason` `workspace_limit`) or the platform                                                 | Wait `Retry-After` seconds, then send the identical request with the same key                 |
| `workspace_concurrency_full`                          | The workspace's share of concurrent calls is full                                                                                    | End a call or wait, then retry after `Retry-After` with the same key                          |
| `quota_exceeded`                                      | A usage quota has no allowance left                                                                                                  | Wait `Retry-After` seconds, or reduce usage                                                   |
| `rate_limited`                                        | Too many call starts in this minute for the key or the workspace                                                                     | Wait `Retry-After` seconds, then send the same request with the same key                      |
| `not_served_in_region`                                | The workspace's caller region cannot run the agent's language                                                                        | Change where your callers are in the workspace settings, or use another language              |
| `idempotency_key_reused`                              | The key was used on this operation for another body                                                                                  | Send a new key for a new session                                                              |

## Related

* [Place calls and read results](/guides/calls)
* [Follow a call's transcript live](/guides/live-transcript)
* [Call lifecycle](/concepts/call-lifecycle)
* [Call end reasons](/reference/call-end-reasons)
* [Idempotency and replay](/concepts/idempotency)
* [Limits and quotas](/concepts/limits)