m
hi
t
Thanks for reaching out, aigentzi. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hi — how can I help today? What are you trying to do with LiveKit right now (e.g., start a room, join a call, integrate the SDK, fix an error)? If you have an error message, project/room IDs, or code snippets, please share them and I’ll help.
m
APP [10:35 AM] Below are Dockerfiles for the backend and the agent, plus a docker-compose.yml and minimal .dockerignore. These match the repo layout you already have (backend/app.py and agent/main.py) and use the same requirements. Adjust env values in .env before running. Dockerfile for backend (backend/Dockerfile)
Copy code
FROM python:3.11-slim

WORKDIR /app

# system deps (if any)
RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
 && rm -rf /var/lib/apt/lists/*

COPY backend/requirements.txt /app/requirements.txt
RUN pip install --no-cache-dir -r /app/requirements.txt

COPY backend /app

EXPOSE 8000

CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers"]
Dockerfile for agent (agent/Dockerfile)
Copy code
FROM python:3.11-slim

WORKDIR /app

RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
 && rm -rf /var/lib/apt/lists/*

COPY agent/requirements.txt /app/requirements.txt
RUN pip install --no-cache-dir -r /app/requirements.txt

COPY agent /app

# Ensure env vars from .env are passed at runtime via docker-compose or env file
CMD ["python", "main.py"]
Note: If you keep a single requirements.txt at repo root, update COPY paths accordingly or duplicate files under backend/ and agent/. docker-compose.yml (root)
Copy code
version: "3.8"
services:
  backend:
    build:
      context: .
      dockerfile: backend/Dockerfile
    container_name: lk_backend
    ports:
      - "8000:8000"
    env_file:
      - .env
    restart: unless-stopped

  agent:
    build:
      context: .
      dockerfile: agent/Dockerfile
    container_name: lk_agent
    env_file:
      - .env
    restart: unless-stopped
    # Optional: give the agent a small delay to allow backend to be ready
    depends_on:
      - backend
.agent and backend requirements • Create backend/requirements.txt and agent/requirements.txt (or share single file). For the setup used earlier, requirements can be: requirements.txt (suggested; place in both backend/ and agent/)
Copy code
fastapi[all]==0.95.2
uvicorn[standard]==0.22.0
python-dotenv==1.0.0
livekit==1.0.3
.dockerignore (root)
Copy code
__pycache__
*.pyc
.env
.env.*
*.log
.git
.gitignore
Usage 1. Copy the Dockerfiles into backend/ and agent/ and add the files described earlier (backend/app.py, agent/main.py). 2. Create .env in repo root from .env.example and set LIVEKIT_API_KEY, LIVEKIT_API_SECRET, LIVEKIT_WS_URL, AGENT_NAME, AGENT_ID. 3. Build & run: ◦ docker-compose up --build 4. Open http://localhost:8000 to open the demo UI; the agent container will run the LiveKit agent process and should receive dispatch jobs when tokens include the agent dispatch. Notes and tips • Ensure LIVEKIT_WS_URL points to your LiveKit project and that the agent can reach it from the container (network/firewall). • If the agent uses additional native libs for plugins (e.g., audio codecs, or OpenAI/Gemini SDK requirements), add the needed apt packages and pip packages to agent Dockerfile. • To view agent logs: docker-compose logs -f agent Want me to: • produce a ready-to-download zip of the repo with Dockerfiles included, or • add healthchecks and a small wait-for script so the agent retries connecting until backend is up? Zak [10:40 AM] this is great thanks what voice provider etc are we using here ? not we are using inference for all api keys not our wonn LiveKit Assistant [10:41 AM] Thanks — good question. This repo is configured to use LiveKit Inference as the voice provider (no external TTS API keys required). The demo UI labels the provider “LiveKit Inference” and the default voice used in examples is the LiveKit inference voice (Default / Cartesia Sonic‑2). That means speech synthesis and inference calls run via LiveKit’s managed inference services using your LiveKit project credentials (LIVEKIT_API_KEY / LIVEKIT_API_SECRET), not separate third‑party TTS keys. If you want to change providers or voice: • To switch to a different LiveKit inference voice, set the desired voice name in your agent prompt/usage or pass it as metadata in the dispatch token so the agent reads it from
ctx.job.metadata
. • To use an external TTS provider instead, update the agent code to call that provider’s API (add provider API key in .env), synthesize audio, and publish the audio track from the agent instead of calling
local_participant.say()
. If you’d like, I can: • add a sample metadata field and agent code showing how to select a specific LiveKit inference voice, or • add an example showing how to call an external TTS provider and publish its audio in the agent. Which would you prefer? Zak [10:42 AM] I would like to have each agent using a diferent provider eg one is gemini flash , one is open ai one is cartsia one is eleven labs etc so we can tset thse wg taxi driver maybe gemni , hotel maybe cartsia etc BUT I dont want to ad cioplexityy if ytou thin k gthsi may break it ? [10:42 AM] all using inference LiveKit Assistant [10:43 AM] Great — using LiveKit Inference for all agents is the simplest, safest approach. Below is a concise plan and ready-to-drop-in agent & dispatch changes that select per-scenario models (LLM + TTS) via Inference model strings — no extra external API keys needed. 1) Approach (short) • Encode desired provider/model in dispatch metadata (we already do this for
scenario
). • In the agent, map scenario → Inference model strings for LLM and TTS and pass those to the agent session or use them when calling inference APIs through LiveKit. • LiveKit Inference handles authentication and routing using your LiveKit project creds (LIVEKIT_API_KEY/SECRET). 2) Recommended scenario → model mapping (example) • taxi → LLM: "google/gemini-2.0-flash", TTS: "google/gemini-tts:default" • hotel → LLM: "openai/gpt-4o", TTS: "cartesia/sonic-3:default" • english_teacher_general → LLM: "openai/gpt-4o-mini", TTS: "cartesia/sonic-2:default" • concierge → LLM: "openai/gpt-4o", TTS: "elevenlabs/eleven-turbo-v2:default" (Adjust model strings to the exact names you want; these are illustrative.) 3) Agent code (use LiveKit agent SDK; replace previous greeting logic) • Read
scenario
from
ctx.job.metadata
. • Look up model strings for that scenario. • Configure the agent session or call inference with those model strings. • Use
ctx.room.local_participant.say(..., model=tts_model)
or call the inference plugin with the chosen LLM model when generating replies. Minimal snippet to plug into your existing agent (agent/main.py):
Copy code
import json
from livekit.agents import rtc_session, JobContext

SCENARIO_MODELS = {
    "taxi": {
        "llm": "google/gemini-2.0-flash",
        "tts": "google/gemini-tts:default"
    },
    "hotel_receptionist": {
        "llm": "openai/gpt-4o",
        "tts": "cartesia/sonic-3:default"
    },
    "english_teacher_general": {
        "llm": "openai/gpt-4o-mini",
        "tts": "cartesia/sonic-2:default"
    },
    "concierge": {
        "llm": "openai/gpt-4o",
        "tts": "elevenlabs/eleven-turbo-v2:default"
    }
}

@rtc_session(agent_name="cloud-english-teacher")
async def english_teacher_agent(ctx: JobContext):
    await ctx.connect()
    job_meta = json.loads(ctx.job.metadata or "{}")
    scenario = job_meta.get("scenario", "english_teacher_general")
    models = SCENARIO_MODELS.get(scenario, SCENARIO_MODELS["english_teacher_general"])
    llm_model = models["llm"]
    tts_model = models["tts"]

    # Generate greeting via LiveKit Inference (agent SDK helpers usually route via model string)
    greeting_prompt = {
        "english_teacher_general": "Hello! I'm your AI English teacher. Let's practice together.",
        "taxi": "Hi! Welcome to the taxi. Where would you like to go?",
        "hotel_receptionist": "Welcome! How may I assist you with your check-in?"
    }.get(scenario, "Hello! Let's begin.")

    # If your SDK provides a `say` overload that accepts model selection, pass tts_model:
    await ctx.room.local_participant.say(greeting_prompt, model=tts_model)

    # For dialog: when generating replies, call the agent's inference/LLM using llm_model.
    # Example pseudocode (adapt to your agent framework's API):
    # reply = await ctx.session.generate_reply(prompt=greeting_prompt, model=llm_model)
    # await ctx.room.local_participant.say(reply.text, model=tts_model)
4) Why this won't add risky complexity • All calls stay within LiveKit Inference so you avoid external API keys and separate integrations. • Each agent picks models at runtime — agents remain isolated; switching one agent’s models won’t affect others. • Start small: enable per-scenario model selection for 1–2 scenarios, verify latency/quality, then expand. 5) Testing checklist • Ensure token dispatch metadata includes
scenario
. • Start agent container (cli.run_app) and backend. • From UI select a scenario, start session — verify agent log shows scenario and chosen models. • Validate speech uses the expected voice and LLM responses match the model behavior. If you want, I’ll: • Add the full model-selection logic into the agent repo and update the Docker image, • Or modify the FastAPI token endpoint to include an explicit
tts_model
and
llm_model
in dispatch metadata so selection is driven from the frontend. Which would you like me to add next?
t
Thanks — I’m glad that plan looks useful. You asked which next step to take. I can do one of the two options you mentioned; pick one and I’ll proceed: • Option A — Add model-selection logic to the agent repo and update the agent Dockerfile: ◦ Agent reads
scenario
(or explicit model names) from
ctx.job.metadata
, maps to
llm
and
tts
model strings, and uses those when calling LiveKit Inference (e.g.,
ctx.room.local_participant.say(..., model=tts_model)
and inference calls with
llm_model
). ◦ I’ll add code, tests/logging, and rebuild Dockerfile so each agent image uses the logic out-of-the-box. • Option B — Modify the backend token/dispatch endpoint to include explicit
tts_model
and
llm_model
in dispatch metadata: ◦ Frontend selects scenario/provider, backend encodes the exact model strings into dispatch tokens so agents don’t need a mapping table. ◦ I’ll update the FastAPI endpoint and show the frontend changes to pass `tts_model`/`llm_model`. Quick guidance to help choose: • If you want centralized control from the UI and easy per-dispatch overrides, choose Option B. • If you prefer agents to own their scenario-to-model mapping (useful when different agents should default differently), choose Option A. Which option would you like me to implement? If you pick one, tell me: • Any exact model strings you want for the initial scenarios (taxi, hotel, english_teacher, concierge), or • If you want me to use the example mappings I suggested.
m
OPTION B , use the example mappings I suggested
t
Great — you chose Option B and want the example mappings used. Below I’ll provide a concise FastAPI backend change that: • accepts a
scenario
from the frontend, • maps it to the example
llm
and
tts
model strings, • includes those values in the
RoomAgentDispatch.metadata
when generating the token/dispatch. Apply this to your existing backend (backend/app.py). Change or merge into your token endpoint. 1) Example scenario → model mapping (use these example strings)
Copy code
SCENARIO_MODELS = {
    "taxi": {
        "llm": "google/gemini-2.0-flash",
        "tts": "google/gemini-tts:default"
    },
    "hotel_receptionist": {
        "llm": "openai/gpt-4o",
        "tts": "cartesia/sonic-3:default"
    },
    "english_teacher_general": {
        "llm": "openai/gpt-4o-mini",
        "tts": "cartesia/sonic-2:default"
    },
    "concierge": {
        "llm": "openai/gpt-4o",
        "tts": "elevenlabs/eleven-turbo-v2:default"
    }
}
2) Minimal FastAPI token/dispatch endpoint
Copy code
from fastapi import FastAPI, Form
from pydantic import BaseModel
import json
import os
from livekit_server_sdk import AccessToken, RoomConfiguration, RoomAgentDispatch  # adjust imports to your SDK

app = FastAPI()

@app.post("/token")
def token(identity: str = Form(...), room: str = Form(...), scenario: str = Form("english_teacher_general")):
    # Select models from mapping
    selected = SCENARIO_MODELS.get(scenario, SCENARIO_MODELS["english_teacher_general"])
    metadata_json = json.dumps(selected)

    # Build AccessToken with room/agent dispatch
    at = AccessToken(os.environ["LIVEKIT_API_KEY"], os.environ["LIVEKIT_API_SECRET"])
    at.identity = identity
    # grant room join
    at.add_grant({"roomJoin": True, "room": room})

    # Attach agent dispatch with metadata (stringified JSON)
    room_config = RoomConfiguration(agents=[RoomAgentDispatch(agent_name="voice-agent", metadata=metadata_json)])
    at.room_config = room_config

    token = at.to_jwt()
    return {"token": token, "metadata": selected}
Notes: • Replace
livekit_server_sdk
and classes with the actual Python/Node SDK objects you use; the important part is including
RoomAgentDispatch.metadata
set to the JSON string of
{ "llm": "...", "tts": "..." }
. • Frontend should POST
scenario
(taxi, hotel_receptionist, english_teacher_general, concierge) when requesting a token. • The response returns the token and the selected metadata for debugging. 3) Agent side (small parsing reminder) • Agent reads
ctx.job.metadata
, parse JSON, then use
llm
and
tts
values. • Example parse snippet:
Copy code
import json
meta = json.loads(ctx.job.metadata or "{}")
llm_model = meta.get("llm")
tts_model = meta.get("tts")
# Use these when calling LiveKit Inference or ctx.room.local_participant.say(..., model=tts_model)
4) Testing checklist • Send a token request with
scenario=taxi
and confirm backend logs the selected mapping. • Start the room with the agent and confirm agent logs show
llm
and
tts
from metadata. • Verify spoken output uses the expected voice and model behavior. If you want, I can: • produce the exact code merged into your current backend file (paste your current backend/app.py and I’ll return the modified file), or • update the frontend sample to POST
scenario
and show how to select scenarios in the UI. Which do you prefer? Sources: Agent dispatch | LiveKit docs | server-sdk-ruby | livekit/livekit_composite | DeepWiki | Introducing LiveKit Inference: A unified model interface for voice AI