> ## 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.

# LiveKit Integration

> Connect to a LemonSlice Avatar via LiveKit's Agents realtime framework

## Overview

[LiveKit Agents](https://docs.livekit.io/agents/) provides a realtime framework for voice, video, and multimodal applications. Our open-source integration lets you add a LemonSlice avatar to your existing agent stack.

> [!NOTE]
>
> Jump to the [starter projects](#starter-projects) section for ready-to-use repos. For production UI patterns (avatar readiness, error handling, timeouts), see [Production checklist](https://lemonslice.com/docs/reference/production-checklist.md).

## Prerequisites

1. A LemonSlice account and API key associated with an active subscription. Create a key at [lemonslice.com/developers](https://lemonslice.com/developers).
2. A reference image for your avatar. See [our guide](https://lemonslice.com/docs/prompting-guide/avatar-image-tips.md) for recommendations, or set `edit_image` to `true` to automatically reframe your image for best results.
3. LiveKit Agents app
   * Your own existing application, or
   * The ready-to-use [LiveKit playground starter project](https://github.com/lemonsliceai/lemonslice-examples/tree/main/02-livekit-playground-demo), or
   * Follow the [LiveKit VoiceAI quickstart](https://docs.livekit.io/agents/start/voice-ai-quickstart/) for Python or Node.js to create one.

## How to use

**1. Install the plugin**

Within your LiveKit Agents app, install the plugin:

```shell PYTHON theme={null}
# When using PIP
pip install "livekit-agents[lemonslice]"

# When using UV
uv add "livekit-agents[lemonslice]"
```

```shell NODE.JS theme={null}
pnpm add @livekit/agents-plugin-lemonslice
```

**2. Authenticate**

In your LiveKit Agents app, set `LEMONSLICE_API_KEY` in your `.env` file.

**3. Add AvatarSession to AgentSession**

In your LiveKit Agents app, create a `lemonslice.AvatarSession` alongside your `AgentSession`:

```python PYTHON theme={null}
from livekit import agents
from livekit.agents import AgentSession, RoomOutputOptions
from livekit.plugins import lemonslice

async def entrypoint(ctx: agents.JobContext):
    await ctx.connect()

    session = AgentSession(
        # Add STT, LLM, TTS, and other components here
    )

    avatar = lemonslice.AvatarSession(
        # Publicly accessible image URL for the avatar
        agent_image_url="...",
        # Prompt to guide the avatar's demeanor while speaking
        agent_prompt="a person talking",
        # Recommended. Adapts video quality to each viewer's bandwidth
        simulcast=True,
    )

    # Start the avatar and wait for it to join
    session_id = await avatar.start(session, room=ctx.room)

    # Start your agent session with the user
    await session.start(
        # ... room, agent, room_options, etc....
    )
```

```javascript NODE.JS theme={null}
import { voice } from '@livekit/agents';
import * as lemonslice from '@livekit/agents-plugin-lemonslice';

const session = new voice.AgentSession({
    // Add STT, LLM, TTS, and other components here
});

const avatar = new lemonslice.AvatarSession({
    // Publicly accessible image URL for the avatar
    agentImageUrl: "...",
    // Prompt to guide the avatar's demeanor while speaking
    agentPrompt: "a person talking",
});

// Start the avatar and wait for it to join
const sessionId = await avatar.start(session, room);

// Start your agent session with the user
await session.start(
    // ... room, agent, room_options, etc.
);
```

> [tab] Python
>
> | Parameter | Description |
> | - | - |
> | `agent_image_url` | A publicly accessible URL to the avatar image. Exactly one of `agent_image_url` / `agent_id` / `agent_image` is required. |
> | `agent_id` | The ID of a LemonSlice avatar. Exactly one of `agent_image_url` / `agent_id` / `agent_image` is required. If provided, avatar-configured settings are used as defaults for `agent_prompt`, `agent_idle_prompt`, and `idle_timeout`. |
> | `agent_image` | A local PIL image to upload as the avatar. Exactly one of `agent_image_url` / `agent_id` / `agent_image` is required. |
> | `edit_image` | Boolean. If True, the source image is reframed before the session starts. Defaults to True for accounts created after September 22, 2026. Currently only works with a `2x3` aspect ratio. See more in [Avatar image tips](https://lemonslice.com/docs/prompting-guide/avatar-image-tips.md#how-to-get-the-best-quality-avatars). |
> | `edit_image_variant` | Framing to generate when `edit_image` runs: `"standing"` (default), `"bust"` (default when using CWM), `"sitting"`, or `"portrait"`. |
> | `agent_prompt` | A high-level system prompt that subtly influences the avatar's movements, expressions, and emotional demeanor while speaking. This prompt is best used to suggest general affect or demeanor (for example, "feel excited" or "look sad") rather than precise or deterministic actions. Defaults to `"a person talking"`. |
> | `agent_idle_prompt` | A high-level system prompt that influences the avatar's movements, expressions, and emotional demeanor during the idle state. Defaults to `"a serious person"`. |
> | `idle_timeout` | Idle timeout in seconds. If a negative number is provided, the session will have no idle timeout. Defaults to 60. We **strongly** discourage disabling the idle timeout during development to avoid excessive credit usage. |
> | `response_done_timeout` | Time in seconds to wait without receiving new audio bytes before marking the response as complete. Some TTS models do not send an end response event, or do not send it in a timely manner, after transmitting all audio bytes. This parameter enables detection of response completion when such events are missing or delayed. |
> | `audio_sample_rate` | Sample rate (Hz) of the audio sent to the avatar. The avatar publishes its audio at the same rate. Either `16000` or `24000`. Defaults to `24000`. |
> | `model` | Model variant (`"cwm-1"`, `"cwm-1-lite"`, `"cartoon"`, or `"pro"`). Leave unset to use the normal flagship model. |
> | `aspect_ratio` | Output aspect ratio (`"2x3"`, `"9x16"`, or `"1x1"`). Defaults to `"2x3"`. |
> | `simulcast` | Boolean. **Recommended: `true`.** Publish the avatar with [simulcast](https://livekit.com/blog/an-introduction-to-webrtc-simulcast) so viewers on slower networks get a lower resolution instead of a stuttering full-resolution stream. Leave it off only if your subscriber expects a single encoding. Defaults to `false`. |
> | `video_codec` | Video codec for the published avatar track (`"vp8"`, `"h264"`, `"vp9"`, `"av1"`, or `"h265"`). Defaults to `"vp8"`. |
> | `scalability_mode` | SVC mode that lets LiveKit send a lighter stream when a viewer's connection can't keep up. Applied only when `video_codec` is `"vp9"` or `"av1"`; ignored otherwise. See [scalability\_mode](#scalability_mode). |

> [tab] Node.js
>
> | Parameter | Description |
> | - | - |
> | `agentImageUrl` | A publicly accessible URL to the avatar image. Exactly one of `agentImageUrl` / `agentId` / `agentImage` is required. |
> | `agentId` | The ID of a LemonSlice avatar. Exactly one of `agentImageUrl` / `agentId` / `agentImage` is required. If provided, avatar-configured settings are used as defaults for `agentPrompt`, `agentIdlePrompt`, and `idleTimeout`. |
> | `agentImage` | A local image file path or `Buffer` to upload as the avatar. Exactly one of `agentImageUrl` / `agentId` / `agentImage` is required. |
> | `agentImageMimeType` | MIME type for `agentImage` when provided as a `Buffer` (for example, `'image/jpeg'`). Ignored for file paths. Defaults to `'image/png'`. |
> | `agentPrompt` | A high-level system prompt that subtly influences the avatar's movements, expressions, and emotional demeanor while speaking. This prompt is best used to suggest general affect or demeanor (for example, "feel excited" or "look sad") rather than precise or deterministic actions. Defaults to `"a person talking"`. |
> | `agentIdlePrompt` | A high-level system prompt that influences the avatar's movements, expressions, and emotional demeanor during the idle state. Defaults to `"a serious person"`. |
> | `idleTimeout` | Idle timeout in seconds. If a negative number is provided, the session will have no idle timeout. Defaults to 60. We **strongly** discourage disabling the idle timeout during development to avoid excessive credit usage. |
> | `audioSampleRate` | Sample rate (Hz) of the audio sent to the avatar. The avatar publishes its audio at the same rate. Either `16000` or `24000`. Defaults to `24000`. |
> | `extraPayload` | Additional LemonSlice session fields forwarded on session create. See [extraPayload](#extrapayload-nodejs) below. |

> [accordion] extraPayload (Node.js)
>
> In the Node.js plugin, session fields that are not first-class `AvatarSession` options are passed through `extraPayload`.
>
> | Field | Description |
> | - | - |
> | `editImage` | Boolean. If True, the source image is reframed before the session starts. Defaults to True for accounts created after September 22, 2026. Currently only works with a `2x3` aspect ratio. See more in [Avatar image tips](https://lemonslice.com/docs/prompting-guide/avatar-image-tips.md#how-to-get-the-best-quality-avatars). |
> | `editImageVariant` | Framing to generate when image editing runs: `"standing"` (default), `"bust"` (default when using CWM), `"sitting"`, or `"portrait"`. |
> | `model` | Model variant (`"cwm-1"`, `"cwm-1-lite"`, `"cartoon"`, or `"pro"`). Leave unset to use the normal flagship model. |
> | `aspectRatio` | Output aspect ratio (`"2x3"`, `"9x16"`, or `"1x1"`). Defaults to `"2x3"`. |
> | `responseDoneTimeout` | Time in seconds to wait without receiving new audio bytes before marking the response as complete. |
> | `simulcast` | Boolean. Defaults to `false`. Set to `true` to enable [WebRTC simulcast](https://livekit.com/blog/an-introduction-to-webrtc-simulcast). |
> | `videoCodec` | Video codec for the published avatar track (`"vp8"`, `"h264"`, `"vp9"`, `"av1"`, or `"h265"`). Defaults to `"vp8"`. |
> | `scalabilityMode` | SVC mode that lets LiveKit send a lighter stream when a viewer's connection can't keep up. Applied only when `videoCodec` is `"vp9"` or `"av1"`; ignored otherwise. See below for more information. |
>
> ```javascript theme={null}
> const avatar = new lemonslice.AvatarSession({
>   agentImageUrl: "...",
>   agentPrompt: "a person talking",
>   agentIdlePrompt: "a serious person",
>   extraPayload: {
>     aspectRatio: "1x1",
>     responseDoneTimeout: 0.8,
>   },
> });
> ```

> [accordion] scalability\_mode
>
> Names follow `L{spatial}T{temporal}`, with an optional `_KEY` suffix. [WebRTC SVC](https://w3c.github.io/webrtc-svc/) defines the modes; LemonSlice accepts:
>
> `"L1T1"`, `"L1T2"`, `"L1T3"`, `"L2T1"`, `"L2T2"`, `"L2T3"`, `"L2T1_KEY"`, `"L2T2_KEY"`, `"L2T3_KEY"`, `"L3T1"`, `"L3T2"`, `"L3T3"`, `"L3T1_KEY"`, `"L3T2_KEY"`, `"L3T3_KEY"`
>
> | Part | Meaning |
> | - | - |
> | `L` | Spatial layers (resolution). `L1` is one size; `L3` is three, so LiveKit can send a smaller picture. |
> | `T` | Temporal layers (frame rate). `T1` is one rate; `T3` is three, so LiveKit can send fewer frames. |
> | `_KEY` | Spatial layers start from keyframes, which makes quality switches cleaner. |
>
> Example: `"L1T3"` is one resolution and three frame rates. `"L3T3_KEY"` is three resolutions and three frame rates, with keyed spatial layers (the usual LiveKit default when publishing VP9/AV1).
>
> This field is ignored unless `video_codec` / `videoCodec` is `"vp9"` or `"av1"`.

> [!NOTE]
>
> When using the [**Gemini Live S2S**](https://docs.livekit.io/agents/models/realtime/plugins/gemini/) model for realtime interactions, set `response_done_timeout=0.8` to handle end of responses correctly.
>
> If you encounter stutters or glitches with any other TTS, please contact [support@lemonslice.com](mailto:support@lemonslice.com).

**4. Hook into Events**

Listen to LemonSlice RPC events over the LiveKit data channel to better manage the avatar lifecycle:

```python Python theme={null}
LEMONSLICE_RPC_TOPIC = "lemonslice"
AVATAR_READY_MSG_TYPE = "bot_ready"

def on_data_received(packet: rtc.DataPacket) -> None:
    if packet.topic != LEMONSLICE_RPC_TOPIC:
        return

    try:
        payload = json.loads(packet.data.decode("utf-8"))
    except (UnicodeDecodeError, json.JSONDecodeError):
        logger.warning("Unable to decode LemonSlice RPC JSON", exc_info=True)
        return

    if (
        not isinstance(payload, dict)
        or payload.get("type") != AVATAR_READY_MSG_TYPE
    ):
        return

    session_id = payload.get("session_id")
    logger.info(f"Avatar has joined and is ready! session_id = {session_id}")

room.on("data_received", on_data_received)
```

```javascript Node.js theme={null}
const LEMONSLICE_RPC_TOPIC = "lemonslice";
const AVATAR_READY_MSG_TYPE = "bot_ready";

room.on(RoomEvent.DataReceived, (payload, participant, kind, topic) => {
    if (topic !== LEMONSLICE_RPC_TOPIC) return;

    try {
        const data = JSON.parse(new TextDecoder().decode(payload));

        if (typeof data !== "object" || data.type !== AVATAR_READY_MSG_TYPE) return;

        const sessionId = data.session_id;
        console.log(`LemonSlice is actively streaming A/V to the user! session_id = ${sessionId}`);
    } catch (e) {
        console.warn("Unable to decode LemonSlice RPC JSON", e);
    }
});
```

**LemonSlice Events**

| Event Type | Description |
| :- | :- |
| `bot_ready` | Fired when LemonSlice is streaming audio and video to the user. There may be a small delay between this event and the user seeing actual video frames if there are network issues. |
| `idle_timeout` | Emitted when the avatar session stops due to inactivity. The idle timeout threshold is defined by the avatar's configuration. |
| `error` | A pipeline-related error occurred. Includes `error` and `fatal` fields. |
| `video_generation_error` | A failure occurred while generating a video segment. |
| `metric` | Returned after every avatar response with performance metrics. Includes `time_to_first_push` (time from receiving the first audio byte to pushing the first generated video frame). If LiveKit/TTS failed to deliver audio in real time, `tts_audio_delay` will be set to `true`. |

> [!NOTE]
>
> These events are available to both your backend agent and frontend client, allowing you to coordinate avatar state across your entire application.

**5. Preview**

Preview the avatar in the [Agents Playground](https://docs.livekit.io/agents/start/playground) or refer to one of our [starter projects](#starter-projects) for sample frontend code.

**6. Shutdown the LiveKit room**

Gracefully shut down the LiveKit room, LiveKit agent, and/or LemonSlice avatar session:

1. Call `ctx.room.disconnect()` to close the LiveKit room connection which will end the LemonSlice avatar session.
2. Call `ctx.shutdown()` to stop the Agent's JobContext and the LemonSlice avatar session if you don't want to shutdown the LiveKit room.
3. Call the [session control endpoint](https://lemonslice.com/docs/api-reference/control-session.md) with the `terminate` event to shutdown only the LemonSlice avatar without shutting down the LiveKit room or agent.

where `ctx` is LiveKit's `agents.JobContext` defined by the function annotated with `@server.rtc_session()`

```python PYTHON theme={null}
@server.rtc_session()
async def my_agent(ctx: agents.JobContext):
  ...
```

> [!WARNING]
>
> If the LemonSlice session is not shut down, it will remain active until the configured idle timeout is reached or your session reaches the maximum allowed duration.

## Multiple avatars in one room

You can put several LemonSlice avatars in the same LiveKit room. Each avatar needs:

1. A unique LiveKit participant identity (and preferably a display name)
2. Its own `AgentSession` — one session drives one avatar

```python PYTHON theme={null}
import asyncio

from livekit import agents
from livekit.agents import Agent, AgentSession
from livekit.plugins import lemonslice

async def entrypoint(ctx: agents.JobContext):
    await ctx.connect()

    characters = [
        {
            "name": "Alice",
            "identity": "lemonslice-avatar-alice",
            "image_url": "https://example.com/alice.jpg",
            "instructions": "You are Alice, a helpful travel guide.",
        },
        {
            "name": "Bob",
            "identity": "lemonslice-avatar-bob",
            "image_url": "https://example.com/bob.jpg",
            "instructions": "You are Bob, a helpful food guide.",
        },
    ]

    sessions = []
    for character in characters:
        session = AgentSession(
            # Add STT, LLM, TTS, and other components here
        )
        avatar = lemonslice.AvatarSession(
            agent_image_url=character["image_url"],
            avatar_participant_identity=character["identity"],
            avatar_participant_name=character["name"],
        )
        agent = Agent(instructions=character["instructions"])
        sessions.append((session, avatar, agent))

    # Start all avatars in parallel, then start the agents that drive them
    await asyncio.gather(
        *(avatar.start(session, room=ctx.room) for session, avatar, _ in sessions)
    )
    await asyncio.gather(
        *(
            session.start(room=ctx.room, agent=agent)
            for session, _, agent in sessions
        )
    )
```

```javascript NODE.JS theme={null}
import { defineAgent, voice } from '@livekit/agents';
import * as lemonslice from '@livekit/agents-plugin-lemonslice';

export default defineAgent({
  entry: async (ctx) => {
    await ctx.connect();
    const room = ctx.room;

    const characters = [
        {
            name: "Alice",
            identity: "lemonslice-avatar-alice",
            imageUrl: "https://example.com/alice.jpg",
            instructions: "You are Alice, a helpful travel guide.",
        },
        {
            name: "Bob",
            identity: "lemonslice-avatar-bob",
            imageUrl: "https://example.com/bob.jpg",
            instructions: "You are Bob, a helpful food guide.",
        },
    ];

    const sessions = characters.map((character) => ({
        session: new voice.AgentSession({
            // Add STT, LLM, TTS, and other components here
        }),
        avatar: new lemonslice.AvatarSession({
            agentImageUrl: character.imageUrl,
            avatarParticipantIdentity: character.identity,
            avatarParticipantName: character.name,
        }),
        agent: voice.Agent.create({ instructions: character.instructions }),
    }));

    // Start all avatars in parallel, then start the agents that drive them
    await Promise.all(
        sessions.map(({ session, avatar }) => avatar.start(session, room)),
    );
    await Promise.all(
        sessions.map(({ session, agent }) => session.start({ room, agent })),
    );
  },
});
```

> [!TIP]
>
> For the fastest setup time, start the avatars in parallel, then start the agent sessions in parallel (`asyncio.gather` / `Promise.all`).

If a value is not provided for the avatar participant identity in the `AvatarSession` declaration, the default value `"lemonslice-avatar-agent"` is used. Since two avatars cannot share an identity, concurrent avatars must set this property explicitly.

On the frontend, filter by participant identity rather than assuming a single avatar participant.

## Deploy on LiveKit Cloud

While you can host your agents on an external Python or Node.js server, we recommend [LiveKit Cloud](https://livekit.io/cloud). It reduces setup and provides infrastructure, hosting, and observability out of the box.

## Starter projects

| Repo | What's included |
| :- | :- |
| [`02-livekit-playground-demo`](https://github.com/lemonsliceai/lemonslice-examples/tree/main/02-livekit-playground-demo) | Starter code to launch a LiveKit agent with the LemonSlice avatar plugin. Run your agent locally and connect in the [LiveKit playground](https://docs.livekit.io/agents/start/playground) for rapid prototyping |
| [`03-livekit-app-python`](https://github.com/lemonsliceai/lemonslice-examples/tree/main/03-livekit-app-python) | Fullstack web app using the [LiveKit Python SDK](https://github.com/livekit/agents). Includes LiveKit Agent + LemonSlice code, front-end UI, and backend token server. |
| [`04-livekit-app-nodejs`](https://github.com/lemonsliceai/lemonslice-examples/tree/main/04-livekit-app-nodejs) | Fullstack web app using the [LiveKit Node.js SDK](https://github.com/livekit/agents-js). Includes LiveKit Agent + LemonSlice code, front-end UI, and backend token server. |


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