Skip to content

Reference integration: real customer-shape code

The 2wai team ships several open-source reference apps that mirror what a real customer integration looks like. This guide is a tour of the architecture they use on Transport 0 (LiveKit), so you can copy the shape directly or lift pieces into your own build.

Every integration follows the same shape:

YOUR backend (mint proxy) 2wai gateway
client ------------------------------------------------------------
| POST /mint (same-origin) | |
| ----------------------------->| POST /v1/sessions |
| | (Bearer sk_, server)|
| | -------------------->|
| <-- livekit_url, token, chat |<---- session fields |
| |
| LiveKit room join (participant_token) ------------->|
| <== agent participant: video + audio tracks live ====|
| |
| sendText(user turn, topic "lk.chat") -------------->|
| <== reply: voice + video on tracks, |
| reply text on "lk.transcription" ================|
| |
| POST /end | DELETE /v1/sessions/{id}
| ----------------------------->| -------------------->|

Two credentials, scoped very differently:

  • The secret key (sk_...) mints sessions and ends them. It lives only on your backend, in an environment variable. It must never reach a client bundle.
  • The participant token is minted per session by the gateway. The client gets only this, and it can do exactly one thing: join the LiveKit room for this one session. It can’t mint new sessions or spend money.

Your client talks only to your own backend (same-origin) and one LiveKit room (WebRTC). Your backend makes every sk_-authenticated call. The user’s turns go from the client straight to the agent over the room; your backend never relays chat.

The reference backend exposes two routes to the client. This is the complete server-side surface of a minimal integration:

app/api/mint/route.ts (excerpt)
export async function POST(req) {
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
mode: 'video',
}),
});
const s = await r.json();
if (!r.ok) return Response.json(s, { status: r.status });
return Response.json({
session_id: s.session_id,
livekit_url: s.livekit_url,
participant_token: s.participant_token,
chat: s.chat,
});
}
// app/api/end/route.ts (teardown)
export async function POST(req) {
const { session_id } = await req.json();
const r = await fetch(`https://api.2wai.ai/v1/sessions/${session_id}`, {
method: 'DELETE',
headers: { Authorization: `Bearer ${process.env.TWAI_SECRET_KEY}` },
});
return Response.json(await r.json().catch(() => ({})), { status: r.status });
}

Two routes: POST /mint (one call to gateway POST /v1/sessions) and POST /end (one call to DELETE /v1/sessions/{id}). Nothing else lives on the backend for a minimal integration.

Prefer an SDK; the raw path below is the shape every SDK encapsulates.

<script src="https://cdn.jsdelivr.net/npm/livekit-client@2/dist/livekit-client.umd.min.js"></script>
<video id="avatar" autoplay playsinline></video>
<form id="chat"><input id="in"/><button>Send</button></form>
<script type="module">
const { Room, RoomEvent } = LivekitClient;
const video = document.getElementById('avatar');
// 1. Mint.
const session = await (await fetch('/api/mint', { method: 'POST' })).json();
// 2. Join. 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 comes from the agent (the remote participant). Strip
// expression tags such as [curious] before display.
room.registerTextStreamHandler(session.chat.reply_topic, async (reader, participant) => {
if (participant.identity === room.localParticipant.identity) return;
const text = (await reader.readAll()).replace(/\[[^\]]*\]/g, '').replace(/\s{2,}/g, ' ').trim();
console.log('reply:', text);
});
await room.connect(session.livekit_url, session.participant_token);
// 3. Chat: the user's words as plain text, a text stream on lk.chat.
document.getElementById('chat').addEventListener('submit', async (e) => {
e.preventDefault();
const text = document.getElementById('in').value;
if (session.chat.format === 'unknown') throw new Error('unsupported chat format: unknown');
await room.localParticipant.sendText(text, { topic: session.chat.send_topic });
document.getElementById('in').value = '';
});
// 4. End the session when the user leaves.
window.addEventListener('pagehide', () => {
navigator.sendBeacon('/api/end', new Blob(
[JSON.stringify({ session_id: session.session_id })],
{ type: 'application/json' },
));
});
</script>

The avatar’s own brain (its persona from 2wai Studio) writes every reply, and its own voice speaks it. Your app sends the user’s words over the room; the agent does the rest.

Driving the avatar with your own LLM or your own TTS (/speak, /audio, /interrupt) is not available on the current gateway: those endpoints answer 409 not_available_on_livekit. See Bring your own brain for what is planned.

  • Create one session per conversation, not one per turn. Send every turn over the same room.
  • End the session when the user leaves (pagehide, then sendBeacon, then your /end route).
  • Let the LiveKit SDK reconnect on short blips; never mint a new session to reconnect.
  • Watch the x-twai-concurrent-sessions header on /v1/sessions responses so you can back off before hitting your cap.

See Sessions for lifecycle in depth and Limits & concurrency for cap and throttle behavior.