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 — thanks for reaching out. How can I help you today? If you’re reporting an issue, please include: • What you’re trying to do (feature or flow) • Any error messages, room ID, or session ID • Steps to reproduce and when it started If you need setup guidance, tell me which SDK/platform (Web, iOS, Android, or server) you’re using.
m
1. we have an issue that an agent is not joining this room : can you share a code update for us to fix this issue : [App] Selected configuration: {scenario: 'taxi', level: 'basic', provider: 'livekit', voice: 'default'} 1. publishing track _{room: 'english-teacher-1764968992093-9q4jdd6', roomID: '', participant: 'user-1764968992405', pID: 'PA_6Fh6uWe8kd8m', trackID: undefined, …}_ 2. enabled 3. : a. true 4. kind 5. : a. "audio" 6. muted 7. : a. false 8. pID 9. : a. "PA_6Fh6uWe8kd8m" 10. participant 11. : a. "user-1764968992405" 12. room 13. : a. "english-teacher-1764968992093-9q4jdd6" 14. roomID 15. : a. "" 16. source 17. : a. "microphone" 18. streamID 19. : a. "097f1c01-93ae-4e65-803b-084261d524b1" 20. streamTrackID 21. : a. "097f1c01-93ae-4e65-803b-084261d524b1" 22. trackID 23. : a. undefined 24. [[Prototype]] 25. : a. Object 26. constructor 27. : i. ƒ Object() 28. hasOwnProperty 29. : i. ƒ hasOwnProperty() 30. isPrototypeOf 31. : i. ƒ isPrototypeOf() 32. propertyIsEnumerable 33. : i. ƒ propertyIsEnumerable() 34. toLocaleString 35. : i. ƒ toLocaleString() 36. toString 37. : i. ƒ toString() 38. valueOf 39. : i. ƒ valueOf() 40. defineGetter 41. : i. _ƒ __defineGetter__()_ 42. defineSetter 43. : i. _ƒ __defineSetter__()_ 44. lookupGetter 45. : i. _ƒ __lookupGetter__()_ 46. lookupSetter 47. : i. _ƒ __lookupSetter__()_ 48. proto 49. : i. (...) 50. get proto 51. : i. _ƒ __proto__()_ 52. set proto 53. : i. _ƒ __proto__()_ 1. disconnect from room _{room: 'english-teacher-1764968992093-9q4jdd6', roomID: 'RM_rA68GfMrtsWU', participant: 'user-1764968992405', pID: 'PA_6Fh6uWe8kd8m'}_ 2. pID 3. : a. "PA_6Fh6uWe8kd8m" 4. participant 5. : a. "user-1764968992405" 6. room 7. : a. "english-teacher-1764968992093-9q4jdd6" 8. roomID 9. : a. "RM_rA68GfMrtsWU" 10. [[Prototype]] 11. : a. Object 12. constructor 13. : i. ƒ Object() 14. hasOwnProperty 15. : i. ƒ hasOwnProperty() 16. isPrototypeOf 17. : i. ƒ isPrototypeOf() 18. propertyIsEnumerable 19. : i. ƒ propertyIsEnumerable() 20. toLocaleString 21. : i. ƒ toLocaleString() 22. toString 23. : i. ƒ toString() 24. valueOf 25. : i. ƒ valueOf() 26. defineGetter 27. : i. _ƒ __defineGetter__()_ 28. defineSetter 29. : i. _ƒ __defineSetter__()_ 30. lookupGetter 31. : i. _ƒ __lookupGetter__()_ 32. lookupSetter 33. : i. _ƒ __lookupSetter__()_ 34. proto 35. : i. (...) 36. get proto 37. : i. _ƒ __proto__()_ 38. set proto 39. : i. _ƒ __proto__()_
t
Thanks — I’m looking at the logs you shared (participant publishes audio, then disconnects;
trackID
is undefined and
roomID
is empty in the publish log). That pattern points to agent dispatch not occurring so the agent never joins the room. To fix this, please verify and apply the following checks and code changes. 1) Ensure the user token includes room dispatch config • Generate the access token with a room config that includes the agent dispatch entry for the exact agent name your agent process registers with. • Example (Python):
Copy code
from livekit import api
token = (
    api.AccessToken(API_KEY, API_SECRET)
    .with_identity("user-1764968992405")
    .with_grants(api.VideoGrants(room_join=True, room="english-teacher-1764968992093-9q4jdd6"))
    .with_room_config(api.RoomConfiguration(
        agents=[api.RoomAgentDispatch(agent_name="my-telephony-agent", metadata='{"lang":"en"}')]
    ))
    .to_jwt()
)
• Confirm the
room
field exactly matches "english-teacher-1764968992093-9q4jdd6" and
agent_name
matches the agent process. 2) Confirm agent registration matches dispatch name • In your agent code, ensure the agent registers with the same
agent_name
used above. Example decorator/registration:
Copy code
@server.rtc_session(agent_name="my-telephony-agent")
async def my_agent(ctx: JobContext):
    await ctx.connect(auto_subscribe=AutoSubscribe.AUDIO_ONLY)
    # agent logic...
3) Check agent process is running and receiving jobs • Confirm the agent service logs show it connected and is receiving/starting jobs for rooms (look for "Worker connected" or "Starting job for room: ..."). • If no job logs appear, dispatch never reached agent. 4) Quick manual dispatch for testing • Manually dispatch the agent to verify the agent can join:
Copy code
lk dispatch create \
  --new-room \
  --agent-name my-telephony-agent \
  --room english-teacher-1764968992093-9q4jdd6 \
  --metadata '{"user_id":"user-1764968992405"}'
