Skip to navigation

Connect your own call leg to an agent

Start an agent session, stream the caller's audio on its media WebSocket, and end it cleanly.

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.

Facts

ItemValue
OperationscreateAgentSession, getCall, endCall
PathsPOST /agent-sessions, GET /calls/{call_id}, POST /calls/{call_id}/end
Capabilitycalls.write for createAgentSession and endCall; calls.read for getCall
Required headersAuthorization on every request; Idempotency-Key on createAgentSession and endCall
AgentRuns its live published version. An agent that was never published is refused
Request bodyagent_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.transportbinary (default): raw audio in binary WebSocket frames. json: base64 audio in media events in text frames
media.encodingpcm16 (default): signed 16-bit, little-endian, mono. mulaw: G.711 mu-law, 8000 Hz only
media.sample_rate8000 (default) or 16000. The same rate in both directions
Answer201 with call_id, published_version_id, state: admitted, media, websocket_url, expires_at
websocket_urlA credential for one call. Connect to it exactly as returned. One socket for each call
Connect windowConnect and send audio before expires_at, 120 seconds after admission. Otherwise the call ends with end_reason never_connected
Agent audioOn 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 limitsAgent sessions share the call-start rate limit and the concurrent calls of the workspace with createCall. See Rate limits and Limits and quotas
dynamic_variablesAt most 64 keys, 4096 characters per value, 16 KiB in total; string values only
metadataAt most 16 keys matching ^[a-z][a-z0-9_]{0,63}$, values of at most 512 characters, 4 KiB in total
EnvironmentRASEN_API_BASE (the base URL, ending in /v1), RASEN_API_KEY, AGENT_ID, CALL_ID, WEBSOCKET_URL
Python3.10 or later, with the httpx and websockets packages
TypeScriptNode.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 -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\"}}"

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.

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())

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

{"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 -sS "$RASEN_API_BASE/calls/$CALL_ID" \
-H "Authorization: Bearer $RASEN_API_KEY"

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.

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 -sS -X POST "$RASEN_API_BASE/calls/$CALL_ID/end" \
-H "Authorization: Bearer $RASEN_API_KEY" \
-H "Idempotency-Key: $(uuidgen)"

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 seeCauseFix
The agent sounds too fast and high, or too slow and lowmedia.sample_rate is not the rate of the audio you send or playDeclare the real rate of your leg. Resample to 8000 or 16000 Hz before you send
Loud noise instead of speechThe audio is not media.encoding: for example mu-law sent as pcm16, big-endian samples, or stereoSend mono audio in the declared encoding: pcm16 is signed 16-bit little-endian
The agent hears nothingWith transport: json you send binary frames, or with transport: binary you send base64 textSend the frame type of the declared transport
The call ends with end_reason never_connectedThe socket did not connect and send audio within 120 seconds of admissionConnect 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 sentenceYour client holds audio back and sends it in bursts, or sends audio only while the caller speaksSend one 20 ms frame every 20 ms, with silence between words, paced by a clock
Clicks or gaps in the agent’s audioYour side plays packets as they arrive, with no bufferPlay 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 BlobThe browser WebSocket default binaryType is blobSet binaryType = "arraybuffer" before the first message
A second session starts for one callA retry after a lost answer used a new Idempotency-KeyPersist the key before you send. Retry with the same key and the same body
The agent runs old settingsThe agent’s changes are in its draft, not publishedPublish 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

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.

{"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

CodeCauseFix
invalid_requestA field is not allowed (a number, caller ID or provider), mulaw with 16000, or a value is out of range. details.field names itRemove or fix the field, and send it with a new Idempotency-Key
agent_not_publishedThe agent has no published versionPublish the agent, then start the session
agent_not_liveThe 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 oneCheck that the live version is the one you want, then send its ID or no expected_version_id
at_capacityNo line is free: your workspace (details.reason workspace_limit) or the platformWait Retry-After seconds, then send the identical request with the same key
workspace_concurrency_fullThe workspace’s share of concurrent calls is fullEnd a call or wait, then retry after Retry-After with the same key
quota_exceededA usage quota has no allowance leftWait Retry-After seconds, or reduce usage
rate_limitedToo many call starts in this minute for the key or the workspaceWait Retry-After seconds, then send the same request with the same key
not_served_in_regionThe workspace’s caller region cannot run the agent’s languageChange where your callers are in the workspace settings, or use another language
idempotency_key_reusedThe key was used on this operation for another bodySend a new key for a new session