> ## Documentation Index
> Fetch the complete documentation index at: https://docs.simli.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Custom JS Simli Client

> Talk to Simli's streaming API from your own JavaScript: the session token, a peer-to-peer or LiveKit connection, audio and live controls

This page builds a browser client for Simli's raw streaming protocol, the one the [JavaScript](https://docs.simli.com/api-reference/javascript.md) and [Python](https://docs.simli.com/api-reference/python.md) SDKs speak for you. It takes the same steps as Simli's own reference clients. Use it when you need your own WebRTC code, or Simli on a platform without an SDK.

> [!TIP]
>
> If you don't need your own client, the [JavaScript SDK](https://docs.simli.com/api-reference/javascript.md) does all of this for you.

## What you need

* A Simli API key, from your [Simli dashboard](https://app.simli.com)
* A server route that creates session tokens, so your API key never reaches the browser
* Your own WebRTC code: the browser's `RTCPeerConnection` for a peer-to-peer session, or [livekit-client](https://github.com/livekit/client-sdk-js) (`npm install livekit-client`) for a LiveKit session

New to WebRTC or raw audio? The [WebRTC](https://docs.simli.com/api-reference/webrtc-info.md) and [Audio formats](https://docs.simli.com/api-reference/audio-info.md) guides cover the basics.

## How a session runs

Each session has one WebSocket to Simli. It carries the connection setup, your audio and your controls, while the avatar's video and voice come back over WebRTC. There are two transports, and they differ only in how that media connects:

* **Peer to peer** (`/compose/webrtc/p2p`): you create an `RTCPeerConnection` and send Simli its offer, and Simli answers it.
* **LiveKit** (`/compose/webrtc/livekit`): Simli puts the avatar in a LiveKit room and sends you a token to join it.

A session goes like this:

1. Your server creates a session token with [`POST /compose/token`](https://docs.simli.com/api-reference/endpoint/webrtc/startAudioToVideoSession). For peer to peer, it also gets ICE servers from [`GET /compose/ice`](https://docs.simli.com/api-reference/endpoint/webrtc/getIceServers).
2. The browser opens the WebSocket with the token.
3. Simli sends `{"destination", "session_id"}`.
4. **Peer to peer:** you send your offer as the first message, and Simli sends back `{"type": "answer", "sdp"}`. **LiveKit:** Simli sends `{"livekit_url", "livekit_token"}`, and you join that room.
5. Simli sends `{"video_metadata": {"fps", "width", "height"}}`, then `START`.
6. You send audio and controls. Simli answers each message with `ACK`, and sends `SPEAK` and `SILENT` as the avatar starts and stops talking.
7. When the session ends, Simli sends `ENDFRAME:<frame>`, `CLOSING REASON: <reason>` and `STOP`, and closes the WebSocket.

The browser code below all goes in one module, `simli-raw.js`.

## 1. Create the session token on your server

Creating a token takes your API key, so do it on your server and send only the token, and the ICE servers, to the browser. This route is for Next.js (App Router). On other backends, make the same two requests with your key in the `x-simli-api-key` header.

```typescript app/api/simli-session/route.ts theme={null}
const SIMLI_API = "https://api.simli.ai";

// Runs on your server, so SIMLI_API_KEY never reaches the browser.
export async function POST() {
	const apiKey = {"x-simli-api-key": process.env.SIMLI_API_KEY!};
	const [tokenRes, iceRes] = await Promise.all([
		fetch(`${SIMLI_API}/compose/token`, {
			method: "POST",
			headers: {...apiKey, "Content-Type": "application/json"},
			body: JSON.stringify({
				faceId: "14c60d62-6ebf-424d-b626-1f4f91c33b04", // Simli's default Trinity-2 face
				handleSilence: true,
				maxSessionLength: 600, // seconds
				maxIdleTime: 180, // seconds
			}),
		}),
		// ICE servers for a peer-to-peer session. LiveKit sessions don't need them.
		fetch(`${SIMLI_API}/compose/ice`, {headers: apiKey}),
	]);
	if (!tokenRes.ok) return new Response(await tokenRes.text(), {status: tokenRes.status});
	const {session_token, warnings} = await tokenRes.json();
	if (warnings?.length) console.warn("Simli:", warnings);
	// A public STUN server if Simli's ICE servers can't be had
	const iceServers = iceRes.ok ? await iceRes.json() : [{urls: ["stun:stun.l.google.com:19302"]}];
	return Response.json({session_token, iceServers});
}
```

Send the plain face ID, with no `model` field. A token is valid for 5 minutes, so create a new one for each session, right before you connect. On an error, such as an invalid face ID or field, Simli answers with an error status and its reason in the body, and the route passes both on. `warnings` lists anything Simli accepted but changed, such as a background that isn't yours.

> [!WARNING]
>
> Anyone who can reach your token route can start a session on your account. Put it behind your own sign-in or rate limiting before you go to production.

### Trinity-2 options

With a [Trinity-2](https://docs.simli.com/api-reference/trinity-2.md) face, the token request can also set the video's size, where the avatar sits, the starting camera and an uploaded background or foreground. All of them are optional:

```json POST /compose/token theme={null}
{
	"faceId": "14c60d62-6ebf-424d-b626-1f4f91c33b04",
	"streaming_width": 1366,
	"streaming_height": 768,
	"avatar_position_x": 0.5,
	"avatar_position_y": 1.0,
	"camera": {"zoom": 1.2, "orbit_y_off": 15},
	"background_id": "6f1c2a9e-1b2c-4d3e-8f90-0123456789ab",
	"foreground_id": "YOUR_FOREGROUND_ID"
}
```

| Fields | See |
| - | - |
| `streaming_width`, `streaming_height`, `avatar_position_x`, `avatar_position_y` | [Framing the video](https://docs.simli.com/api-reference/trinity-2.md#framing-the-video) |
| `camera` | [The starting camera](https://docs.simli.com/api-reference/trinity-2/camera.md#the-starting-camera) |
| `background_id`, `foreground_id` | [Starting a session with one](https://docs.simli.com/api-reference/trinity-2/backgrounds.md#starting-a-session-with-one). They take the id of an image you uploaded, not the image. |

## 2. Open the WebSocket

```javascript simli-raw.js theme={null}
const SIMLI_WS = "wss://api.simli.ai";

// Your route from step 1
async function getSession() {
	const res = await fetch("/api/simli-session", {method: "POST"});
	if (!res.ok) throw new Error(`Couldn't create a Simli session: ${await res.text()}`);
	return res.json(); // {session_token, iceServers}
}

function openSocket(path, params) {
	const url = new URL(SIMLI_WS + path);
	for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);
	const ws = new WebSocket(url);
	const opened = new Promise((resolve, reject) => {
		ws.addEventListener("open", resolve, {once: true});
		ws.addEventListener("error", () => reject(new Error("Simli WebSocket failed")), {once: true});
	});
	return {ws, opened};
}
```

| Query parameter | Transport | Meaning |
| - | - | - |
| `session_token` | Both | The token from step 1. |
| `enableSFU` | Peer to peer | `true`, the default, relays the media through Cloudflare's network for reliability. `false` connects you straight to the Simli server. |

## 3. Connect the media

> [tab] Peer to peer
>
> ```javascript simli-raw.js theme={null}
> export async function startP2P(video, audio, handlers = {}) {
> 	const {session_token, iceServers} = await getSession();
>
> 	// Open the WebSocket first: Simli sets the session up while your ICE candidates gather.
> 	const {ws, opened} = openSocket("/compose/webrtc/p2p", {session_token, enableSFU: "true"});
>
> 	// Receive only: Simli sends one audio and one video track, and you send nothing over WebRTC.
> 	const pc = new RTCPeerConnection({iceServers});
> 	pc.addTransceiver("audio", {direction: "recvonly"});
> 	pc.addTransceiver("video", {direction: "recvonly"});
> 	pc.addEventListener("track", (evt) => {
> 		(evt.track.kind === "video" ? video : audio).srcObject = evt.streams[0];
> 	});
>
> 	const session = {ws, pc, handlers, closed: false};
> 	listen(session); // sets Simli's answer as the remote description (step 4)
> 	pc.addEventListener("connectionstatechange", () => {
> 		if (pc.connectionState === "failed") close(session);
> 	});
>
> 	try {
> 		await pc.setLocalDescription(await pc.createOffer());
> 		await iceGathered(pc);
> 		await opened;
> 		// The offer must be the first message you send.
> 		ws.send(JSON.stringify({type: pc.localDescription.type, sdp: pc.localDescription.sdp}));
> 	} catch (error) {
> 		close(session);
> 		throw error;
> 	}
> 	return session;
> }
>
> // Simli takes no trickled candidates, so they go in the offer. Wait until gathering
> // completes, or until no new candidate has come for 250 ms.
> function iceGathered(pc, quietMs = 250) {
> 	return new Promise((resolve) => {
> 		if (pc.iceGatheringState === "complete") return resolve();
> 		let timer = setTimeout(resolve, quietMs);
> 		pc.addEventListener("icecandidate", (evt) => {
> 			clearTimeout(timer);
> 			if (evt.candidate) timer = setTimeout(resolve, quietMs);
> 			else resolve(); // gathering is complete
> 		});
> 	});
> }
> ```
>
> Send the offer within 20 seconds of opening the WebSocket. Otherwise Simli ends the session with `STOP REASON: failed to receive RTC Offer`.

> [tab] LiveKit
>
> ```javascript simli-raw.js theme={null}
> import {Room, RoomEvent, Track} from "livekit-client";
>
> export async function startLiveKit(video, audio, handlers = {}) {
> 	const {session_token} = await getSession();
> 	const {ws, opened} = openSocket("/compose/webrtc/livekit", {session_token});
>
> 	// adaptiveStream off, as in Simli's reference client: the video isn't paused or
> 	// scaled down to fit the element.
> 	const room = new Room({adaptiveStream: false});
> 	room.on(RoomEvent.TrackSubscribed, (track) => {
> 		if (track.kind === Track.Kind.Video) track.attach(video);
> 		else if (track.kind === Track.Kind.Audio) track.attach(audio);
> 	});
> 	room.on(RoomEvent.TrackUnsubscribed, (track) => track.detach());
>
> 	const session = {ws, room, handlers, closed: false};
> 	listen(session); // joins the room when Simli says where (step 4)
> 	room.on(RoomEvent.Disconnected, () => close(session));
>
> 	try {
> 		await opened;
> 	} catch (error) {
> 		close(session);
> 		throw error;
> 	}
> 	return session;
> }
> ```
>
> There's no offer to send. Simli sends `{"livekit_url", "livekit_token"}`, and sends `START` once you've joined. Connect to that URL rather than a cached one, because it can change from session to session. If you haven't joined within 60 seconds, Simli ends the session with `CLIENT NOT CONNECTED TO LIVEKIT ROOM, TERMINATED SESSION`. The token can subscribe but not publish: your audio still goes over the WebSocket.
>
> If you only use peer to peer, leave out `startLiveKit` and the `livekit-client` import.

## 4. Handle Simli's messages

Everything Simli sends on the WebSocket is text. The JSON messages set up the connection, and the rest are plain strings.

```javascript simli-raw.js theme={null}
function listen(session) {
	const {ws, handlers} = session;
	let closingReason = null;
	ws.addEventListener("message", async ({data}) => {
		if (data.startsWith("{")) {
			const message = JSON.parse(data);
			try {
				if (message.destination) console.info("Simli session", message.session_id, "on", message.destination);
				else if (message.type === "answer") await session.pc.setRemoteDescription(message); // peer to peer
				else if (message.livekit_url) await session.room.connect(message.livekit_url, message.livekit_token); // LiveKit
				else if (message.video_metadata) handlers.onVideo?.(message.video_metadata); // {fps, width, height}
			} catch (error) {
				handlers.onError?.(String(error));
				close(session);
			}
		} else if (data === "START") handlers.onStart?.(); // send audio from now on
		else if (data === "ACK") return; // one for each message you send
		else if (data === "SPEAK" || data === "SILENT") handlers.onSpeaking?.(data === "SPEAK");
		else if (data.startsWith("ENDFRAME:")) return; // the number of the last frame
		else if (data.startsWith("CLOSING REASON: ")) closingReason = data.slice("CLOSING REASON: ".length);
		else if (data === "STOP") {
			handlers.onStop?.(closingReason);
			close(session);
		} else if (/^(ERROR|RATE LIMIT|STOP REASON|CLIENT NOT CONNECTED)/.test(data)) {
			handlers.onError?.(data);
			close(session);
		} else handlers.onNotice?.(data); // a camera, background or foreground notice: the session goes on
	});
	ws.addEventListener("close", () => close(session));
}

// Ends the session at once. Safe to call more than once.
export function close(session) {
	if (session.closed) return;
	session.closed = true;
	session.ws.close();
	session.pc?.close();
	session.room?.disconnect();
}
```

| Message | When |
| - | - |
| `{"destination": ..., "session_id": ...}` | First, once the WebSocket is open. Include it when you report an issue. |
| `{"type": "answer", "sdp": ...}` | Peer to peer, after your offer. |
| `{"livekit_url": ..., "livekit_token": ...}` | LiveKit. Join this room. |
| `{"video_metadata": {"fps", "width", "height"}}` | Just before `START`. The video's frame rate and size. |
| `START` | The session is ready. Send audio and controls from now on. |
| `ACK` | After each message you send. |
| `SPEAK`, `SILENT` | The avatar started or stopped talking. |
| `WARNING: ...` | A [camera](https://docs.simli.com/api-reference/trinity-2/camera.md#moving-the-camera-during-a-session) value was outside its supported range, and was applied anyway. |
| Other plain text | A camera, [background or foreground](https://docs.simli.com/api-reference/trinity-2/backgrounds.md#swapping-it-during-a-session) message wasn't applied, for example `Invalid camera override received`. The session goes on. |
| `ERROR: <reason>` | Simli refused the session or couldn't run it, for example `ERROR: SESSION_TOKEN_EXPIRED`. Start again with a new token. |
| `RATE LIMIT REACHED! ...` | You have too many sessions open. Close the ones you don't use. |
| `STOP REASON: ...`, `CLIENT NOT CONNECTED TO LIVEKIT ROOM, ...` | You didn't send the offer, or join the room, in time. |
| `ENDFRAME:<frame>`, `CLOSING REASON: <reason>`, `STOP` | The session is over, and Simli closes the WebSocket. |

The closing reasons you'll see most often:

| Reason | Why |
| - | - |
| `User Sent Final Chunk` | You sent `DONE`, and the avatar finished your audio. |
| `IDLE` | Nothing but silence for `maxIdleTime` seconds. With `handleSilence: false`, no audio at all for 30 seconds. |
| `MAX` | The session reached `maxSessionLength` seconds. |
| `RATE LIMIT EXCEEDED` | You have too many sessions open. |
| `WebRTC Disconnected...` | Peer to peer: the media connection dropped. |
| `Client disconnected from LK room` | LiveKit: you left the room. |

## 5. Send audio

Audio goes over the WebSocket as binary messages of raw PCM16: signed 16-bit little-endian samples, 16 kHz, mono, with no file header. Start sending it only after `START`.

```javascript simli-raw.js theme={null}
const CHUNK_BYTES = 6000; // 3000 samples, under 0.2 seconds of audio

// pcm: a Uint8Array of PCM16, 16 kHz, mono audio
export function sendAudio(ws, pcm) {
	for (let i = 0; i < pcm.length; i += CHUNK_BYTES) ws.send(pcm.subarray(i, i + CHUNK_BYTES));
}

// Drops the audio the avatar hasn't spoken yet, for example when the user interrupts
export function interrupt(ws) {
	ws.send("SKIP");
}

// Drops the audio the avatar hasn't spoken yet, and plays this instead, right away
export function playNow(ws, pcm) {
	const message = new Uint8Array(14 + pcm.length);
	message.set(new TextEncoder().encode("PLAY_IMMEDIATE"), 0);
	message.set(pcm, 14);
	ws.send(message);
}
```

* **Queueing:** audio plays after whatever you sent before it. You can send it faster than real time, and Simli buffers it.
* **Chunks:** chunks of about 6000 bytes work well. Split on whole samples, so every chunk is an even number of bytes.
* **Gaps:** with `handleSilence: true` (the default), Simli fills the gaps between your audio with silence, so the avatar keeps moving. With `false`, the video waits for your audio. See [Choosing `handleSilence`](https://docs.simli.com/api-reference/javascript#choosing-handlesilence).
* **Sources:** to turn a file into PCM16, use `ffmpeg -i speech.mp3 -f s16le -acodec pcm_s16le -ar 16000 -ac 1 speech.pcm`. For speech from a TTS API, ask it for 16 kHz PCM. See [Audio formats](https://docs.simli.com/api-reference/audio-info.md).

## 6. Move the camera and swap the background

With a [Trinity-2](https://docs.simli.com/api-reference/trinity-2.md) face, you can move the camera and change the background or foreground while the session runs. Other faces answer these messages with a notice and ignore them.

```javascript simli-raw.js theme={null}
const CAMERA_FIELDS = [
	"pos_y_off", "pos_x_off", "pos_z_off", "zoom",
	"rot_x_off", "rot_y_off", "rot_z_off",
	"orbit_x_off", "orbit_y_off",
];

// CAM_ + little-endian float32s, y before x. Replaces the whole camera: fields left out are
// neutral. Glides over lerpSeconds if it's above 0, and cuts otherwise.
export function sendCamera(ws, camera = {}, lerpSeconds = 0) {
	const values = CAMERA_FIELDS.map((field) => camera[field] ?? (field === "zoom" ? 1 : 0));
	const lerpAt = 4 + 4 * values.length;
	const message = new Uint8Array(lerpAt + (lerpSeconds > 0 ? 8 : 0));
	const view = new DataView(message.buffer);
	message.set(new TextEncoder().encode("CAM_"), 0);
	values.forEach((value, i) => view.setFloat32(4 + 4 * i, value, true));
	if (lerpSeconds > 0) {
		message.set(new TextEncoder().encode("LERP"), lerpAt);
		view.setFloat32(lerpAt + 4, lerpSeconds, true);
	}
	ws.send(message);
}

// The nil UUID goes back to the avatar's own background, or takes the foreground away.
const NO_ASSET = "00000000-0000-0000-0000-000000000000";

// The id of one of your uploaded backgrounds, or null for the avatar's own
export function setBackground(ws, backgroundId) {
	ws.send("BG_" + (backgroundId ?? NO_ASSET));
}

// The id of one of your uploaded foregrounds, or null for none
export function setForeground(ws, foregroundId) {
	ws.send("FG_" + (foregroundId ?? NO_ASSET));
}
```

```javascript theme={null}
sendCamera(session.ws, {orbit_y_off: 20, zoom: 1.3}, 1.5); // orbit right and zoom in, over 1.5 seconds
sendCamera(session.ws); // cut back to the avatar's own framing
setBackground(session.ws, "6f1c2a9e-1b2c-4d3e-8f90-0123456789ab");
setForeground(session.ws, null);
```

`BG_` and `FG_` take only an id from [`POST /assets/backgrounds` or `/assets/foregrounds`](https://docs.simli.com/api-reference/trinity-2/backgrounds#uploading-one), never an image. For the camera fields and their ranges, see [Camera](https://docs.simli.com/api-reference/trinity-2/camera.md#moving-the-camera-during-a-session). For how a new background loads, see [Backgrounds](https://docs.simli.com/api-reference/trinity-2/backgrounds.md#swapping-it-during-a-session).

## 7. End the session

```javascript simli-raw.js theme={null}
// Lets the avatar finish the audio it has, then ends the session. Simli sends STOP when it's done.
export function finish(ws) {
	ws.send("DONE");
}
```

After `DONE`, Simli plays the audio you've sent, ignores any you send after it, and then ends the session with `CLOSING REASON: User Sent Final Chunk` and `STOP`. To end the session at once instead, call `close(session)` from step 4: closing the WebSocket ends it, and so does closing the peer connection or leaving the room.

## Putting it together

```html index.html theme={null}
<!-- muted: the voice plays through the <audio> element -->
<video id="video" autoplay playsinline muted></video>
<audio id="audio" autoplay></audio>
<button id="start">Start</button>
<input id="file" type="file" accept=".pcm" />
<button id="send">Send audio</button>
<button id="interrupt">Interrupt</button>
<button id="finish">Finish</button>
<script type="module" src="main.js"></script>
```

```javascript main.js theme={null}
import {startP2P, sendAudio, interrupt, finish, close} from "./simli-raw.js";

const video = document.getElementById("video");
const audio = document.getElementById("audio");
let session = null;

document.getElementById("start").onclick = async () => {
	// startLiveKit(video, audio, handlers) takes the same arguments
	session = await startP2P(video, audio, {
		onStart: () => console.log("Simli is ready for audio"),
		onSpeaking: (speaking) => console.log(speaking ? "Speaking" : "Silent"),
		onNotice: (notice) => console.warn("Simli:", notice),
		onError: (error) => console.error("Simli:", error),
		onStop: (reason) => console.log("Session ended:", reason),
	});
};

// A raw PCM16, 16 kHz, mono file, such as the ffmpeg output from step 5
document.getElementById("send").onclick = async () => {
	const file = document.getElementById("file").files[0];
	sendAudio(session.ws, new Uint8Array(await file.arrayBuffer()));
};
document.getElementById("interrupt").onclick = () => interrupt(session.ws);
document.getElementById("finish").onclick = () => finish(session.ws);
addEventListener("beforeunload", () => session && close(session));
```

Serve these through your bundler or framework, since `simli-raw.js` imports `livekit-client`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.