• If this causes the agent to join, your token-based dispatch or dispatch rules were the issue. 5) Track-related notes •
trackID
being
undefined
in the publish log can happen if publishing happened briefly or the participant disconnected quickly; focus first on ensuring the agent joins the room so you can observe full publish flows. If you want, tell me: • Which SDK/language you use to generate tokens, • The
agent_name
your agent process registers with, and I’ll give a ready-to-drop-in token-generation snippet matching your stack. Sources: Authentication | LiveKit docs | Agent dispatch | LiveKit docs | Agents telephony integration | LiveKit docs
m
we are using python agent ID is CA_e7hLTus66nKZ and name cloud-english-teacher
t
Thanks — since your Python agent name is cloud-english-teacher (ID
CA_e7hLTus66nKZ
) and the room is
english-teacher-1764968992093-9q4jdd6
, use a token that explicitly includes a room config with a matching agent dispatch entry. That ensures LiveKit will dispatch your agent when the user joins. Please use this Python example to generate the token (replace `API_KEY`/`API_SECRET` and any metadata you need):
Copy code
from livekit import api
import os

API_KEY = os.getenv("LIVEKIT_API_KEY")
API_SECRET = os.getenv("LIVEKIT_API_SECRET")

token = (
    api.AccessToken(API_KEY, API_SECRET)
    .with_identity("user-1764968992405")
    .with_grants(api.VideoGrants(
        room_join=True,
        room="english-teacher-1764968992093-9q4jdd6"
    ))
    .with_room_config(api.RoomConfiguration(
        agents=[
            api.RoomAgentDispatch(
                agent_name="cloud-english-teacher",   # must match your agent name
                agent_id="CA_e7hLTus66nKZ",          # optional, can include for clarity
                metadata='{"role":"agent","lang":"en"}'
            )
        ]
    ))
    .to_jwt()
)

print(token)
Next steps to verify: • Ensure your agent process registers as
cloud-english-teacher
and is running. Your agent logs should show it connected and ready to receive jobs. • Join the room with the generated token and watch agent logs for a job start message like "Starting job for room: english-teacher-...". • If no job appears, run a manual dispatch to test:
Copy code
lk dispatch create \
  --new-room \
  --agent-name cloud-english-teacher \
  --room english-teacher-1764968992093-9q4jdd6 \
  --metadata '{"user_id":"user-1764968992405"}'
If you’d like, I can: • Produce a token snippet tailored to your token-generation framework (Flask/Django/fastapi), or • Show a minimal agent startup snippet to confirm it registers correctly. Which would you prefer?
m
there is an HTML page lik this where a user goes to page selects "the scenario' and then the agent is supiosed to start speaking
t
Thanks — with your agent named cloud-english-teacher (ID
CA_e7hLTus66nKZ
) and the HTML frontend scenario selection, do the following to ensure the agent joins and speaks when a user selects a scenario. 1) Backend: generate a token that dispatches your agent to the exact room • Include
room
and
room_config.agents
with
agent_name="cloud-english-teacher"
(agent_id optional) and set scenario in
metadata
. • Example Python token generation to return to your frontend:
Copy code
from livekit import api
import os, json

API_KEY = os.getenv("LIVEKIT_API_KEY")
API_SECRET = os.getenv("LIVEKIT_API_SECRET")

def generate_token_for_user(identity, room, scenario):
    token = (
        api.AccessToken(API_KEY, API_SECRET)
        .with_identity(identity)
        .with_grants(api.VideoGrants(room_join=True, room=room))
        .with_room_config(api.RoomConfiguration(
            agents=[
                api.RoomAgentDispatch(
                    agent_name="cloud-english-teacher",
                    agent_id="CA_e7hLTus66nKZ",
                    metadata=json.dumps({"scenario": scenario})
                )
            ]
        ))
        .to_jwt()
    )
    return token
2) Frontend: request token after scenario selection and connect with it • Send the selected scenario to your backend, get the token and room name, then connect the user to that room (so LiveKit creates the room and triggers dispatch). 3) Agent (Python): ensure registration matches and speak after connect • Register agent with matching name and read scenario from
ctx.job.metadata
. Call
.connect()
then
.say()
(or equivalent) to start speaking immediately. Example agent snippet:
Copy code
@server.rtc_session(agent_name="cloud-english-teacher")
async def cloud_english_teacher(ctx: JobContext):
    import json
    await ctx.connect()
    job_meta = json.loads(ctx.job.metadata or "{}")
    scenario = job_meta.get("scenario", "general")
    greetings = {
        "english_teacher_general": "Hello! Let's practice English together.",
        "taxi": "Hi, where would you like to go today?"
    }
    await ctx.room.local_participant.say(greetings.get(scenario, "Hello!"))
4) Quick test (manual dispatch) • If you need to validate the agent can join immediately:
Copy code
lk dispatch create \
  --new-room \
  --agent-name cloud-english-teacher \
  --room english-teacher-1764968992093-9q4jdd6 \
  --metadata '{"scenario":"english_teacher_general","user_id":"user-1764968992405"}'
