Docs

Calls

What your server decides, what the client reports, and how to end a call without cutting the character off mid-sentence.

A Realtime Avatar call is a live AI avatar in voice and lip-synced video that can call your page's functions; AvatarCall renders it in React. By default the platform runs speech recognition, the LLM, the voice and the video; voice mode drops the video. Your server decides who may start a call (the route's authorize callback), mints each one from one connect route (createRealtimeAvatarRoute in Next.js) and sets a policy the browser cannot override, including the instructions, prior messages to continue from, a hard stop on the session duration (up to 30 minutes), clientTools: true for the functions your page registers with attachAvatarTools or useCharacterTools, a signed transcript webhook and recording. AvatarCall reports five states (connecting, waiting, live, recovering and ended) and is web-only; on React Native you compose AvatarVideoSurface inside RealtimeAvatarLiveKitRoom from realtime-avatar/react-native.

Character stories and learning experiences

Yes. Define an original or appropriately licensed character, its speaking style and the context your server supplies for each call. Your application owns the story, source material, permissions and consequences of a user's choices. A character-driven lesson or story is an application design, not a guarantee of historical accuracy, learning outcomes or professional advice. Start with the Studio to evaluate a character, then use the SDK to integrate the experience.

Continuing a character conversation

Keep the character's behavior in instructions and supply relevant prior context when your server starts the next call. Your application decides what to save, what the user can inspect or delete, and which parts of a story belong in the next interaction. A new session does not automatically inherit persistent relationship memory. Use the Calls and Tool calling documentation to connect context and optional transcript delivery without treating diagnostic logs as your application's memory store.

What your server decides

The session policy on your connect endpoint. Every field here is authoritative — whatever the browser sent for these is discarded, and a field you do not set is absent rather than inherited from the caller. The Field column is the SDK name; the Wire column is the key a hand-rolled request sends — snake_case and strict, see Calling the API directly below.

FieldWireWhat it does
instructionsinstructionsHer behavior contract — who she is and how she speaks. Up to 16,000 characters. The highest-leverage field on the whole surface.
contextinitial_contextUp to 32 prior messages, replayed as memory. This is what makes a call continue a story instead of starting cold. On the wire it is initial_context, and each entry is { role: "system" | "user" | "assistant", content } with content 1–8000 characters — the SDK types this for you, raw HTTP does not.
maxSecondsmax_session_secondsHard stop, up to 1800. Enforced on our side, so it holds even if your client stops reporting. Compute it from the balance you just admitted.
listenstt_mode: "server" | "off"Speech recognition. Default true — she hears the user the whole call. Set false only if you drive every turn yourself — see Tool calling.
voicevoiceOverride her stored voice for this call. Must be a Fish voice; see below.
voiceWebhookvoice_webhook: { url, secret } — https URL, secret 16–200 charsSpeak the call with your own voice: each sentence is POSTed to your server, signed, and she speaks the audio you return. Replaces voice; see Custom voice (webhook) below.
videorender_backend: "generative", or omit itHow she is rendered: omit it for the generated loop + state map, or { mode: "generative" } to synthesize the video live — see Creating an avatar.
cameracameraOptional boolean. Your server authorizes camera sharing with true; capture remains off until the user enables it. Works in voice and avatar calls. Use useAvatarCamera to toggle within the same session without interrupting the microphone. See React and Native. User camera pixels are excluded from server video recordings.
clientToolscapabilities: ["client_tools"]true opts the call into the client tool plane — functions declared in your page that she can call mid-conversation. See Tool calling.
transcripttranscript_webhook: { url, secret } — https URL, secret 16–200 chars{ url, secret } — get the two-sided transcript back, signed, after the call ends. On the wire it is transcript_webhook, and secret is 16–200 characters — the SDK types this for you, raw HTTP does not. See Tool calling.
metadataclient_metadataUp to 16 string pairs, echoed verbatim on that transcript so you can attribute it without a lookup.
recordingrecordingoff (default), audio, video, or audio_video. Your server decides whether to record after obtaining consent. Audio includes published user and avatar audio.

