Skip to content

Quickstart

This walks through the minimum needed to see your avatar talk on Transport 0 (LiveKit): a tiny backend that mints a session, and a plain HTML page that joins the LiveKit room, renders the avatar’s video and audio tracks, and sends what you type straight to the avatar over the room.

The avatar answers with its own brain and its own voice, the ones set on it in 2wai Studio. You send the user’s words; the avatar decides what to say back.

  • A 2wai secret key (sk_...) from the developer portal (see Getting access).
  • An avatar_id. For a key from the developer portal this is a gen id: gen- followed by 26 lowercase letters and digits. Get it from the avatar_id field of catalog hydrate, GET /v1/avatars/{owner}/{name}. The avatar’s owner must have exposed it to the API in 2wai Studio.
  • Node.js 18+ or Python 3.10+ for the backend.
  • A browser, plus LiveKit’s web SDK (livekit-client 2.x from npm, or the CDN build used below).

Step 1: Mint a LiveKit session on your server

Section titled “Step 1: Mint a LiveKit session on your server”

Your backend calls POST /v1/sessions with your secret key. The gateway answers 201 with everything the client needs to join the room. LiveKit is the only transport and the default, so you do not need to send transport at all.

server.js
import express from 'express';
const app = express();
app.use(express.json());
// sk_... read from an environment variable, never hard-coded or shipped
// to a client.
const TWAI_SECRET_KEY = process.env.TWAI_SECRET_KEY;
app.post('/session', async (req, res) => {
const response = await fetch('https://api.2wai.ai/v1/sessions', {
method: 'POST',
headers: {
Authorization: `Bearer ${TWAI_SECRET_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
avatar_id: 'gen-xxxxxxxxxxxxxxxxxxxxxxxxxx', // from catalog hydrate
mode: 'video',
}),
});
if (!response.ok) {
const body = await response.json();
return res.status(response.status).json(body);
}
// 201 response:
// { session_id, transport: "livekit", livekit_url, room_name,
// participant_token, agent_identity, expires_at: null,
// chat: { send_topic: "lk.chat", format, reply_topic: "lk.transcription" } }
const session = await response.json();
// Hand only the fields the client needs. TWAI_SECRET_KEY stays here.
res.json({
session_id: session.session_id,
livekit_url: session.livekit_url,
participant_token: session.participant_token,
chat: session.chat,
});
});
app.listen(3000, () => console.log('listening on :3000'));

Add a route that ends the session when the user is done. A session you never end stays open, and counts against your concurrency cap, until it is reaped for being idle.

server.js (continued)
app.post('/end', async (req, res) => {
const { session_id } = req.body;
const r = await fetch(`https://api.2wai.ai/v1/sessions/${session_id}`, {
method: 'DELETE',
headers: { Authorization: `Bearer ${TWAI_SECRET_KEY}` },
});
res.status(r.status).end();
});

Step 2: Join the room and talk to the avatar

Section titled “Step 2: Join the room and talk to the avatar”

This page asks your /session route for a session, joins the LiveKit room with the official livekit-client library, plays the agent’s video and audio tracks, and sends each line you type to the agent as a text stream on topic lk.chat. The agent’s reply text comes back as a text stream on lk.transcription; its voice and lip-synced video arrive on the tracks. The agent is the other participant in the room: the first remote participant to join, usually within about a second of you connecting.

Send the user’s words as they are: every avatar reads plain text, and chat.format in the session response says text. If it ever says unknown, do not send; see Chat formats.

index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>2wai avatar quickstart</title>
<script src="https://cdn.jsdelivr.net/npm/livekit-client@2/dist/livekit-client.umd.min.js"></script>
</head>
<body>
<video id="avatar" autoplay playsinline style="max-width: 480px;"></video>
<p id="reply"></p>
<form id="chat-form">
<input id="chat-input" type="text" placeholder="Say something..." autocomplete="off" />
<button type="submit">Send</button>
</form>
<script type="module">
const { Room, RoomEvent } = LivekitClient;
const video = document.getElementById('avatar');
const replyEl = document.getElementById('reply');
const form = document.getElementById('chat-form');
const input = document.getElementById('chat-input');
// Ask YOUR backend to mint a session. It holds the sk_; this page never does.
const res = await fetch('/session', { method: 'POST' });
const session = await res.json();
// Transport 0: adaptiveStream + dynacast MUST be off for 2wai agents.
const room = new Room({ adaptiveStream: false, dynacast: false });
// The agent joins the room; play its video + audio when its tracks arrive.
room.on(RoomEvent.TrackSubscribed, (track) => {
if (track.kind === 'video') track.attach(video);
else if (track.kind === 'audio') track.attach(); // hidden <audio>, plays
});
// The agent's reply text arrives as a text stream on chat.reply_topic
// ("lk.transcription"). It can contain expression tags like [curious];
// strip [...] before showing it.
room.registerTextStreamHandler(session.chat.reply_topic, async (reader, participant) => {
if (participant.identity === room.localParticipant.identity) return; // ignore our own
const raw = await reader.readAll();
replyEl.textContent = raw.replace(/\[[^\]]*\]/g, '').replace(/\s{2,}/g, ' ').trim();
});
await room.connect(session.livekit_url, session.participant_token);
form.addEventListener('submit', async (event) => {
event.preventDefault();
const text = input.value.trim();
if (!text) return;
if (session.chat.format === 'unknown') {
throw new Error('this room did not say how it reads a turn; end the session and contact support');
}
input.value = '';
// The user's words, as plain text, on chat.send_topic ("lk.chat").
await room.localParticipant.sendText(text, { topic: session.chat.send_topic });
});
// End the session when the user leaves.
window.addEventListener('pagehide', () => {
navigator.sendBeacon('/end', new Blob(
[JSON.stringify({ session_id: session.session_id })],
{ type: 'application/json' },
));
});
</script>
</body>
</html>

Serve index.html from the same backend (or any static host that can reach /session and /end), open it, and the avatar appears a couple of seconds after the room connects. Type something, hit send, and the avatar answers in its own voice.

  1. Run your server (node server.js or uvicorn server:app --reload).
  2. Open index.html in a browser.
  3. Type a message, hit send.