5) Debug checklist • Token contains
room
and
room_config.agents
with
agent_name
exactly "cloud-english-teacher". • Agent process is running and registers as "cloud-english-teacher". • Agent logs show it received a job for the room. • Frontend connects to the room using the returned token right after scenario selection. If you want, I can: • Produce the exact backend endpoint handler (Flask/FastAPI/Django) that returns the token and room, or • Show a minimal frontend JS snippet wired to your scenario dropdown. Which would you like me to provide next? Sources: Authentication | LiveKit docs | Agent dispatch | LiveKit docs | Generating tokens | LiveKit docs | Agent speech and audio | LiveKit docs | Deploying to production | LiveKit Docs
m
please share Fast API and Js thanks
t
Below are a minimal, ready-to-adapt FastAPI backend and matching JavaScript frontend that: • generate a LiveKit access token with RoomConfiguration.agent dispatch for agent "cloud-english-teacher" (ID CA_e7hLTus66nKZ), • return the token and room name to the frontend when a scenario is selected, • frontend connects to the LiveKit room using the returned token so the agent is dispatched and can speak. Backend (FastAPI) • Install: pip install fastapi[all] livekit • Set LIVEKIT_API_KEY and LIVEKIT_API_SECRET in environment
Copy code
# backend/main.py
import os
import json
from fastapi import FastAPI, HTTPException, Request
from pydantic import BaseModel
from livekit import api

API_KEY = os.getenv("LIVEKIT_API_KEY")
API_SECRET = os.getenv("LIVEKIT_API_SECRET")
AGENT_NAME = "cloud-english-teacher"
AGENT_ID = "CA_e7hLTus66nKZ"

if not API_KEY or not API_SECRET:
    raise RuntimeError("Set LIVEKIT_API_KEY and LIVEKIT_API_SECRET")

app = FastAPI()

class TokenRequest(BaseModel):
    identity: str
    room: str
    scenario: str

@app.post("/api/token")
async def create_token(req: TokenRequest):
    try:
        token = (
            api.AccessToken(API_KEY, API_SECRET)
            .with_identity(req.identity)
            .with_grants(api.VideoGrants(room_join=True, room=req.room))
            .with_room_config(api.RoomConfiguration(
                agents=[
                    api.RoomAgentDispatch(
                        agent_name=AGENT_NAME,
                        agent_id=AGENT_ID,
                        metadata=json.dumps({"scenario": req.scenario})
                    )
                ]
            ))
            .to_jwt()
        )
        return {"token": token, "room": req.room}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
Run: uvicorn backend.main:app --reload --port 8000 Frontend (JavaScript) • Uses LiveKit client SDK (browser). Include LiveKit JS via npm or script tag. • Replace LIVEKIT_WS_URL with your LiveKit URL (wss/http endpoint) if needed.
Copy code
<!-- index.html -->
<!doctype html>
<html>
<head>
  <meta charset="utf-8" />
  <script src="https://unpkg.com/livekit-client/dist/livekit-client.min.js"></script>
</head>
<body>
  <select id="scenario-select">
    <option value="english_teacher_general">English Teacher (General)</option>
    <option value="taxi">Taxi Driver</option>
    <!-- add other scenarios -->
  </select>

  <button id="join-btn">Start</button>

  <div id="log"></div>

  <script>
    const API_TOKEN_ENDPOINT = "/api/token"; // adjust if backend hosted elsewhere
    const LIVEKIT_WS_URL = "wss://your-project.livekit.cloud"; // replace with your LiveKit URL

    function log(msg) {
      const d = document.getElementById("log");
      d.innerText += msg + "\n";
    }

    document.getElementById("join-btn").addEventListener("click", async () => {
      const scenario = document.getElementById("scenario-select").value;
      const identity = "user-" + Date.now(); // or your user id
      const room = "english-teacher-1764968992093-9q4jdd6"; // or dynamically create per session

      log(`Requesting token for scenario=${scenario} room=${room} identity=${identity}`);

      const resp = await fetch(API_TOKEN_ENDPOINT, {
        method: "POST",
        headers: {"Content-Type":"application/json"},
        body: JSON.stringify({ identity, room, scenario })
      });

      if (!resp.ok) {
        const txt = await resp.text();
        log("Token request failed: " + txt);
        return;
      }

      const { token, room: roomName } = await resp.json();

      // Connect to LiveKit
      const { Room } = livekit;
      const room = new Room();

      room.on("connected", () => log("Connected to room: " + roomName));
      room.on("participantConnected", p => log("Participant connected: " + p.identity));
      room.on("trackPublished", (pub, participant) => log(`Track published by ${participant.identity}`));

      try {
        await room.connect(LIVEKIT_WS_URL, token);
        log("Connected. Waiting for agent to be dispatched...");
      } catch (err) {
        log("LiveKit connect error: " + err);
      }
    });
  </script>
</body>
</html>
Notes and next steps • Ensure your agent process is running and registered with name "cloud-english-teacher". • The backend sets the scenario in the dispatch metadata so the agent can read it from
ctx.job.metadata
. • The frontend must request the token after the user selects the scenario so dispatch includes scenario metadata. • If you want, I can provide: ◦ a FastAPI endpoint variant returning a short-lived identity or room naming strategy, or ◦ a small agent snippet showing how to read metadata and call
.say()
after
.connect()
. Which of those would you like next?
m
share both please
t
Below are both items: (A) an enhanced FastAPI backend endpoint that returns a token with agent dispatch, plus a short-lived room/identity strategy; and (B) a Python agent snippet that registers as "cloud-english-teacher", reads scenario metadata, connects, and speaks immediately. Replace API keys, LiveKit URL, and adjust prompts as needed. A — FastAPI backend (token endpoint) • Installs: pip install fastapi[all] livekit python-dotenv • Set LIVEKIT_API_KEY and LIVEKIT_API_SECRET in environment or .env
Copy code
# backend/main.py
import os
import json
import uuid
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from dotenv import load_dotenv
from livekit import api

load_dotenv()

API_KEY = os.getenv("LIVEKIT_API_KEY")
API_SECRET = os.getenv("LIVEKIT_API_SECRET")
AGENT_NAME = "cloud-english-teacher"
AGENT_ID = "CA_e7hLTus66nKZ"

if not API_KEY or not API_SECRET:
    raise RuntimeError("Set LIVEKIT_API_KEY and LIVEKIT_API_SECRET")