The complete session creation request must fit within 64 KiB of JSON. This byte budget includes instructions, context, and all other fields; non-ASCII text can use multiple bytes per character. What the platform adds to your request (the avatar's clip library, its resolved voice and name) does not count against it.

There is no standalone voice_style field. Put persona, wording, and reply style in instructions. Sessions speak with Fish voices only, unless you send a voice_webhook. A voice with any other provider (Cartesia, Breeze Blue) is not an error: the call speaks with the character's own Fish voice, or with a Fish house voice matched to the character, and keeps that override's language and speed. A Fish voice takes speed, emotion, and language, and a model of s1, s2-pro, s2.1-pro, drama-3; it defaults to s2.1-pro. The retired Fish ids speech-1.6, speech-1.5, s1-mini are still accepted and speak as s2.1-pro. The platform carries the session instructions and voice configuration separately: the model writes the reply under the session instructions, then TTS renders that text under the voice configuration.

When the user talks while she is speaking, she decides whether to stop. If she carries on, what they said is still answered once she finishes. Send behavior: { yield_to_caller: true } on the raw request to have her stop at once for words that call for an answer, as a person would; a listening sound such as "mm" still lets her carry on.

Custom voice (webhook)

Send voice_webhook and the call speaks with a voice you host. Each time she is about to speak, the platform POSTs the sentence to your url, signed with your secret, and she speaks the audio you stream back, lip-synced. It works in both avatar and voice mode. Everything else stays ours: listening, turn-taking, interruption, the reply itself, and the video. It is server-only — a browser-minted request has the field removed — and it replaces the built-in voice, so sending it with voice or voice_id is a 422. With the SDK, set voiceWebhook on the session policy (realtime-avatar 0.28.0 or later); over raw HTTP, the field is voice_webhook.

FieldRule
urlMust start with https://, up to 500 characters. Redirects are never followed, and a host that resolves to a private address ends the call.
secret16–200 characters. The HMAC key for x-rta-signature, the transcript webhook's scheme.
voice_idOptional, your own voice identifier, echoed in every request.
languageOptional BCP-47 hint, echoed in every request.
sample_rateOptional: 8000, 16000, 22050, 24000 (default), 44100 or 48000. The rate of raw audio/pcm replies.
timeout_msOptional, 1000–15000 (default 5000). Bounds the first audio byte of each attempt and every later gap between chunks.

Each POST is JSON: {type: "voice.synthesize", version: 1, request_id, session_id, text, voice_id, language, output: {encoding: "pcm_s16le", sample_rate, channels: 1}, client_metadata}. text is the plain words to say — no markup, no stage directions. The headers are x-rta-signature: v1=<hex hmac> over "<timestamp>.<body>", x-rta-timestamp and x-rta-request-id. Verify the signature over the raw bytes before trusting anything.

Answer 200 and stream the audio as soon as you have it: the first byte is what the user waits for. audio/pcm (or audio/raw) is raw signed 16-bit little-endian mono at output.sample_rate, and audio/pcm;rate=16000 names another rate. WAV, MP3 and Ogg bodies are decoded too, but PCM is the one to use. Any rate works. A 2xx with no body — a 204, Content-Length: 0, or an empty first chunk — is voice_webhook_empty_audio, whatever its content type. When the user interrupts, the connection is closed mid-body; that is normal.

import { createHmac, timingSafeEqual } from "node:crypto";

// app/api/rta/voice/route.ts. The mint half, in your connect endpoint:
//   session: async () => ({ instructions,
//     voiceWebhook: { url: "https://your.app/api/rta/voice", secret: VOICE_SECRET } })
const MAX_SKEW_SECONDS = 300;

function verify(raw: string, signature: string, timestamp: string, secret: string): boolean {
  if (!/^\d+$/.test(timestamp) || Math.abs(Date.now() / 1000 - Number(timestamp)) > MAX_SKEW_SECONDS) {
    return false; // missing, malformed, or stale: replay-bound
  }
  const digest = createHmac("sha256", secret).update(`${timestamp}.${raw}`).digest("hex");
  const expected = Buffer.from(`v1=${digest}`);
  const given = Buffer.from(signature);
  return given.length === expected.length && timingSafeEqual(given, expected);
}

export async function POST(request: Request): Promise<Response> {
  const raw = await request.text(); // RAW body, before any parsing
  const signature = request.headers.get("x-rta-signature") ?? "";
  const timestamp = request.headers.get("x-rta-timestamp") ?? "";
  if (!verify(raw, signature, timestamp, process.env.RTA_VOICE_SECRET ?? "")) {
    return new Response(null, { status: 401 }); // a 401 ends the call
  }
  const job: unknown = JSON.parse(raw);
  if (typeof job !== "object" || job === null || !("text" in job) || typeof job.text !== "string") {
    return new Response(null, { status: 422 });
  }
  const upstream = await fetch("https://api.openai.com/v1/audio/speech", {
    method: "POST",
    headers: { authorization: `Bearer ${process.env.OPENAI_API_KEY}`, "content-type": "application/json" },
    body: JSON.stringify({ model: "gpt-4o-mini-tts", voice: "alloy", input: job.text, response_format: "pcm" }),
  });
  if (!upstream.ok || !upstream.body) return new Response(null, { status: 502 });
  // OpenAI's pcm is 24 kHz signed 16-bit little-endian mono: pass it straight through.
  return new Response(upstream.body, { headers: { "content-type": "audio/pcm;rate=24000" } });
}
import hashlib, hmac, json, os, time

import httpx
from fastapi import FastAPI, HTTPException, Request, Response
from fastapi.responses import StreamingResponse
from starlette.background import BackgroundTask

app = FastAPI()

# Mint half — in your connect route, next to avatar_id. Wire names.
#   body["voice_webhook"] = {"url": "https://your.app/api/rta/voice",  # https only
#                            "secret": VOICE_SECRET}                   # 16..200 chars
VOICE_SECRET = os.environ["RTA_VOICE_SECRET"]
MAX_SKEW_SECONDS = 300


def verify(body: bytes, signature: str, timestamp: str, secret: str) -> bool:
    if not timestamp.isdecimal() or abs(time.time() - int(timestamp)) > MAX_SKEW_SECONDS:
        return False                                  # missing, malformed, or stale: replay-bound
    signed = f"{timestamp}.{body.decode()}".encode()
    expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
    return hmac.compare_digest(f"v1={expected}", signature)


@app.post("/api/rta/voice")
async def voice(request: Request):
    raw = await request.body()                        # RAW bytes, before any parsing
    if not verify(raw, request.headers.get("x-rta-signature", ""),
                  request.headers.get("x-rta-timestamp", ""), VOICE_SECRET):
        raise HTTPException(401)                      # a 401 ends the call
    job = json.loads(raw)

    client = httpx.AsyncClient(timeout=30)
    try:
        upstream = await client.send(
            client.build_request(
                "POST", "https://api.openai.com/v1/audio/speech",
                headers={"authorization": f"Bearer {os.environ['OPENAI_API_KEY']}"},
                json={"model": "gpt-4o-mini-tts", "voice": "alloy",
                      "input": job["text"], "response_format": "pcm"},
            ),
            stream=True,
        )
    except httpx.HTTPError:
        await client.aclose()
        return Response(status_code=502)              # retried once, then voice_error
    if upstream.status_code != 200:                   # decide BEFORE the 200 is sent
        await upstream.aclose()
        await client.aclose()
        return Response(status_code=502)

    async def close() -> None:
        await upstream.aclose()
        await client.aclose()

    # OpenAI's pcm is 24 kHz signed 16-bit little-endian mono: pass it straight through.
    return StreamingResponse(upstream.aiter_bytes(), media_type="audio/pcm;rate=24000",
                             background=BackgroundTask(close))

When your endpoint fails, the client gets a voice_error event with one of these codes. A timeout, a connection failure, and HTTP 408, 429 and 5xx are retried once, only before any audio has arrived; the retry is a new POST with a new request_id. A failure that is not retried, or whose retry fails too, drops the rest of that reply: its later sentences are not sent, and the next reply tries again. A fatal one ends the call with failed.

CodeWhenEnds the call on its own
voice_webhook_url_not_allowedThe host does not resolve, or resolves to a private addressYes, at the start
voice_webhook_unauthorizedYour endpoint answered 401 or 403Yes
voice_webhook_unreachableDNS, connection or TLS failure, after one retryNo: drops the rest of that reply
voice_webhook_timeoutNo first audio byte, or no next chunk, within timeout_ms; retried once if no audio has arrivedNo: drops the rest of that reply
voice_webhook_http_errorAny other non-2xx, including a redirect; 408, 429 and 5xx are retried onceNo: drops the rest of that reply
voice_webhook_unsupported_audioA 2xx with a body that is not a supported audio type, or does not decodeNo: drops the rest of that reply
voice_webhook_empty_audioA 2xx with no body: a 204, Content-Length: 0, or an empty first chunkNo: drops the rest of that reply

Repeated unrecoverable failures end the call too: the last one arrives as a fatal voice_error carrying that failure's code, whatever it is, followed by failed. The event carries a message for you, never your URL, secret or response body.

Two modes

ModeWhat the user getsUse it for
avatar (default)She is on screen — audio and videoThe full call
voiceAudio onlyA cheaper on-ramp, or a fallback when bandwidth will not carry video

Same character, same policy — only mode changes. A voice call draws on separate capacity, so it never competes with a video call.

Recordings

Your backend can request a recording on POST /realtime/livekit/session. Recording defaults to off, and browser requests cannot override your server policy. Use audio for a mixed recording of published user and avatar audio, video for silent video, or audio_video for both in one MP4.

# Use your authenticated server-side HTTP client; see the API reference.
response = client.post("/realtime/livekit/session", json={
    "avatar_id": avatar_id,
    "recording": "audio_video",
})
response.raise_for_status()
grant = response.json()
recording_id = grant["recording"]["recordingId"]

# Later, after the call has ended:
recording = client.get(f"/recordings/{recording_id}").json()
if recording["status"] == "ready":
    access = client.get(f"/recordings/{recording_id}/access").json()
    # Return access["url"] only to someone allowed to view this call.

The recording ID stays the same through pending, recording, processing and ready. A failure is failed; an operator can mark a recording expired. Ending the call starts finalization, so the file may become ready afterward. Recording reads require a server API key with recordings:read and are limited to your workspace. The canonical recording schema defines the artifact and playback-access response.

RTA does not automatically delete recordings. Media is stored privately and remains available until an operator deletes it; retainedUntil reports the platform's retention horizon, not an expiry date. Keep recordingId in your database. Playback URLs last at most one hour and support seeking; request a new URL when one expires. A URL's expiresAt is separate from the recording's retainedUntil.

Recording captures authorized tracks already published in the call. It does not open a camera, request screen capture, or grant additional publishing rights. Transcript delivery remains a separate option; use sessionId and timestamps to join transcript turns to the recording.

If recording is unavailable, the mint returns recording_unsupported before starting the call. A capture startup failure returns recording_failed. Raw API callers must let RTA create a fresh room for each recorded session; reusing room_name or setting create_room: false is refused. Endpoint details are in the API reference.

Connection history

Enable connectionHistory: true in your server session policy when you want the SDK to retain connection changes with the call. On the wire this isconnection_history: true. Collection defaults to off and requires an SDK release with connection-history support. Your application keeps using the existingonConnectionDetailsChange callback for live behavior; it does not write an uploader.

The SDK uses existing LiveKit connection events and batches their changes to RTA with a short-lived capability that can only write to that session. It adds no receiver polling. Read the history through GET /sessions/{sessionId}/connection-historyusing a server key with usage:read. RTA stores at most 240 received changes per session and retains the history. Missing data remains unknown. Client timestamps are approximate; connection quality is not proof of successful device playback or an exact recording timeline.

What the client reports

Five states. Write copy for the ones you care about; the SDK ships none.

statusMeaning
connectingGetting her ready
waitingEvery slot is busy and you are holding a place in line — call.queuePosition has the number. Not an error; the SDK retries for you. Render the position, not a failure.
liveShe is there
recoveringA blip; reconnecting automatically with backoff
endedOver — onEnded already told you why

Network facts and call diagnostics

Use RTA's call status, actions and end reasons for ordinary product flows. Internally the SDK reads LiveKit's connection and track facts through its public APIs. A connected room or an available track does not prove that the user saw a frame or heard audio. Keep playback observations and business rules separate from transport diagnostics. The React integration shows the SDK's existing call-level callbacks.

Keep the RTA session_id together with your own call or segment ID. Server-authored metadata on startCall becomes client_metadata on the wire and carries application correlation independently of transcript storage. The granted room name and the platform's session timestamps provide the starting point for a LiveKit investigation. Room names can be reused; a room SID identifies a specific room lifetime.

Platform operators can investigate detailed historical network information in LiveKit Cloud. Its Analytics API lists sessions and participant details on Scale plans or higher; use the returned LiveKit session ID for detail requests, not the RTA session ID. Project management credentials remain with the operator; an RTA API key does not grant access to the shared LiveKit project. A developer diagnostic endpoint would need to authorize the RTA session first and expose only permitted fields. The documented API does not establish whether a browser actually presented each frame.

What you can do mid-call

call.say(text, { steer })  // say something to her; `steer` shapes THIS reply only
call.sayAndEnd(text)       // speak one exact line, verbatim, then close
call.keepAlive()           // the user is still here — postpone the idle disconnect
call.end()                 // end now
call.secondsRemaining      // to the hard stop, or null before the clock lands
call.queuePosition         // place in line while waiting, else null
# These are CLIENT-side actions — they act on a live call, which lives in the
# browser or native app. A Python backend owns the policy, not the live turn.
#
# What Python does own — and there is no Python SDK, so this half is plain HTTP:
#   POST /realtime/livekit/session           mint a call — body is snake_case and strict:
#                                            avatar_id, mode, instructions, initial_context,
#                                            max_session_seconds, stt_mode, capabilities,
#                                            transcript_webhook, client_metadata,
#                                            voice_webhook (the Wire
#                                            column above, not the SDK field names)
#   POST /realtime/livekit/session/release   free the slot early
#   GET  /credits/balance                    what the next call must fit inside

See Tool calling for the Python side of the conversation — the signed transcript you receive when a call ends.

say(text, { steer }) is the hook for tool results — steer applies to one reply and then evaporates, so a lookup result cannot leak into every later turn. See Tool calling.

Ending well

A call that stops mid-sentence feels broken no matter how good the render was. When time is nearly up you get a callback and a handle; whatever you pass to sayAndEnd is spoken exactly as written — never rewritten by the model, never interrupted — and only then does the call close.

<AvatarCall
  client={client}                                  // createProxyClient({ proxyUrl })
  avatarId={avatarId}
  balanceMs={creditRemainingMs}

  onEnding={async ({ secondsLeft, call }) => {
    if (secondsLeft > 15) return;                 // wait for the last window
    call.sayAndEnd(await writeGoodbye(character));
  }}
  onQuiet={({ secondsLeft }) => toast(`Still there? (${secondsLeft}s)`)}
  onLowBalance={({ secondsLeft }) => openTopUp(secondsLeft)}
  onEnded={({ reason }) => showEndScreen(reason)}
/>

onEnded always carries one of user_ended · session_cap · idle · disconnected · out_of_credits · agent_ended · failed. Key your end screen off it — "talk again?" and "you're out of minutes" are different screens with different outcomes.

The idle timer is real and enforced: when it fires the client disconnects and capacity is freed. That is deliberate. An abandoned tab holding a live character is the most expensive thing that can happen in this product, and it would be on your bill.

You can also release a call from your server. rta.endCall(sessionId, { reason }) frees the slot immediately — best-effort and idempotent: true when acknowledged, false for anything else, never a throw, so calling it twice (or on a call that already ended) is safe. Reach for it when your backend learns the call is over before the client does: a webhook, an admin action, a superseded reconnect. (Wire: POST /realtime/livekit/session/release, realtime:write scope.)

From the client, call.end() is the same thing and is what you normally want. The SDK also sends a release on tab-close via releaseLiveKitSessionBeacon(), which survives the page going away where a normal fetch would not. Release early and often: a held slot is capacity nobody else can use, and the queue is shared.

Calling the API directly

Not on TypeScript? The same call is one authenticated POST — the Python tab on Quickstart has a working endpoint. Two things to know before hand-rolling it:

  • Every endpoint is strict, and casing is per endpoint. An unknown or mis-cased key is a rejected call, not a dropped field — and which casing is right depends on where you are writing. The realtime routes on this page (/realtime/livekit/session and its /release) are snake_case; every REST resource endpoint — avatars, clips, keys, assets — is camelCase. The preview /scenes routes answer in snake_case, like the mint they feed, and so does /realtime/livekit/prejoin. Measured against the published spec: 3 of the 14 request bodies are snake_case at the top level and 11 are camelCase, with two exceptions worth knowing, because the strictness above turns a mis-cased key there into a 422: POST /avatars is camelCase outside and snake_case inside voice (auto_description, voice_id), and so is POST /renders, whose inline voice is the live call's voice object (voice_id). The SDK translates its camelCase policy for you; a hand-rolled request has no such help — send the Wire column from the policy table above (initial_context, max_session_seconds, transcript_webhook, client_metadata…), never the SDK names.
  • Pass the connection payload to your client byte-for-byte. It is validated strictly — add one key and the client rejects the whole thing, so the call never opens and nothing points at the cause.

Full endpoint list, scopes, and error codes: API reference.

Compare and cost guides