Streaming into your app
The Quickstart shows the smallest working client. This page covers the production shape: a mint proxy on your server, LiveKit room join on the client, agent track subscription, chat over LiveKit text streams, reconnect, cleanup, and the common failure modes.
+------------------+ +----------------+ +---------------------+| Your client | | Your server | | 2wai API || | | (mint proxy) | | (api.2wai.ai) |+--------+---------+ +--------+-------+ +----------+----------+ | | | | 1. POST /mint | | | -------------------------> | 2. POST /v1/sessions | | | --------------------------> | | | | | | <-- livekit_url, token, | | | chat | | <-- same fields | | | | | 3. join room (livekit_url, participant_token) | | ----------------------------------------------------------| | | | <-- agent participant appears, video + audio tracks | | | | 4. sendText(user turn, topic "lk.chat") | | ----------------------------------------------------------| | | | <-- agent replies: voice + video on its tracks, | | reply text as a text stream on "lk.transcription" | | |Three distinct hops:
- Mint proxy (your server): holds the
sk_and exchanges it for a per-sessionparticipant_token. - LiveKit room join (your client to LiveKit): WebRTC transport, standard LiveKit SDK.
- Chat over text streams: user turns go to the agent as a text stream on topic
lk.chat; the agent’s reply text comes back as a text stream onlk.transcription, and its voice and video on the subscribed tracks.
The avatar’s own brain and voice (set on it in 2wai Studio) produce every reply. Your server does not drive speech: /speak, /audio and /interrupt answer 409 not_available_on_livekit on the current gateway.
Mint proxy
Section titled “Mint proxy”The simplest Node mint proxy:
import express from 'express';const app = express();app.use(express.json());
app.post('/mint', async (req, res) => { const r = await fetch('https://api.2wai.ai/v1/sessions', { method: 'POST', headers: { Authorization: `Bearer ${process.env.TWAI_SECRET_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ avatar_id: process.env.AVATAR_ID, // gen-... from catalog hydrate; pin it on the proxy mode: 'video', }), }); if (!r.ok) return res.status(r.status).json(await r.json());
const s = await r.json(); // Return only the fields the client needs to join the room and chat. res.json({ session_id: s.session_id, livekit_url: s.livekit_url, participant_token: s.participant_token, chat: s.chat, });});
app.post('/end', async (req, res) => { const r = await fetch(`https://api.2wai.ai/v1/sessions/${req.body.session_id}`, { method: 'DELETE', headers: { Authorization: `Bearer ${process.env.TWAI_SECRET_KEY}` }, }); res.status(r.status).end();});
app.listen(3000);transport is not needed: LiveKit is the default and the only transport ("mse-ws" is refused with 410 transport_retired).
Reference impls for Node, Python, and Cloudflare Worker are in 2waiorg/2wai-toolkit-public.
The session response
Section titled “The session response”POST /v1/sessions answers 201 with:
{ "session_id": "...", "transport": "livekit", "livekit_url": "wss://...", "room_name": "...", "participant_token": "eyJhbGciOi...", "agent_identity": "...", "expires_at": null, "chat": { "send_topic": "lk.chat", "format": "text", "reply_topic": "lk.transcription" }}livekit_url: the LiveKit server to connect to. Always use the value from the response; never hard-code one.room_name: the LiveKit room. It is not the same string assession_id.agent_identity: despite the name, this is the identity theparticipant_tokenassigns to your client (it reads likeviewer-...), not the agent’s identity. Do not use it to find the agent.chat.format: how the agent reads each user turn. It istext(send the user’s words as they are) for every avatar; see Chat formats.
Finding the agent. The agent is the other participant in the room: the first remote participant to join, usually within about a second of you connecting. Treat any remote participant’s tracks and text streams as the agent’s, or remember the first one from RoomEvent.ParticipantConnected (or room.remoteParticipants if it was already there when you connected).
Client: join, render, chat
Section titled “Client: join, render, chat”<video id="avatar" autoplay playsinline style="max-width: 480px"></video><script src="https://cdn.jsdelivr.net/npm/livekit-client@2/dist/livekit-client.umd.min.js"></script><script type="module"> const { Room, RoomEvent } = LivekitClient; const video = document.getElementById('avatar');
async function connect() { const session = await (await fetch('/mint', { method: 'POST' })).json();
// Mandatory for 2wai: adaptiveStream + dynacast MUST be off. const room = new Room({ adaptiveStream: false, dynacast: false });
room.on(RoomEvent.TrackSubscribed, (track) => { if (track.kind === 'video') track.attach(video); else if (track.kind === 'audio') track.attach(); });
// Reply text from the agent, one text stream per reply. It can contain // bracketed expression tags such as [curious]: strip them before display. room.registerTextStreamHandler(session.chat.reply_topic, async (reader, participant) => { if (participant.identity === room.localParticipant.identity) return; // ignore our own const text = stripTags(await reader.readAll()); console.log('avatar reply:', text); });
await room.connect(session.livekit_url, session.participant_token); return { room, session }; }
// Remove expression tags like [curious] from reply text. function stripTags(text) { return text.replace(/\[[^\]]*\]/g, '').replace(/\s{2,}/g, ' ').trim(); }
// Send a user turn as a text stream on lk.chat, as plain text. NOT publishData. async function send({ room, session }, text) { if (session.chat.format === 'unknown') { throw new Error('this room did not say how it reads a turn; see Chat formats'); } await room.localParticipant.sendText(text, { topic: session.chat.send_topic }); }
const conn = await connect(); window.send = (text) => send(conn, text);</script>Chat formats
Section titled “Chat formats”Every avatar reads the user’s turn as plain text on lk.chat, and each session’s chat.format says so.
chat.format | What to send on lk.chat | Where you see it |
|---|---|---|
text | The user’s words as plain text, up to 8,000 characters. | Every avatar. |
json-v1 | No longer returned. Sessions minted before 20 November 2026 named it for most avatars. Those rooms still accept JSON.stringify({ v: 1, request_id, text }) (request_id is 1 to 96 characters of A-Za-z0-9_-), so a client written for it keeps working, and they now take plain text too. | Older sessions only. |
unknown | Do not send. The gateway could not tell which room kind this is. End the session and contact support with the session_id. | Should be rare. |
What the agent refuses, with no error back to your client:
- a blank turn;
- a turn longer than 8,000 characters;
- a turn that is a JSON object, or starts like one (
{then"), but is not a valid v1 envelope. An object is read as an envelope attempt and never spoken.
Anything else is read as the user’s words, including text that starts with a brace, like {laughs} hi, and text that looks like a number.
Python, with the LiveKit Python SDK:
await room.local_participant.send_text( "Hi, tell me about yourself.", topic=session["chat"]["send_topic"], # "lk.chat")Speaking events
Section titled “Speaking events”LiveKit’s RoomEvent.ActiveSpeakersChanged fires when the agent participant starts or stops producing audio. Use it to animate the UI (for example “listening” versus “speaking”). The agent is the remote participant, so any speaker that is not you is the agent. Don’t match a name pattern, and don’t use agent_identity (that is your own identity):
room.on(RoomEvent.ActiveSpeakersChanged, (speakers) => { const agentActive = speakers.some((p) => p.identity !== room.localParticipant.identity); // update UI});Reply text and expression tags
Section titled “Reply text and expression tags”The reply text on lk.transcription can contain bracketed expression tags such as [curious]. They steer the avatar’s delivery and are not meant to be read. Strip anything in [...] before you show the text to a user (the stripTags helper above does this).
Reconnect
Section titled “Reconnect”LiveKit SDKs reconnect to the same room on their own after short network blips; you do not need to do anything.
Do not call POST /v1/sessions again to “reconnect”. A new session is a new room with a new agent, and the old session stays open (and counts against your concurrency cap) until you end it or it is reaped. If the connection is truly gone and you want to start over, end the old session with DELETE /v1/sessions/{id} first, then mint a new one.
Ending a session
Section titled “Ending a session”Call DELETE /v1/sessions/{id} (through your proxy’s /end route) when the user leaves: on a pagehide handler with navigator.sendBeacon, on your app’s own idle timeout, or when the conversation is explicitly over. Sessions left idle are reaped after 30 minutes; when your key is at its concurrency cap, idle LiveKit sessions can be reaped after 120 seconds.
Common failure modes
Section titled “Common failure modes”| Symptom | Likely cause | Fix |
|---|---|---|
| Mint returns 401 | sk_ wrong or revoked | Verify curl ... /v1/sessions with the sk_ directly (not via proxy) |
Mint returns 404 no_such_avatar | Wrong id, or the avatar is not exposed to the API by its owner | Resolve the id with catalog hydrate and check the avatar is exposed in 2wai Studio |
| Mint returns 429 | Your key’s cap (concurrency_cap) or the platform cap (platform_busy) | Back off per the Retry-After header; end sessions you no longer need |
| Room connects but no video appears | adaptiveStream not disabled | Pass new Room({ adaptiveStream: false, dynacast: false }) |
Reply text shows [curious] and similar | Expression tags in lk.transcription text | Strip [...] before display |
| Avatar never answers | Turn sent with publishData or on the wrong topic; a blank turn or one over 8,000 characters; or a JSON object (or text starting {") that is not a valid v1 envelope | Use sendText on chat.send_topic with the user’s words as plain text, at most 8,000 characters |
| First user turn clipped or ignored | Sent before the agent was ready | SDKs honor a 2-4 s SEND_GRACE_MS window after agent-ready; raw clients should wait a beat after the agent’s tracks subscribe before sending |