app = FastAPI()

class TokenRequest(BaseModel):
    scenario: str
    preferred_room: str | None = None
    identity: str | None = None

@app.post("/api/token")
async def create_token(req: TokenRequest):
    # short-lived identity and deterministic room name strategy
    identity = req.identity or f"user-{uuid.uuid4().hex[:12]}"
    room = req.preferred_room or f"english-teacher-{int(uuid.uuid4().int % 1_000_000_000)}"

    try:
        token = (
            api.AccessToken(API_KEY, API_SECRET)
            .with_identity(identity)
            .with_grants(api.VideoGrants(room_join=True, room=room))
            .with_room_config(api.RoomConfiguration(
                agents=[
                    api.RoomAgentDispatch(
                        agent_name=AGENT_NAME,
                        agent_id=AGENT_ID,
                        metadata=json.dumps({"scenario": req.scenario})
                    )
                ]
            ))
            .to_jwt()
        )
        return {"token": token, "room": room, "identity": identity}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
Run: uvicorn backend.main:app --reload --port 8000 B — Frontend JavaScript (connect after scenario selection) • Use LiveKit JS client (npm package or CDN). Replace LIVEKIT_WS_URL with your LiveKit endpoint.
Copy code
<!-- index.html -->
<!doctype html>
<html>
<head>
  <meta charset="utf-8" />
  <script src="https://unpkg.com/livekit-client/dist/livekit-client.min.js"></script>
</head>
<body>
  <select id="scenario-select">
    <option value="english_teacher_general">English Teacher (General)</option>
    <option value="taxi">Taxi Driver</option>
  </select>
  <button id="start-btn">Start Session</button>
  <pre id="log"></pre>

  <script>
    const API_TOKEN_ENDPOINT = "/api/token";
    const LIVEKIT_WS_URL = "wss://your-project.livekit.cloud"; // replace

    function log(msg){ document.getElementById("log").innerText += msg + "\n"; }

    document.getElementById("start-btn").addEventListener("click", async () => {
      const scenario = document.getElementById("scenario-select").value;
      log("Requesting token for scenario: " + scenario);

      const resp = await fetch(API_TOKEN_ENDPOINT, {
        method: "POST",
        headers: {"Content-Type":"application/json"},
        body: JSON.stringify({ scenario })
      });

      if (!resp.ok) {
        log("Token request failed: " + await resp.text());
        return;
      }

      const { token, room, identity } = await resp.json();
      log(`Token received. identity=${identity} room=${room}`);

      const { Room } = livekit;
      const roomClient = new Room();

      roomClient.on("connected", () => log("Connected to LiveKit room: " + room));
      roomClient.on("participantConnected", p => log("Participant connected: " + p.identity));
      roomClient.on("trackPublished", (pub, participant) => log(`Track published by ${participant.identity}`));

      try {
        await roomClient.connect(LIVEKIT_WS_URL, token);
        log("Connected — waiting for agent dispatch...");
      } catch (err) {
        log("LiveKit connect error: " + err);
      }
    });
  </script>
</body>
</html>
C — Python agent (registers as cloud-english-teacher, reads metadata, speaks) • Use your existing agent runtime. This minimal snippet shows registration, connect, reading job metadata and speaking via
.say()
after connect.
Copy code
# agent/agent.py
import json
from livekit.agents import rtc_session, JobContext

@rtc_session(agent_name="cloud-english-teacher")
async def cloud_english_teacher(ctx: JobContext):
    # Called when dispatched for a room/job
    await ctx.connect()  # join the room
    job_meta = {}
    try:
        job_meta = json.loads(ctx.job.metadata or "{}")
    except Exception:
        pass

    scenario = job_meta.get("scenario", "english_teacher_general")

    prompts = {
        "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?",
    }
    greeting = prompts.get(scenario, "Hello! Let's begin.")

    # Speak immediately in the room
    await ctx.room.local_participant.say(greeting)

    # Example: keep the agent alive to handle conversation (adjust as needed)
    # await ctx.wait_for_disconnect()
Notes and tips • Ensure the agent service is running and can receive dispatches for agent_name "cloud-english-teacher". • The backend embeds the scenario in dispatch metadata so the agent can tailor its initial prompt. • Use
lk dispatch create ...
for manual tests if needed. • If you want a full FastAPI example that returns the LiveKit WS URL from configuration or token lifetime customization, tell me which framework you use to serve static files and I’ll adapt the endpoint accordingly. Would you like the FastAPI endpoint to also serve the HTML/JS (single app), or keep them separate?
m
Would you like the FastAPI endpoint to also serve the HTML/JS (single app),
t
Below is a single FastAPI app that: • Serves the HTML/JS UI at GET / (so your frontend and backend are one app), • Provides POST /api/token which returns a LiveKit token containing a RoomConfiguration.agent dispatch for agent "cloud-english-teacher" (ID CA_e7hLTus66nKZ), • Uses a simple room/identity strategy and embeds the selected scenario in dispatch metadata. Adjust LIVEKIT_WS_URL, API keys, prompts, and static content as needed. Files: one file app.py (run with uvicorn)
Copy code
# app.py
import os
import json
import uuid
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import HTMLResponse, JSONResponse
from pydantic import BaseModel
from dotenv import load_dotenv
from livekit import api

load_dotenv()

API_KEY = os.getenv("LIVEKIT_API_KEY")
API_SECRET = os.getenv("LIVEKIT_API_SECRET")
LIVEKIT_WS_URL = os.getenv("LIVEKIT_WS_URL", "wss://your-project.livekit.cloud")

AGENT_NAME = "cloud-english-teacher"
AGENT_ID = "CA_e7hLTus66nKZ"

