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.
Split-plane architecture
Section titled “Split-plane architecture”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.
Your backend: two routes
Section titled “Your backend: two routes”The reference backend exposes two routes to the client. This is the complete server-side surface of a minimal integration:
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 });}import osfrom fastapi import FastAPI, Requestimport httpx
app = FastAPI()SK = os.environ["TWAI_SECRET_KEY"]AVATAR = os.environ["AVATAR_ID"] # gen-... from catalog hydrate
@app.post("/mint")async def mint(): async with httpx.AsyncClient() as c: r = await c.post( "https://api.2wai.ai/v1/sessions", headers={"Authorization": f"Bearer {SK}"}, json={"avatar_id": AVATAR, "mode": "video"}, ) r.raise_for_status() s = r.json() return { "session_id": s["session_id"], "livekit_url": s["livekit_url"], "participant_token": s["participant_token"], "chat": s["chat"], }
@app.post("/end")async def end(req: Request): body = await req.json() async with httpx.AsyncClient() as c: r = await c.delete( f"https://api.2wai.ai/v1/sessions/{body['session_id']}", headers={"Authorization": f"Bearer {SK}"}, ) return {"status": r.status_code}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.
Your client: join, subscribe, chat
Section titled “Your client: join, subscribe, chat”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>Use the Flutter SDK. The client code reduces to one widget:
import 'package:twai_avatar_sdk/twai_avatar_sdk.dart';import 'package:twai_avatar_sdk_livekit/transport0.dart' as t0;
final rest = TwaiApiRestClient( baseUrl: Uri.parse('https://my-app.com/api'), // your mint proxy credentials: const AnonymousCredentials(),);
Future<t0.MintResult> mint() async { final r = await rest.createLiveKitSession( // gen-... id from catalog hydrate TwaiApiLiveKitSessionRequest(avatarId: 'gen-xxxxxxxxxxxxxxxxxxxxxxxxxx'), ); return t0.MintResultEnabled( url: r.livekitUrl.toString(), token: r.participantToken, room: r.roomName, );}
t0.TwaiTransport0Player( mint: mint, idleBuilder: (ctx) => NetworkVideoIdle(Uri.parse('https://.../idle.mp4')).build(ctx), onReplyText: (e) => print('avatar: ${e.text}'),);Full working app: apps/avatar_only_flutter.
import TwaiPlayer
TwaiPlayerView(mint: { let s = try await api.createSession(.init( avatarId: "gen-xxxxxxxxxxxxxxxxxxxxxxxxxx", mode: .video, transport: "livekit" )) return .enabled(url: s.livekitUrl, token: s.participantToken, room: s.roomName)}).onReady { handle in try? await handle.send("Hi!")}Full sample: ios-native/Samples/HelloAvatar.
Where the replies come from
Section titled “Where the replies come from”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.
Session hygiene
Section titled “Session hygiene”- Create one session per conversation, not one per turn. Send every turn over the same room.
- End the session when the user leaves (
pagehide, thensendBeacon, then your/endroute). - Let the LiveKit SDK reconnect on short blips; never mint a new session to reconnect.
- Watch the
x-twai-concurrent-sessionsheader on/v1/sessionsresponses so you can back off before hitting your cap.
See Sessions for lifecycle in depth and Limits & concurrency for cap and throttle behavior.