modern-winter-66316
12/05/2025, 9:12 PMtall-airline-16756
12/05/2025, 9:12 PMtall-airline-16756
12/05/2025, 9:12 PMmodern-winter-66316
12/05/2025, 9:14 PMtall-airline-16756
12/05/2025, 9:14 PMtrackID 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):
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:
@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:
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 docsmodern-winter-66316
12/05/2025, 9:16 PMtall-airline-16756
12/05/2025, 9:17 PMCA_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):
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:
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?modern-winter-66316
12/05/2025, 9:19 PMtall-airline-16756
12/05/2025, 9:20 PMCA_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:
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:
@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:
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 Docsmodern-winter-66316
12/05/2025, 9:27 PMtall-airline-16756
12/05/2025, 9:27 PM# 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.
<!-- 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?modern-winter-66316
12/05/2025, 9:28 PMtall-airline-16756
12/05/2025, 9:29 PM# 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.
<!-- 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.
# 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?modern-winter-66316
12/05/2025, 9:30 PMtall-airline-16756
12/05/2025, 9:30 PM# 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.
# 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)?modern-winter-66316
12/05/2025, 9:31 PMtall-airline-16756
12/05/2025, 9:31 PMfastapi[all]==0.95.2
uvicorn[standard]==0.22.0
python-dotenv==1.0.0
livekit==1.0.3
.env.example
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
#!/usr/bin/env bash
export $(grep -v '^#' .env | xargs)
uvicorn app:app --reload --port 8000
run_agent.sh
#!/usr/bin/env bash
export $(grep -v '^#' .env | xargs)
python agent.py
app.py
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
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
# 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?modern-winter-66316
12/05/2025, 9:33 PMtall-airline-16756
12/05/2025, 9:34 PMfastapi[all]==0.95.2
uvicorn[standard]==0.22.0
python-dotenv==1.0.0
livekit==1.0.3
.env.example
# 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
#!/usr/bin/env bash
export $(grep -v '^#' .env | xargs)
uvicorn backend.app:app --reload --port 8000
run_agent.sh
#!/usr/bin/env bash
export $(grep -v '^#' .env | xargs)
python agent/main.py
backend/app.py
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
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
# 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?modern-winter-66316
12/05/2025, 9:34 PMtall-airline-16756
12/05/2025, 9:35 PMFROM 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)
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)
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/)
fastapi[all]==0.95.2
uvicorn[standard]==0.22.0
python-dotenv==1.0.0
livekit==1.0.3
.dockerignore (root)
__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?modern-winter-66316
12/05/2025, 9:40 PMtall-airline-16756
12/05/2025, 9:41 PMctx.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?modern-winter-66316
12/05/2025, 9:42 PMmodern-winter-66316
12/05/2025, 9:42 PMtall-airline-16756
12/05/2025, 9:43 PMscenario).
• 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):
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?modern-winter-66316
12/05/2025, 9:44 PMtts_model and llm_model in dispatch metadata so selection is driven from the frontend.tall-airline-16756
12/05/2025, 9:45 PM