if not API_KEY or not API_SECRET:
    raise RuntimeError("Set LIVEKIT_API_KEY and LIVEKIT_API_SECRET environment variables")

app = FastAPI()

class TokenRequest(BaseModel):
    scenario: str
    preferred_room: str | None = None
    identity: str | None = None

@app.get("/", response_class=HTMLResponse)
async def index():
    # Minimal HTML + JS UI served by FastAPI
    html = f"""
<!doctype html>
<html>
<head>
  <meta charset="utf-8" />
  <title>AI English Teacher</title>
  <script src="https://unpkg.com/livekit-client/dist/livekit-client.min.js"></script>
  <style>
    body{{font-family: Arial; padding:20px; background:#121212; color:#eee}}
    select, button{{padding:8px; margin:8px 0}}
    pre{{background:#0f0f0f; padding:12px; max-height:300px; overflow:auto}}
  </style>
</head>
<body>
  <h2>AI English Teacher — Demo</h2>
  <label>Voice Provider: LiveKit Inference</label><br/>
  <label>Scenario:</label>
  <select id="scenario-select">
    <option value="english_teacher_general">English Teacher (General)</option>
    <option value="taxi">Taxi Driver</option>
    <option value="hotel_receptionist">Hotel Receptionist</option>
  </select>
  <br/>
  <button id="start-btn">Start Session</button>
  <pre id="log">Waiting for actions...\n</pre>

  <script>
    const API_TOKEN_ENDPOINT = "/api/token";
    const LIVEKIT_WS_URL = "{LIVEKIT_WS_URL}";

    function log(msg){ const p=document.getElementById("log"); p.innerText += msg + "\\n"; p.scrollTop = p.scrollHeight; }

    async function startSession() {{
      const scenario = document.getElementById("scenario-select").value;
      log("Requesting token for scenario: " + scenario);

      const resp = await fetch(API_TOKEN_ENDPOINT, {{
        method: "POST",
        headers: {{ "Content-Type": "application/json" }},
        body: JSON.stringify({{ scenario }})
      }});

      if (!resp.ok) {{
        const txt = await resp.text();
        log("Token request failed: " + txt);
        return;
      }}

      const {{ token, room, identity }} = await resp.json();
      log(`Token received. identity=${{identity}} room=${{room}}`);

      const {{ Room }} = livekit;
      const roomClient = new Room();

      roomClient.on("connected", () => log("Connected to LiveKit room: " + room));
      roomClient.on("disconnected", () => log("Disconnected"));
      roomClient.on("participantConnected", p => log("Participant connected: " + p.identity));
      roomClient.on("trackPublished", (pub, participant) => log(`Track published by ${{participant.identity}}`));

      try {{
        await roomClient.connect(LIVEKIT_WS_URL, token);
        log("Connected — waiting for agent dispatch...");
      }} catch (err) {{
        log("LiveKit connect error: " + err);
      }}
    }}

    document.getElementById("start-btn").addEventListener("click", startSession);
  </script>
</body>
</html>
"""
    return HTMLResponse(content=html)

@app.post("/api/token")
async def create_token(req: TokenRequest):
    identity = req.identity or f"user-{uuid.uuid4().hex[:12]}"
    room = req.preferred_room or f"english-teacher-{int(uuid.uuid4().int % 1_000_000_000)}"
    try:
        token = (
            api.AccessToken(API_KEY, API_SECRET)
            .with_identity(identity)
            .with_grants(api.VideoGrants(room_join=True, room=room))
            .with_room_config(api.RoomConfiguration(
                agents=[
                    api.RoomAgentDispatch(
                        agent_name=AGENT_NAME,
                        agent_id=AGENT_ID,
                        metadata=json.dumps({"scenario": req.scenario})
                    )
                ]
            ))
            .to_jwt()
        )
        return JSONResponse({"token": token, "room": room, "identity": identity})
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
Run: uvicorn app:app --reload --port 8000 Agent snippet (Python) • Ensure your agent runtime registers as "cloud-english-teacher" and is running. The agent reads scenario from job metadata and speaks after connect.
Copy code
# agent.py
import json
from livekit.agents import rtc_session, JobContext

@rtc_session(agent_name="cloud-english-teacher")
async def cloud_english_teacher(ctx: JobContext):
    await ctx.connect()
    job_meta = {}
    try:
        job_meta = json.loads(ctx.job.metadata or "{}")
    except Exception:
        pass

    scenario = job_meta.get("scenario", "english_teacher_general")
    prompts = {
        "english_teacher_general": "Hello! I'm your AI English teacher. Let's practice together.",
        "taxi": "Hi! Where would you like to go today?",
        "hotel_receptionist": "Welcome! How may I assist you with your check-in?"
    }
    greeting = prompts.get(scenario, "Hello! Let's begin.")
    await ctx.room.local_participant.say(greeting)

    # Keep the agent alive to handle conversation - adapt to your runtime
    # await ctx.wait_for_disconnect()
