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

# Production checklist for deploying LemonSlice avatars

> Production checklist for deploying LemonSlice avatars

<video src="https://mintcdn.com/lemonslice/In5NRFQHKTq5DO3B/videos/hero.webm?fit=max&auto=format&n=In5NRFQHKTq5DO3B&q=85&s=50c8d52ef0dae51a2244d7f25be30d3a" controls />

Clip from our [home page playground demo](https://lemonslice.com/) — a LiveKit agent built with the checklist on this page.
We wrote these recommendations based on what we've learned helping customers ship production apps to millions of users.

***

## Use a ringing sound and UI

Avatar video takes a few seconds to initialize.
A phone-call metaphor works well: users understand ringing, pickup, conversation, and hang-up.
Our [Quickstart](https://github.com/lemonsliceai/lemonslice-examples/tree/main/03-livekit-app-python) provides a useful template.

<video src="https://mintcdn.com/lemonslice/Pwz3AnAucmyyVpeh/videos/ringing-example.webm?fit=max&auto=format&n=Pwz3AnAucmyyVpeh&q=85&s=debbe3232528149cf9b166694f05d012" controls />

***

## Handle avatar connect/disconnect events

> [!NOTE]
>
> **Read this section if you experience any of the following issues:**
>
> * Empty room (user sees black screen)
> * User gets no video or audio, but audio/text input are still active
> * Avatar disappears

Use the [`@lemonsliceai/avatar`](https://www.npmjs.com/package/@lemonsliceai/avatar) npm package on the frontend to detect when the avatar's first video frame has rendered, then switch from ringing to your **active call** UI. Listen for the avatar leaving to return to an **inactive** state so users can rejoin.

> [tab] LiveKit
>
> Also listen for `ParticipantDisconnected` when the avatar leaves (call completion, idle timeout, errors, etc.).
>
> > [!NOTE]
> >
> > On the backend, wait for the agent to join the room with `wait_for_agent` (Python) or `waitForParticipant` (Node), then call `generate_reply()` so the avatar does not sit idle before speaking. See the [LiveKit starter project](https://github.com/lemonsliceai/lemonslice-examples/tree/main/03-livekit-app-python) for a complete implementation.
>
> ```tsx theme={null}
> import { useState, useEffect } from "react";
> import { LiveKitRoom, RoomEvent, useRoomContext } from "@livekit/components-react";
> import { LiveKitAvatarReadyWatcher } from "@lemonsliceai/avatar/livekit-react";
>
> const AVATAR_IDENTITY = "lemonslice-avatar-agent";
>
> function AvatarCall({ serverUrl, token }: { serverUrl: string; token: string }) {
>   const [avatarReady, setAvatarReady] = useState(false);
>
>   return (
>     <LiveKitRoom serverUrl={serverUrl} token={token} connect>
>       <LiveKitAvatarReadyWatcher onReady={() => setAvatarReady(true)} />
>
>       {!avatarReady && <RingingUI />}
>       {avatarReady && <ActiveCallUI />}
>
>       <DisconnectHandler />
>     </LiveKitRoom>
>   );
> }
>
> function DisconnectHandler() {
>   const room = useRoomContext();
>
>   useEffect(() => {
>     const handleDisconnect = (participant) => {
>       if (participant.identity === AVATAR_IDENTITY) {
>         room.disconnect();
>         // Swap to inactive call UI — user can rejoin from here
>       }
>     };
>
>     room.on(RoomEvent.ParticipantDisconnected, handleDisconnect);
>     return () => room.off(RoomEvent.ParticipantDisconnected, handleDisconnect);
>   }, [room]);
>
>   return null;
> }
> ```

> [tab] Daily (Hosted)
>
> LemonSlice events arrive on Daily's `app-message` channel. When the agent participant leaves, handle `participant-left` to reset your UI.
>
> See the [hosted Daily starter project](https://github.com/lemonsliceai/lemonslice-examples/tree/main/01-hosted-daily-app) for a full React implementation.
>
> ```tsx theme={null}
> import { useState, useRef, useEffect, useCallback } from "react";
> import { useDailyEvent, useMediaTrack } from "@daily-co/daily-react";
> import { useAvatarReady } from "@lemonsliceai/avatar/react";
>
> function AvatarCall() {
>   const [avatarReady, setAvatarReady] = useState(false);
>   const avatarTrack = useMediaTrack("LemonSlice Agent", "video");
>
>   useAvatarReady(avatarTrack?.persistentTrack ?? null, {
>     onReady: () => setAvatarReady(true),
>   });
>
>   useDailyEvent(
>     "app-message",
>     useCallback((ev) => {
>       if (ev?.data?.type === "idle_timeout") {
>         // Agent stopped due to inactivity — swap to inactive call UI
>       }
>     }, [])
>   );
>
>   useDailyEvent("participant-left", (ev) => {
>     if (ev.participant?.user_name === "LemonSlice Agent") {
>       // Swap to inactive call UI — user can start a new room
>     }
>   });
>
>   return avatarReady ? <ActiveCallUI /> : <RingingUI />;
> }
> ```

***

## Handle room errors

> [!NOTE]
>
> **Read this section if you experience any of the following issues:**
>
> * Avatar fails to join a call
> * Crashed calls — avatar leaves or audio cuts out

> [tab] LiveKit
>
> Listen for `Disconnected` events to handle network errors, WebRTC failures, or join failures.
>
> ```javascript theme={null}
> import { DisconnectReason, RoomEvent } from "livekit-client";
>
> room.on(RoomEvent.Disconnected, (reason) => {
>   switch (reason) {
>     case DisconnectReason.CLIENT_INITIATED:
>       // User ended the call — swap to inactive call UI
>       break;
>     default:
>       // Unexpected disconnect — swap to inactive call UI
>   }
> });
> ```

> [tab] Daily (Hosted)
>
> Listen for `daily_error` app-messages and Daily's top-level error/left events.
>
> ```javascript theme={null}
> useDailyEvent("app-message", (ev) => {
>   if (ev?.data?.type === "daily_error") {
>     console.error(ev.data.error, ev.data.fatal);
>     // Swap to inactive call UI if fatal
>   }
> });
>
> useDailyEvent("error", (ev) => {
>   console.error("Daily error:", ev);
>   // Swap to inactive call UI
> });
> ```

***

## Catch pipeline errors

> [!NOTE]
>
> **Read this section if you experience any of the following issues:**
>
> * Avatar does not speak
> * Session dies unexpectedly

> [tab] LiveKit
>
> Subscribe to `AgentSession` error events on your backend. Errors with `err.recoverable == False` mean the pipeline is dead — end the session gracefully.
>
> ```python theme={null}
> @session.on("error")
> def on_session_error(ev: ErrorEvent) -> None:
>     err = ev.error
>     if isinstance(err, TTSError):
>         logger.error("AgentSession TTS error", exc_info=err.error)
>     elif isinstance(err, STTError):
>         logger.error("AgentSession STT error", exc_info=err.error)
>     elif isinstance(err, LLMError):
>         logger.error("AgentSession LLM error", exc_info=err.error)
>     else:
>         logger.error("AgentSession error", exc_info=err.error)
> ```

> [tab] Daily (Hosted)
>
> The Hosted Pipeline manages STT, LLM, and TTS for you. Monitor pipeline issues on the frontend via LemonSlice app-messages — especially `daily_error` and `video_generation_error`. See the [event reference](https://lemonslice.com/docs/hosted/integrations/daily-room-integration.md#receiving-events) for the full list.

***

## Handle startup failures

> [!NOTE]
>
> **Read this section if you experience any of the following issues:**
>
> * The call never connects

If the avatar fails to join, give users a way to exit gracefully instead of waiting indefinitely.

> [tab] LiveKit
>
> The [LiveKit starter project](https://github.com/lemonsliceai/lemonslice-examples/tree/main/03-livekit-app-python) monitors agent startup and can send a failure message to the room. Catch it on the frontend:
>
> ```javascript theme={null}
> const ROOM_MESSAGE_TOPIC = "lemonslice/message";
>
> room.on(RoomEvent.DataReceived, (payload, participant, kind, topic) => {
>   if (topic !== ROOM_MESSAGE_TOPIC) return;
>
>   try {
>     const message = JSON.parse(new TextDecoder().decode(payload));
>     if (message.type === "startup_failure") {
>       room.disconnect();
>       // Swap to inactive call UI — user can retry
>     }
>   } catch (err) {
>     console.error("Failed to parse data packet:", err);
>   }
> });
> ```

> [tab] Daily (Hosted)
>
> Set a client-side timeout after creating the room. If `bot_ready` has not fired within your threshold (e.g. 30 seconds), call `leave()` and show a retry UI. Also handle `daily_error` with `fatal: true` during startup.

***

## Check timeouts

> [!NOTE]
>
> **Read this section if you experience any of the following issues:**
>
> * Avatar suddenly exits a call
> * Calls end after the same number of minutes every time

Several timeouts can affect a session. Confirm each is set to the value you intend:

* **LemonSlice idle timeout** (default 60 seconds) — resets when the avatar is talking
* **LemonSlice GPU timeout** (default 30 minutes) — contact [support@lemonslice.com](mailto:support@lemonslice.com) if you need longer calls
* **Third-party timeouts** (LiveKit, Daily, ElevenLabs, etc.)

> [tab] LiveKit
>
> Set `idle_timeout` on `AvatarSession`:
>
> > [!WARNING]
> >
> > Setting `idle_timeout` to `-1` disables the LemonSlice idle timeout. Ensure sessions are properly terminated to avoid stale calls and runaway billing.
>
> ```python LiveKit (Python) theme={null}
> avatar = lemonslice.AvatarSession(
>     agent_image_url="https://example.com/avatar.jpg",
>     agent_prompt="a person talking.",
>     idle_timeout=600,
> )
> session_id = await avatar.start(session, room=ctx.room)
> ```
>
> ```javascript LiveKit (Node.js) theme={null}
> const avatar = new lemonslice.AvatarSession({
>   agentImageUrl: "https://example.com/avatar.jpg",
>   agentPrompt: "a person talking.",
>   idleTimeout: 600,
> });
> const sessionId = await avatar.start(session, room);
> ```
>
> ```python Pipecat (Python) theme={null}
> transport = LemonSliceTransport(
>     ...
>     session_request=LemonSliceNewSessionRequest(
>         agent_image_url="https://example.com/avatar.jpg",
>         agent_prompt="a person talking.",
>         idle_timeout=600,
>     ),
> )
> ```

> [tab] Daily (Hosted)
>
> Idle timeout is configured on your agent in the [LemonSlice web app](https://lemonslice.com/agents). When it fires, you'll receive an `idle_timeout` app-message — use it to reset your UI.
>
> End sessions explicitly with a `force-end` control event when the user hangs up:
>
> ```javascript theme={null}
> sendAppMessage({ event: "force-end" }, "*");
> ```

***

## Budget your latency

> [!NOTE]
>
> **Read this section if your avatar feels slow to respond** — including delayed replies after the user finishes speaking.

If the conversation lags, the bottleneck is usually **your LLM** — not LemonSlice video. Check LLM response times and tool-calling latency first.

![Agent pipeline latency](https://mintcdn.com/lemonslice/wLzWQq1Uo3Mp5DG5/images/livekit-diagram-2.png?fit=max\&auto=format\&n=wLzWQq1Uo3Mp5DG5\&q=85\&s=aafc121b35714408c20d449f2c7b24fa)

Humans expect a quick back-and-forth. Measure each pipeline step (STT, LLM, TTS, avatar video) and set a latency budget upfront. LLM times often creep from sub-second to three or four seconds as you add function calls, reasoning, or multimodal inputs. If a step blows your budget, move it off the critical path — run it async, set expectations with the user, or defer it.

### Use VAD to decrease perceived latency

Perceived latency matters more than absolute latency. Voice Activity Detection (VAD) lets you start reacting before a user has fully finished speaking, which effectively pulls your entire pipeline forward. Good turn detection means you can kick off generation as soon as intent is clear.

***

## Handle unstable networks

> [!NOTE]
>
> **Read this section if you experience any of the following issues:**
>
> * Avatar video stutters, freezes, or drops frames for some users
> * The same call is smooth on a strong connection and choppy on mobile or congested Wi-Fi

By default, LemonSlice encodes the avatar as one full-quality VP8 track. When a viewer's bandwidth can't sustain it, frames are dropped and the video stutters. LemonSlice can instead encode multiple quality layers of the avatar video. The room server then forwards each viewer the highest layer their connection can sustain and steps down as conditions change.

> [tab] LiveKit
>
> LemonSlice's LiveKit integration accepts three encoding options on `AvatarSession`: `video_codec`, `scalability_mode`, and `simulcast`. Pick one combination based on the connecting browser's codec support.
>
> * **VP9 with SVC** when [`supportsVP9()`](https://docs.livekit.io/reference/client-sdk-js/functions/supportsVP9.html) is true. Set `video_codec="vp9"` and `scalability_mode="L3T3_KEY"`.
> * **VP8 with simulcast** for every other browser. Set `video_codec="vp8"` and `simulcast=True`.
>
> **1. Detect VP9 support on the frontend**
>
> Call LiveKit's [`supportsVP9()`](https://docs.livekit.io/reference/client-sdk-js/functions/supportsVP9.html) helper and include the result in the request that starts your LiveKit session with the LemonSlice avatar.
>
> ```typescript theme={null}
> import { supportsVP9 } from "livekit-client";
>
> await fetch("/api/start-session", {
>   method: "POST",
>   headers: { "Content-Type": "application/json" },
>   body: JSON.stringify({ supports_vp9: supportsVP9() }),
> });
> ```
>
> **2. Pass the encoding options to AvatarSession**
>
> Pass VP9 and SVC when the viewer supports VP9. Otherwise pass VP8 and simulcast.
>
> ```python Python theme={null}
> def avatar_video_options(supports_vp9: bool) -> dict:
>     if supports_vp9:
>         return {"video_codec": "vp9", "scalability_mode": "L3T3_KEY"}
>     return {"video_codec": "vp8", "simulcast": True}
>
>
> avatar = lemonslice.AvatarSession(
>     agent_image_url="https://example.com/avatar.jpg",
>     agent_prompt="a person talking.",
>     **avatar_video_options(supports_vp9),
> )
> session_id = await avatar.start(session, room=ctx.room)
> ```
>
> ```javascript Node.js theme={null}
> function avatarVideoOptions(supportsVp9) {
>   if (supportsVp9) {
>     return { videoCodec: "vp9", scalabilityMode: "L3T3_KEY" };
>   }
>   return { videoCodec: "vp8", simulcast: true };
> }
>
> const avatar = new lemonslice.AvatarSession({
>   agentImageUrl: "https://example.com/avatar.jpg",
>   agentPrompt: "a person talking.",
>   extraPayload: avatarVideoOptions(supportsVp9),
> });
> const sessionId = await avatar.start(session, room);
> ```
>
> On the WebSocket API, LemonSlice accepts the same `video_codec`, `scalability_mode`, and `simulcast` fields on [`livekit_properties`](https://lemonslice.com/docs/websocket).

***

## Match the audio sample rate to your TTS

> [!NOTE]
>
> **Read this section if you experience any of the following issues:**
>
> * The avatar's voice sounds duller or more muffled than the raw TTS output
> * Audio quality drops when you switch from a voice-only agent to the avatar

LemonSlice publishes avatar audio at the session's `audio_sample_rate`, which defaults to `16000`. If your TTS outputs 24 kHz audio, set `audio_sample_rate` to `24000` so LemonSlice passes the audio through untouched instead of downsampling it. Supported values are `16000` and `24000`.

If the incoming audio does not match `audio_sample_rate`, LemonSlice resamples it to the session rate. Nothing breaks, but you don't get the quality gain.

> [tab] LiveKit
>
> > [!WARNING]
> >
> > As of October 30, 2026, `audioSampleRate` is not in the published Node.js plugin. Use [this pull request](https://github.com/livekit/agents-js/pull/2801) until it is merged.
>
> > [!NOTE]
> >
> > On the Python plugin, `audio_sample_rate` requires `livekit-agents` 1.8.10 or later.
>
> Configure your TTS for the same rate you pass to the LemonSlice `AvatarSession`.
>
> ```python Python theme={null}
> session = AgentSession(
>     tts=elevenlabs.TTS(encoding="pcm_24000"),
>     ...
> )
>
> avatar = lemonslice.AvatarSession(
>     agent_image_url="https://example.com/avatar.jpg",
>     audio_sample_rate=24000,
> )
> session_id = await avatar.start(session, room=ctx.room)
> ```
>
> ```javascript Node.js theme={null}
> const session = new voice.AgentSession({
>   tts: new elevenlabs.TTS({ encoding: "pcm_24000" }),
>   ...
> });
>
> const avatar = new lemonslice.AvatarSession({
>   agentImageUrl: "https://example.com/avatar.jpg",
>   audioSampleRate: 24000,
> });
> const sessionId = await avatar.start(session, room);
> ```

> [tab] Pipecat
>
> > [!NOTE]
> >
> > `audio_sample_rate` requires `pipecat-ai` 1.15.0 or later.
>
> Set `audio_sample_rate` on the LemonSlice session request and use the same rate for the pipeline's `audio_out_sample_rate`.
>
> ```python theme={null}
> transport = LemonSliceTransport(
>     ...
>     session_request=LemonSliceNewSessionRequest(
>         agent_image_url="https://example.com/avatar.jpg",
>         audio_sample_rate=24000,
>     ),
> )
>
> task = PipelineTask(
>     pipeline,
>     params=PipelineParams(
>         # User input audio not to be confused with TTS output audio
>         audio_in_sample_rate=16000,
>         # Avatar output audio
>         audio_out_sample_rate=24000,
>     ),
> )
> ```

> [tab] Agora
>
> Agora streams whatever audio your TTS returns straight to LemonSlice. Set `audio_sample_rate` in the `avatar` block to match the TTS output rate configured in the `tts` block:
>
> ```json theme={null}
> {
>   "tts": {
>     "vendor": "elevenlabs",
>     "params": {
>       "model_id": "eleven_flash_v2_5",
>       "voice_id": "<elevenlabs_voice_id>",
>       "sample_rate": 24000
>     }
>   },
>   "avatar": {
>     "vendor": "generic",
>     "enable": true,
>     "params": {
>       "api_base_url": "https://lemonslice.com/api/liveai/agora",
>       "avatar_id": "lemonslice",
>       "agent_image_url": "https://example.com/avatar.jpg",
>       "audio_sample_rate": 24000,
>       ...
>     }
>   }
> }
> ```

> [tab] WebSocket
>
> Pass `audio_sample_rate` when creating the session, then send every audio chunk with a matching `sampleRate`:
>
> ```bash theme={null}
> curl --request POST \
>   --url "https://lemonslice.com/api/liveai/sessions" \
>   --header "X-API-Key: $LEMONSLICE_API_KEY" \
>   --header "Content-Type: application/json" \
>   --data '{
>     "transport_type": "websocket-livekit",
>     "agent_image_url": "https://example.com/avatar.jpg",
>     "audio_sample_rate": 24000,
>     "livekit_properties": { ... }
>   }'
> ```
>
> ```javascript theme={null}
> socket.send(JSON.stringify({
>   command: "audio",
>   audio: "<base64_pcm16_mono>",
>   sampleRate: 24000,
> }));
> ```

***

## Optional: Show a transcription

Displaying transcription can improve usability, especially for catching STT errors and making the agent's timing feel more predictable. Users can see when their speech has been "accepted," which reduces ambiguity around when the agent will respond.

However, transcription introduces its own UX risks. Many pipelines expose both fast, low-accuracy interim results and slower, higher-accuracy final transcripts (e.g., `interim_results=false` to suppress partials for Deepgram). When both are surfaced, users can see text rapidly change or correct itself, which feels unstable and undermines trust. We recommend disabling interim results if you choose to show transcriptions.


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