Notes and troubleshooting • Set LIVEKIT_API_KEY, LIVEKIT_API_SECRET in environment. Optionally set LIVEKIT_WS_URL. • The HTML served by FastAPI posts to /api/token so frontend and backend run together. • The token includes room and agent dispatch metadata so LiveKit will dispatch agent "cloud-english-teacher" to the created room when the user connects. • Confirm the agent process is running and registered under the exact name "cloud-english-teacher". Agent logs should show jobs received and the greeting being sent. • For testing, you can also run: lk dispatch create --new-room --agent-name cloud-english-teacher --room <room> --metadata '{"scenario":"english_teacher_general"}' Would you like this packaged as a single runnable repo layout (requirements.txt and run scripts)?
m
yes: Would you like this packaged as a single runnable repo layout (requirements.txt and run scripts)?
t
Below is a minimal runnable repo layout you can drop into a directory. It includes requirements, start scripts, FastAPI app serving the HTML/JS and token endpoint, the Python agent, and an example .env. Follow the steps to run the demo. Files: • requirements.txt • .env.example • run_backend.sh • run_agent.sh • app.py • agent.py • README.md requirements.txt
Copy code
fastapi[all]==0.95.2
uvicorn[standard]==0.22.0
python-dotenv==1.0.0
livekit==1.0.3
.env.example
Copy code
LIVEKIT_API_KEY=your_api_key_here
LIVEKIT_API_SECRET=your_api_secret_here
LIVEKIT_WS_URL=wss://your-project.livekit.cloud
run_backend.sh
Copy code
#!/usr/bin/env bash
export $(grep -v '^#' .env | xargs)
uvicorn app:app --reload --port 8000
run_agent.sh
Copy code
#!/usr/bin/env bash
export $(grep -v '^#' .env | xargs)
python agent.py
app.py
Copy code
import os
import json
import uuid
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse, JSONResponse
from pydantic import BaseModel
from dotenv import load_dotenv
from livekit import api

load_dotenv()

API_KEY = os.getenv("LIVEKIT_API_KEY")
API_SECRET = os.getenv("LIVEKIT_API_SECRET")
LIVEKIT_WS_URL = os.getenv("LIVEKIT_WS_URL", "wss://your-project.livekit.cloud")

AGENT_NAME = "cloud-english-teacher"
AGENT_ID = "CA_e7hLTus66nKZ"

if not API_KEY or not API_SECRET:
    raise RuntimeError("Set LIVEKIT_API_KEY and LIVEKIT_API_SECRET environment variables")

app = FastAPI()

class TokenRequest(BaseModel):
    scenario: str
    preferred_room: str | None = None
    identity: str | None = None

@app.get("/", response_class=HTMLResponse)
async def index():
    html = f"""
<!doctype html>
<html>
<head>
  <meta charset="utf-8" />
  <title>AI English Teacher — Demo</title>
  <script src="https://unpkg.com/livekit-client/dist/livekit-client.min.js"></script>
  <style>
    body{{font-family: Arial; padding:20px; background:#121212; color:#eee}}
    select, button{{padding:8px; margin:8px 0}}
    pre{{background:#0f0f0f; padding:12px; max-height:300px; overflow:auto}}
  </style>
</head>
<body>
  <h2>AI English Teacher — Demo</h2>
  <label>Scenario:</label>
  <select id="scenario-select">
    <option value="english_teacher_general">English Teacher (General)</option>
    <option value="taxi">Taxi Driver</option>
    <option value="hotel_receptionist">Hotel Receptionist</option>
  </select>
  <br/>
  <button id="start-btn">Start Session</button>
  <pre id="log">Waiting for actions...\n</pre>

  <script>
    const API_TOKEN_ENDPOINT = "/api/token";
    const LIVEKIT_WS_URL = "{LIVEKIT_WS_URL}";

    function log(msg){ const p=document.getElementById("log"); p.innerText += msg + "\\n"; p.scrollTop = p.scrollHeight; }

    async function startSession() {{
      const scenario = document.getElementById("scenario-select").value;
      log("Requesting token for scenario: " + scenario);

      const resp = await fetch(API_TOKEN_ENDPOINT, {{
        method: "POST",
        headers: {{ "Content-Type": "application/json" }},
        body: JSON.stringify({{ scenario }})
      }});

      if (!resp.ok) {{
        const txt = await resp.text();
        log("Token request failed: " + txt);
        return;
      }}

      const {{ token, room, identity }} = await resp.json();
      log(`Token received. identity=${{identity}} room=${{room}}`);

      const {{ Room }} = livekit;
      const roomClient = new Room();

      roomClient.on("connected", () => log("Connected to LiveKit room: " + room));
      roomClient.on("disconnected", () => log("Disconnected"));
      roomClient.on("participantConnected", p => log("Participant connected: " + p.identity));
      roomClient.on("trackPublished", (pub, participant) => log(`Track published by ${{participant.identity}}`));

      try {{
        await roomClient.connect(LIVEKIT_WS_URL, token);
        log("Connected — waiting for agent dispatch...");
      }} catch (err) {{
        log("LiveKit connect error: " + err);
      }}
    }}

    document.getElementById("start-btn").addEventListener("click", startSession);
  </script>
</body>
</html>
"""
    return HTMLResponse(content=html)

@app.post("/api/token")
async def create_token(req: TokenRequest):
    identity = req.identity or f"user-{uuid.uuid4().hex[:12]}"
    room = req.preferred_room or f"english-teacher-{int(uuid.uuid4().int % 1_000_000_000)}"
    try:
        token = (
            api.AccessToken(API_KEY, API_SECRET)
            .with_identity(identity)
            .with_grants(api.VideoGrants(room_join=True, room=room))
            .with_room_config(api.RoomConfiguration(
                agents=[
                    api.RoomAgentDispatch(
                        agent_name=AGENT_NAME,
                        agent_id=AGENT_ID,
                        metadata=json.dumps({"scenario": req.scenario})
                    )
                ]
            ))
            .to_jwt()
        )
        return JSONResponse({"token": token, "room": room, "identity": identity})
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
agent.py
Copy code
import asyncio
import json
from dotenv import load_dotenv
from livekit.agents import rtc_session, JobContext, server

load_dotenv()

# Ensure your agent runtime is configured to connect to the same LiveKit project.
# This snippet assumes you run it with your agent framework/startup that registers with LiveKit.
@rtc_session(agent_name="cloud-english-teacher")
async def cloud_english_teacher(ctx: JobContext):
    await ctx.connect()
    job_meta = {}
    try:
        job_meta = json.loads(ctx.job.metadata or "{}")
    except Exception:
        pass

    scenario = job_meta.get("scenario", "english_teacher_general")
    prompts = {
        "english_teacher_general": "Hello! I'm your AI English teacher. Let's practice together.",
        "taxi": "Hi! Where would you like to go today?",
        "hotel_receptionist": "Welcome! How may I assist you with your check-in?"
    }
    greeting = prompts.get(scenario, "Hello! Let's begin.")
    await ctx.room.local_participant.say(greeting)

    # Keep running until disconnected (adjust per your agent framework)
    while not ctx.room.is_closed:
        await asyncio.sleep(1)

# Minimal runner if using the built-in agent server helper (depends on your agent runtime)
if __name__ == "__main__":
    # If your agent framework provides a server.run or similar, invoke it here.
    # For many setups, the agent runtime auto-discovers decorators and runs.
    # Replace with your agent startup method as needed.
    try:
        server.run_app()  # adjust if your runtime differs
    except Exception:
        # fallback simple loop to keep the process alive for demo purposes
        import asyncio
        asyncio.get_event_loop().run_forever()
README.md
Copy code
# LiveKit Agent Demo — cloud-english-teacher

1. Copy .env.example to .env and set LIVEKIT_API_KEY and LIVEKIT_API_SECRET (and LIVEKIT_WS_URL if needed).

2. Install dependencies:
   pip install -r requirements.txt

3. Start backend (serves UI + token endpoint):
   chmod +x run_backend.sh
   ./run_backend.sh

4. Start agent (in a separate terminal):
   chmod +x run_agent.sh
   ./run_agent.sh

5. Open http://localhost:8000 in a browser, select a scenario and click Start Session.
   The backend will return a token containing a RoomConfiguration dispatch for agent "cloud-english-teacher".
   The agent should receive the job, join the room, and send the greeting.

Notes:
- Adjust agent startup (agent.py) to fit your agent runtime if you use a different runner.
- Use `lk dispatch create` to manually test dispatch.
- Check logs for agent job receipts and greeting messages.
If you want, I can: • Provide a GitHub-ready zip of these files, • Tighten the agent runner to a specific agent framework you use, • Add Dockerfiles for the backend and agent. Which would you like next?
m
Yes—the repo uses LiveKit’s agent framework. The backend entrypoint (agent/main.py) imports livekit.agents, defines an EnglishTeacherAgent, and registers it via cli.run_app(...) so LiveKit handles session dispatch. There’s no separate custom framework; it’s the LiveKit agent SDK plus their plugins (OpenAI/Gemini/Inference).
t
Below is a runnable repo layout tailored to your setup: FastAPI backend that serves the HTML/JS and a LiveKit agent implemented with the LiveKit agent framework using cli.run_app(...) as the entrypoint. Replace keys, adjust prompts, and install deps per instructions. Files: • requirements.txt • .env.example • run_backend.sh • run_agent.sh • backend/app.py • agent/main.py • README.md requirements.txt
Copy code
fastapi[all]==0.95.2
uvicorn[standard]==0.22.0
python-dotenv==1.0.0
livekit==1.0.3
.env.example
Copy code
# LiveKit credentials
LIVEKIT_API_KEY=your_api_key_here
LIVEKIT_API_SECRET=your_api_secret_here
LIVEKIT_WS_URL=wss://your-project.livekit.cloud
# Optional: change agent name/id if needed
AGENT_NAME=cloud-english-teacher
AGENT_ID=CA_e7hLTus66nKZ
run_backend.sh
Copy code
#!/usr/bin/env bash
export $(grep -v '^#' .env | xargs)
uvicorn backend.app:app --reload --port 8000
run_agent.sh
Copy code
#!/usr/bin/env bash
export $(grep -v '^#' .env | xargs)
python agent/main.py
backend/app.py
Copy code
import os
import json
import uuid
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse, JSONResponse
from pydantic import BaseModel
from dotenv import load_dotenv
from livekit import api

load_dotenv()

API_KEY = os.getenv("LIVEKIT_API_KEY")
API_SECRET = os.getenv("LIVEKIT_API_SECRET")
LIVEKIT_WS_URL = os.getenv("LIVEKIT_WS_URL", "wss://your-project.livekit.cloud")
AGENT_NAME = os.getenv("AGENT_NAME", "cloud-english-teacher")
AGENT_ID = os.getenv("AGENT_ID", "CA_e7hLTus66nKZ")

if not API_KEY or not API_SECRET:
    raise RuntimeError("Set LIVEKIT_API_KEY and LIVEKIT_API_SECRET environment variables")

app = FastAPI()

class TokenRequest(BaseModel):
    scenario: str
    preferred_room: str | None = None
    identity: str | None = None

@app.get("/", response_class=HTMLResponse)
async def index():
    html = f"""
<!doctype html>
<html>
<head>
  <meta charset="utf-8" />
  <title>AI English Teacher — Demo</title>
  <script src="https://unpkg.com/livekit-client/dist/livekit-client.min.js"></script>
  <style>
    body{{font-family: Arial; padding:20px; background:#121212; color:#eee}}
    select, button{{padding:8px; margin:8px 0}}
    pre{{background:#0f0f0f; padding:12px; max-height:300px; overflow:auto}}
  </style>
</head>
<body>
  <h2>AI English Teacher — Demo</h2>
  <label>Scenario:</label>
  <select id="scenario-select">
    <option value="english_teacher_general">English Teacher (General)</option>
    <option value="taxi">Taxi Driver</option>
    <option value="hotel_receptionist">Hotel Receptionist</option>
  </select>
  <br/>
  <button id="start-btn">Start Session</button>
  <pre id="log">Waiting for actions...\n</pre>

  <script>
    const API_TOKEN_ENDPOINT = "/api/token";
    const LIVEKIT_WS_URL = "{LIVEKIT_WS_URL}";

    function log(msg){ const p=document.getElementById("log"); p.innerText += msg + "\\n"; p.scrollTop = p.scrollHeight; }

    async function startSession() {{
      const scenario = document.getElementById("scenario-select").value;
      log("Requesting token for scenario: " + scenario);

      const resp = await fetch(API_TOKEN_ENDPOINT, {{
        method: "POST",
        headers: {{ "Content-Type": "application/json" }},
        body: JSON.stringify({{ scenario }})
      }});

      if (!resp.ok) {{
        const txt = await resp.text();
        log("Token request failed: " + txt);
        return;
      }}

      const {{ token, room, identity }} = await resp.json();
      log(`Token received. identity=${{identity}} room=${{room}}`);

      const {{ Room }} = livekit;
      const roomClient = new Room();

      roomClient.on("connected", () => log("Connected to LiveKit room: " + room));
      roomClient.on("disconnected", () => log("Disconnected"));
      roomClient.on("participantConnected", p => log("Participant connected: " + p.identity));
      roomClient.on("trackPublished", (pub, participant) => log(`Track published by ${{participant.identity}}`));

      try {{
        await roomClient.connect(LIVEKIT_WS_URL, token);
        log("Connected — waiting for agent dispatch...");
      }} catch (err) {{
        log("LiveKit connect error: " + err);
      }}
    }}

    document.getElementById("start-btn").addEventListener("click", startSession);
  </script>
</body>
</html>
"""
    return HTMLResponse(content=html)

@app.post("/api/token")
async def create_token(req: TokenRequest):
    identity = req.identity or f"user-{uuid.uuid4().hex[:12]}"
    room = req.preferred_room or f"english-teacher-{int(uuid.uuid4().int % 1_000_000_000)}"
    try:
        token = (
            api.AccessToken(API_KEY, API_SECRET)
            .with_identity(identity)
            .with_grants(api.VideoGrants(room_join=True, room=room))
            .with_room_config(api.RoomConfiguration(
                agents=[
                    api.RoomAgentDispatch(
                        agent_name=AGENT_NAME,
                        agent_id=AGENT_ID,
                        metadata=json.dumps({"scenario": req.scenario})
                    )
                ]
            ))
            .to_jwt()
        )
        return JSONResponse({"token": token, "room": room, "identity": identity})
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
agent/main.py
Copy code
import os
import json
import asyncio
from dotenv import load_dotenv
from livekit.agents import rtc_session, JobContext, server, cli

load_dotenv()

AGENT_NAME = os.getenv("AGENT_NAME", "cloud-english-teacher")

# Your LiveKit agent function. Use the LiveKit agent SDK and plugins as needed.
@rtc_session(agent_name=AGENT_NAME)
async def english_teacher_agent(ctx: JobContext):
    # Connect agent to the room
    await ctx.connect()
    # Read scenario from dispatch metadata
    job_meta = {}
    try:
        job_meta = json.loads(ctx.job.metadata or "{}")
    except Exception:
        pass

    scenario = job_meta.get("scenario", "english_teacher_general")
    prompts = {
        "english_teacher_general": "Hello! I'm your AI English teacher. Let's practice together.",
        "taxi": "Hi! Where would you like to go today?",
        "hotel_receptionist": "Welcome! How may I assist you with your check-in?"
    }
    greeting = prompts.get(scenario, "Hello! Let's begin.")

    # Speak immediately
    await ctx.room.local_participant.say(greeting)

    # Example: keep agent alive to handle conversation until disconnected
    while not ctx.room.is_closed:
        await asyncio.sleep(1)

# Use LiveKit's CLI runner to start the agent process so it receives dispatched jobs.
if __name__ == "__main__":
    # cli.run_app will start the agent worker that listens for dispatch jobs.
    cli.run_app()
README.md
Copy code
# LiveKit Agent Demo (single-repo)

1. Copy .env.example to .env and set LIVEKIT_API_KEY and LIVEKIT_API_SECRET (and LIVEKIT_WS_URL if needed).

2. Install dependencies:
   pip install -r requirements.txt

3. Start backend (serves UI + token endpoint):
   chmod +x run_backend.sh
   ./run_backend.sh

4. Start agent (in a separate terminal):
   chmod +x run_agent.sh
   ./run_agent.sh

5. Open http://localhost:8000 in a browser, select a scenario and click Start Session.
   The backend returns a token containing a RoomConfiguration dispatch for agent "cloud-english-teacher".
   The LiveKit agent framework (agent/main.py via cli.run_app) should receive the job, join the room, and send the greeting.

Troubleshooting:
- Ensure the agent process logs show job receipts and join messages.
- If agent doesn't join, verify AGENT_NAME exactly matches the value in the token's RoomAgentDispatch.
- Use `lk dispatch create ...` for manual tests.
- Confirm LIVEKIT_WS_URL points to your LiveKit project.
That’s ready to drop into a repo. Want me to: • produce a zipped repo you can download, • add Dockerfiles for backend and agent, • or adjust agent prompts to include OpenAI/Gemini plugin integration examples?
m
share docker files
t
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 1. 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?
m
this is great thanks what voice provider etc are we using here ? not we are using inference for all api keys not our wonn
t
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?
m
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 ?
all using inference
t
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?
m
• both of these please 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.
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!