modern-winter-66316
12/05/2025, 11:47 PMtall-airline-16756
12/05/2025, 11:47 PMtall-airline-16756
12/05/2025, 11:48 PMmodern-winter-66316
12/05/2025, 11:48 PMwss://turbo-ms4yz8cm.livekit.cloud
◦ All STT/LLM/TTS routed via LiveKit Inference
◦ Env vars for creds (I will paste them)
• Rooms: Create one new room per lesson
• Docker: Simple Dockerfile + docker-compose (Windows compatible)
Agent behavior (one persona only):
• English Teacher (General)
• Friendly, natural conversation
• Adjusts difficulty
• Gives quick feedback + one actionable tip
Deliverables:
• FastAPI backend with:
◦ POST /create-room
◦ POST /start-lesson (creates AgentSession + joins room)
◦ GET /health
• Agent worker using the single persona + single voice
• Minimal HTML/JS frontend to:
◦ Start lesson
◦ Join room via WebRTC
◦ Show transcripts
◦ Play agent audio
• Dockerfile + docker-compose
• Clear setup + Vercel deployment instructionstall-airline-16756
12/05/2025, 11:48 PMmodern-winter-66316
12/05/2025, 11:48 PMtall-airline-16756
12/05/2025, 11:49 PMPOST /start-lesson is called (agent auto-joins and begins speaking), or should the agent wait until a human student publishes audio before starting?modern-winter-66316
12/05/2025, 11:49 PMtall-airline-16756
12/05/2025, 11:49 PMmodern-winter-66316
12/05/2025, 11:50 PMtall-airline-16756
12/05/2025, 11:51 PMCA_e7hLTus66nKZ for RoomAgentDispatch, or prefer the name cloud-english-teacher?
2. Model identifiers — confirm these exact strings:
◦ STT: deepgram/nova-3
◦ LLM: openai/gpt-4.1-mini
◦ TTS: cartesia/sonic-2
1. Provider keys: will STT/LLM/TTS provider keys be configured in LiveKit Cloud, or do you want the backend to provide them via env vars? If backend, please name the env vars you’ll use (don’t paste secrets if you prefer not to).
2. Room naming: should the backend generate room names like lesson-{uuid} (recommended) or accept a client-supplied room_name?
3. Token return behavior: confirm both endpoints should return a freshly minted student token (you said yes)—and that /start-lesson should also trigger agent auto-join immediately.
4. Docker layout: do you want the FastAPI server and agent worker as separate services in docker-compose (recommended), or a single container?
Reply with confirmations (short answers) and I’ll produce the full FastAPI code, agent wiring, Dockerfile/docker-compose, and run instructions.
Sources: CreateRoom() is Taking Too Long | SDKs | livekit/livekit_composite | DeepWiki | Agent dispatch | LiveKit docs | Generating tokens | LiveKit docsmodern-winter-66316
12/05/2025, 11:52 PMtall-airline-16756
12/05/2025, 11:53 PMimport os
import uuid
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from livekit import api
from livekit.protocol import livekit as proto_livekit
load_dotenv()
LIVEKIT_URL = os.getenv("LIVEKIT_URL", "wss://turbo-ms4yz8cm.livekit.cloud")
LIVEKIT_API_KEY = os.getenv("LIVEKIT_API_KEY")
LIVEKIT_API_SECRET = os.getenv("LIVEKIT_API_SECRET")
if not LIVEKIT_API_KEY or not LIVEKIT_API_SECRET:
raise RuntimeError("Please set LIVEKIT_API_KEY and LIVEKIT_API_SECRET in environment")
app = FastAPI()
class TokenResponse(BaseModel):
token: str
room_name: str
url: str
def make_student_identity():
return f"student-{uuid.uuid4().hex[:8]}"
def make_room_name():
return f"lesson-{uuid.uuid4().hex[:8]}"
@app.get("/health")
def health():
return {"status": "ok"}
@app.post("/create-room", response_model=TokenResponse)
def create_room():
"""
Create a new lesson room and return a token for the student to join.
This endpoint does NOT dispatch the agent; use /start-lesson to auto-join the agent.
"""
room_name = make_room_name()
identity = make_student_identity()
try:
grants = api.VideoGrants(
room_join=True,
room=room_name,
can_publish=True,
can_subscribe=True,
can_publish_data=True,
)
token = (
api.AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET)
.with_identity(identity)
.with_name("Student")
.with_grants(grants)
.to_jwt()
)
return TokenResponse(token=token, room_name=room_name, url=LIVEKIT_URL)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Token generation failed: {e}")
@app.post("/start-lesson", response_model=TokenResponse)
def start_lesson():
"""
Create a new lesson room and return a token for the student to join.
The returned token includes RoomConfiguration with RoomAgentDispatch so the
agent named "cloud-english-teacher" auto-joins when the student connects.
"""
room_name = make_room_name()
identity = make_student_identity()
try:
grants = api.VideoGrants(
room_join=True,
room=room_name,
can_publish=True,
can_subscribe=True,
can_publish_data=True,
)
# RoomAgentDispatch: agent auto-joins the room when this token is used.
room_config = proto_livekit.RoomConfiguration(
agents=[
proto_livekit.RoomAgentDispatch(
agent_name="cloud-english-teacher",
# include agent_id if desired, but name is primary
agent_id="CA_e7hLTus66nKZ",
metadata='{"role":"tutor","persona":"english_teacher"}',
)
]
)
token = (
api.AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET)
.with_identity(identity)
.with_name("Student")
.with_grants(grants)
.with_room_config(room_config)
.to_jwt()
)
return TokenResponse(token=token, room_name=room_name, url=LIVEKIT_URL)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Token generation failed: {e}")
requirements.txt
fastapi
uvicorn[standard]
python-dotenv
livekit-api
.env.example
LIVEKIT_URL=wss://turbo-ms4yz8cm.livekit.cloud
LIVEKIT_API_KEY=your_livekit_api_key_here
LIVEKIT_API_SECRET=your_livekit_api_secret_here
Notes and next steps
• The agent must be registered/available in your LiveKit Cloud project as name "cloud-english-teacher" (agent ID CA_e7hLTus66nKZ can be included for clarity).
• The models (deepgram/nova-3, openai/gpt-4.1-mini, cartesia/sonic-2) are configured in LiveKit Cloud provider settings — backend does not need provider keys.
• /create-room returns a token without agent dispatch. /start-lesson returns a token that includes RoomAgentDispatch so the agent auto-joins and may begin speaking immediately.
• Tokens include publish rights so the student can send audio. Frontend should call room.connect(url, token) using the returned fields.
• I can now provide:
◦ The agent worker code wired to deepgram/openai/cartesia (as a separate Docker service)
◦ Dockerfile + docker-compose (Windows-compatible) with separate services for fastapi and agent-worker
◦ Minimal HTML/JS frontend that requests /start-lesson and connects via WebRTC
◦ Vercel deployment instructions for the frontend
Which of those would you like next?
Sources: Authentication | LiveKit docs | server-sdk-js | livekit/livekit_composite | DeepWiki | Agent dispatch | LiveKit docs | server-sdk-ruby | livekit/livekit_composite | DeepWiki | Speech-to-text (STT) models | LiveKit Docsmodern-winter-66316
12/05/2025, 11:56 PMtall-airline-16756
12/05/2025, 11:58 PMimport os
import asyncio
from dotenv import load_dotenv
from livekit.agents import cli, WorkerOptions, JobContext
from livekit.agents.voice import AgentSession, Agent
from livekit.agents.llm import ChatContext
# Load env
load_dotenv()
# Agent configuration (matches RoomAgentDispatch.agent_name)
AGENT_NAME = "cloud-english-teacher"
AGENT_ID = "CA_e7hLTus66nKZ" # optional metadata usage
# Models to route via LiveKit Inference
STT_MODEL = "deepgram/nova-3"
LLM_MODEL = "openai/gpt-4.1-mini"
TTS_MODEL = "cartesia/sonic-2"
# System prompt / persona
SYSTEM_PROMPT = (
"You are a friendly, patient English teacher. "
"Speak naturally and clearly in English. Ask follow-ups, "
"adjust difficulty to the user, give quick feedback, and "
"end each reply with one actionable tip."
)
class EnglishTeacherAgent(Agent):
def __init__(self):
# Agent uses a chat context with a system prompt
ctx = ChatContext()
ctx.append({"role": "system", "content": SYSTEM_PROMPT})
super().__init__(chat_ctx=ctx)
async def entrypoint(job: JobContext):
# job.room is available when dispatched
print(f"[agent] dispatched to room {job.room.name}")
# Connect to the room (auto-subscribe audio)
await job.connect()
# Create AgentSession wired to LiveKit Inference model strings
session = AgentSession(
ctx=job,
agent=EnglishTeacherAgent(),
stt=STT_MODEL,
llm=LLM_MODEL,
tts=TTS_MODEL,
# enable recommended audio preprocessing if available
enable_noise_cancellation=True,
)
# Start the session: this will subscribe to audio and route through STT/LLM/TTS
await session.start(room=job.room)
# Greet immediately when agent auto-joins
await session.say("Hello! I'm your English teacher. Let's practice conversational English now.", allow_interruptions=False)
# Keep session alive while room exists; session lifecycle is managed by framework
try:
await session.wait_closed()
except asyncio.CancelledError:
pass
if __name__ == "__main__":
# WorkerOptions registers worker with LiveKit using entrypoint; matching by agent_name
opts = WorkerOptions(entrypoint_fnc=entrypoint, agent_name=AGENT_NAME)
cli.run_app(opts)
agent/pyproject.toml
[project]
name = "english-teacher-agent"
version = "0.1.0"
dependencies = [
"python-dotenv",
"livekit-agents~=1.0",
]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
agent/Dockerfile
# Use slim Python base that works on Windows-hosted Docker
FROM python:3.11-slim
WORKDIR /app
# Install system deps needed for some packages
RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential \
&& rm -rf /var/lib/apt/lists/*
# Copy dependency definition and install
COPY pyproject.toml /app/pyproject.toml
RUN pip install --upgrade pip hatchling && pip install -e .
# Copy agent code
COPY agent.py /app/agent.py
# Create non-root user
RUN useradd --create-home --shell /bin/bash appuser && chown -R appuser /app
USER appuser
ENV PYTHONUNBUFFERED=1
CMD ["python", "agent.py"]
agent/.env.example
# LiveKit Cloud (set these in your .env used by docker-compose)
LIVEKIT_URL=wss://turbo-ms4yz8cm.livekit.cloud
LIVEKIT_API_KEY=your_livekit_api_key
LIVEKIT_API_SECRET=your_livekit_api_secret
# Optional runtime controls
LOG_LEVEL=info
Run instructions (separate service)
1. Place these files under an agent/ directory.
2. Copy .env.example to .env and set LIVEKIT_API_KEY and LIVEKIT_API_SECRET.
3. Build image:
◦ docker build -t cloud-english-teacher-agent -f agent/Dockerfile agent/
1. Run container with env:
◦ docker run --env-file agent/.env --name english-agent cloud-english-teacher-agent
Docker-compose note (integrate with your FastAPI service)
• In your docker-compose.yml, add a service:
◦ image: cloud-english-teacher-agent
◦ env_file: ./agent/.env
◦ restart: unless-stopped
Behavior notes
• The worker registers as agent_name "cloud-english-teacher" via WorkerOptions; RoomAgentDispatch(agent_name="cloud-english-teacher") in tokens will auto-dispatch this worker to join rooms.
• STT/LLM/TTS use the LiveKit Inference model strings you specified; provider keys remain configured in LiveKit Cloud.
• The agent greets immediately on join and then continues handling the session. The system prompt enforces persona (friendly, adjusts difficulty, quick feedback + one tip).
• If you want extra control (difficulty tracking, adaptive prompts, explicit turn-taking), I can add that logic next.
Would you like the agent to log transcripts to a file or expose a small HTTP status endpoint in the agent container?
Sources: Introducing LiveKit Inference: A unified model interface for voice AI | Models | LiveKit Docs | Agents v0.x migration guide - Node.js | LiveKit Docs | examples/drive-thru | livekit/livekit_composite | DeepWiki | OpenAI LLM models | LiveKit Docsmodern-winter-66316
12/05/2025, 11:58 PMtall-airline-16756
12/05/2025, 11:58 PMversion: "3.8"
services:
fastapi:
build:
context: .
dockerfile: Dockerfile.api
container_name: livekit_fastapi
env_file:
- .env
ports:
- "8000:8000"
restart: unless-stopped
english-agent:
build:
context: ./agent
dockerfile: Dockerfile
container_name: livekit_english_agent
env_file:
- .env
depends_on:
- fastapi
restart: unless-stopped
Place files
• Root:
◦ Dockerfile.api (FastAPI image)
◦ main.py, requirements.txt, .env.example -> copy to .env and add LIVEKIT_API_KEY & LIVEKIT_API_SECRET
• agent/:
◦ agent.py, pyproject.toml, Dockerfile, .env.example (copy to .env if testing locally)
Build & run
1. Create root .env from .env.example and set:
◦ LIVEKIT_URL=wss://turbo-ms4yz8cm.livekit.cloud
◦ LIVEKIT_API_KEY=...
◦ LIVEKIT_API_SECRET=...
1. From project root:
◦ docker-compose up --build
Notes
• The agent container uses LIVEKIT credentials from the same .env so it can connect to LiveKit Cloud and be dispatched by tokens your FastAPI issues (RoomAgentDispatch with agent_name "cloud-english-teacher").
• fastapi exposes port 8000 for /create-room, /start-lesson, /health.
• For Windows Docker Desktop, use WSL2 backend or ensure file permissions allow Docker to read .env.
• If you want logs or transcript persistence, I can add a volume and logging config.modern-winter-66316
12/06/2025, 12:02 AMtall-airline-16756
12/06/2025, 12:02 AMFROM 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 requirements.txt /app/requirements.txt
RUN pip install --no-cache-dir -r /app/requirements.txt
COPY main.py /app/main.py
ENV PYTHONUNBUFFERED=1
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
2) FastAPI requirements.txt
fastapi
uvicorn[standard]
python-dotenv
livekit-api
3) .env.example (root; copy to .env and fill keys)
LIVEKIT_URL=wss://turbo-ms4yz8cm.livekit.cloud
LIVEKIT_API_KEY=your_livekit_api_key_here
LIVEKIT_API_SECRET=your_livekit_api_secret_here
4) Minimal frontend (static index.html). Put in e.g., frontend/index.html. This uses livekit-client JS (CDN) to connect; replace CDN import if you host libs yourself.
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>English Lesson</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
#transcript { white-space: pre-wrap; border: 1px solid #ddd; padding: 10px; height: 120px; overflow: auto; }
</style>
</head>
<body>
<h2>LiveKit English Lesson</h2>
<button id="start">Start Lesson (auto agent)</button>
<div>
<p>Room: <span id="roomName">—</span></p>
<p>Identity: <span id="identity">student</span></p>
</div>
<div>
<h4>Transcript</h4>
<div id="transcript">—</div>
</div>
<script src="https://unpkg.com/livekit-client/dist/livekit-client.min.js"></script>
<script>
const startBtn = document.getElementById('start');
const transcriptEl = document.getElementById('transcript');
const roomNameEl = document.getElementById('roomName');
async function getTokenAndJoin() {
startBtn.disabled = true;
// Request /start-lesson from backend
const res = await fetch('/start-lesson', { method: 'POST' });
if (!res.ok) {
alert('Failed to start lesson');
startBtn.disabled = false;
return;
}
const data = await res.json();
const { token, room_name, url } = data;
roomNameEl.textContent = room_name;
// connect via LiveKit client
const room = new livekit.Room();
room.on('participantConnected', p => {
console.log('participantConnected', p.identity);
});
room.on('trackPublished', (publication, participant) => {
console.log('trackPublished', participant.identity, publication.trackName);
});
// Subscribe to remote audio and capture transcripts via data messages if agent sends them
room.on('dataReceived', (payload, participant) => {
try {
const text = new TextDecoder().decode(payload);
transcriptEl.textContent += `\n${participant.identity}: ${text}`;
} catch (e) {
console.log('data message decode error', e);
}
});
// Connect to LiveKit
await room.connect(url, token, { autoSubscribe: true });
// Publish local microphone
const pc = await navigator.mediaDevices.getUserMedia({ audio: true });
await room.localParticipant.publishTrack(pc.getTracks()[0]);
// Listen for remote audio; LiveKit client plays audio automatically for subscribed audio tracks
room.on('trackSubscribed', (track, publication, participant) => {
if (track.kind === 'audio') {
// track.play() is handled by the library on attach; but ensure it's attached if needed
const el = track.attach();
el.style.display = 'none';
document.body.appendChild(el);
}
});
}
startBtn.addEventListener('click', getTokenAndJoin);
</script>
</body>
</html>
Notes
• Place index.html on a static server (can be served from FastAPI static files or Vercel). If serving from FastAPI, add a static route or serve via a simple HTTP server.
• The frontend expects the backend endpoints at the same origin; if your frontend is served elsewhere, update fetch URL to the backend full URL and ensure CORS is enabled on FastAPI (main.py earlier allowed all origins).
• Transcripts: agent may send transcripts over LiveKit data channels or you can surface STT results via your backend; the frontend listens for data messages as a simple hook.
If you want, I will:
• Add static file serving in FastAPI so / serves index.html.
• Add transcript publishing from the agent (data messages) or server-side logging.
• Provide final docker-compose (already shared) or push-to-Vercel steps for the frontend.modern-winter-66316
12/06/2025, 12:10 AMtall-airline-16756
12/06/2025, 12:10 AMimport os
import uuid
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from livekit import api
from livekit.protocol import livekit as proto_livekit
load_dotenv()
LIVEKIT_URL = os.getenv("LIVEKIT_URL", "wss://turbo-ms4yz8cm.livekit.cloud")
LIVEKIT_API_KEY = os.getenv("LIVEKIT_API_KEY")
LIVEKIT_API_SECRET = os.getenv("LIVEKIT_API_SECRET")
if not LIVEKIT_API_KEY or not LIVEKIT_API_SECRET:
raise RuntimeError("Please set LIVEKIT_API_KEY and LIVEKIT_API_SECRET in environment")
app = FastAPI()
# Serve the frontend static files from ./static
app.mount("/", StaticFiles(directory="static", html=True), name="static")
class TokenResponse(BaseModel):
token: str
room_name: str
url: str
def make_student_identity():
return f"student-{uuid.uuid4().hex[:8]}"
def make_room_name():
return f"lesson-{uuid.uuid4().hex[:8]}"
@app.get("/health")
def health():
return {"status": "ok"}
@app.post("/create-room", response_model=TokenResponse)
def create_room():
room_name = make_room_name()
identity = make_student_identity()
try:
grants = api.VideoGrants(
room_join=True,
room=room_name,
can_publish=True,
can_subscribe=True,
can_publish_data=True,
)
token = (
api.AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET)
.with_identity(identity)
.with_name("Student")
.with_grants(grants)
.to_jwt()
)
return TokenResponse(token=token, room_name=room_name, url=LIVEKIT_URL)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Token generation failed: {e}")
@app.post("/start-lesson", response_model=TokenResponse)
def start_lesson():
room_name = make_room_name()
identity = make_student_identity()
try:
grants = api.VideoGrants(
room_join=True,
room=room_name,
can_publish=True,
can_subscribe=True,
can_publish_data=True,
)
room_config = proto_livekit.RoomConfiguration(
agents=[
proto_livekit.RoomAgentDispatch(
agent_name="cloud-english-teacher",
agent_id="CA_e7hLTus66nKZ",
metadata='{"role":"tutor","persona":"english_teacher"}',
)
]
)
token = (
api.AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET)
.with_identity(identity)
.with_name("Student")
.with_grants(grants)
.with_room_config(room_config)
.to_jwt()
)
return TokenResponse(token=token, room_name=room_name, url=LIVEKIT_URL)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Token generation failed: {e}")
2) static/index.html
• Use the same minimal index.html you already have: ensure it is saved at static/index.html so FastAPI serves it at GET /
3) Dockerfile.api (no change needed if you used earlier Dockerfile; ensure it copies the static folder) Example Dockerfile.api:
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 requirements.txt /app/requirements.txt
RUN pip install --no-cache-dir -r /app/requirements.txt
COPY main.py /app/main.py
COPY static /app/static
ENV PYTHONUNBUFFERED=1
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
4) requirements.txt
fastapi
uvicorn[standard]
python-dotenv
livekit-api
5) .env (copy from .env.example and fill)
LIVEKIT_URL=wss://turbo-ms4yz8cm.livekit.cloud
LIVEKIT_API_KEY=your_livekit_api_key_here
LIVEKIT_API_SECRET=your_livekit_api_secret_here
Run locally with Docker Compose (from project root)
1. Ensure .env is set.
2. docker-compose up --build
3. Open http://localhost:8000/ — you should see index.html served by FastAPI.
4. Clicking "Start Lesson" in the page will POST to /start-lesson (same origin) and connect to LiveKit.
If you want, I can:
• Add CORS rules or change the frontend to fetch backend when hosted on a different origin.
• Add a small status endpoint in the agent container for transcripts/logs.
Which would you prefer next?modern-winter-66316
12/06/2025, 12:11 AMtall-airline-16756
12/06/2025, 12:12 AMimport os
import uuid
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from livekit import api
from livekit.protocol import livekit as proto_livekit
load_dotenv()
LIVEKIT_URL = os.getenv("LIVEKIT_URL", "wss://turbo-ms4yz8cm.livekit.cloud")
LIVEKIT_API_KEY = os.getenv("LIVEKIT_API_KEY")
LIVEKIT_API_SECRET = os.getenv("LIVEKIT_API_SECRET")
BACKEND_ORIGINS = os.getenv("BACKEND_ORIGINS", "*") # comma-separated or "*" for all
if not LIVEKIT_API_KEY or not LIVEKIT_API_SECRET:
raise RuntimeError("Please set LIVEKIT_API_KEY and LIVEKIT_API_SECRET in environment")
app = FastAPI()
# Configure CORS
if BACKEND_ORIGINS.strip() == "*" or BACKEND_ORIGINS.strip() == "":
allow_origins = ["*"]
else:
allow_origins = [o.strip() for o in BACKEND_ORIGINS.split(",") if o.strip()]
app.add_middleware(
CORSMiddleware,
allow_origins=allow_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Serve frontend static files when running same origin
app.mount("/", StaticFiles(directory="static", html=True), name="static")
class TokenResponse(BaseModel):
token: str
room_name: str
url: str
def make_student_identity():
return f"student-{uuid.uuid4().hex[:8]}"
def make_room_name():
return f"lesson-{uuid.uuid4().hex[:8]}"
@app.get("/health")
def health():
return {"status": "ok"}
@app.post("/create-room", response_model=TokenResponse)
def create_room():
room_name = make_room_name()
identity = make_student_identity()
try:
grants = api.VideoGrants(
room_join=True,
room=room_name,
can_publish=True,
can_subscribe=True,
can_publish_data=True,
)
token = (
api.AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET)
.with_identity(identity)
.with_name("Student")
.with_grants(grants)
.to_jwt()
)
return TokenResponse(token=token, room_name=room_name, url=LIVEKIT_URL)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Token generation failed: {e}")
@app.post("/start-lesson", response_model=TokenResponse)
def start_lesson():
room_name = make_room_name()
identity = make_student_identity()
try:
grants = api.VideoGrants(
room_join=True,
room=room_name,
can_publish=True,
can_subscribe=True,
can_publish_data=True,
)
room_config = proto_livekit.RoomConfiguration(
agents=[
proto_livekit.RoomAgentDispatch(
agent_name="cloud-english-teacher",
agent_id="CA_e7hLTus66nKZ",
metadata='{"role":"tutor","persona":"english_teacher"}',
)
]
)
token = (
api.AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET)
.with_identity(identity)
.with_name("Student")
.with_grants(grants)
.with_room_config(room_config)
.to_jwt()
)
return TokenResponse(token=token, room_name=room_name, url=LIVEKIT_URL)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Token generation failed: {e}")
2) .env.example — add BACKEND_ORIGINS
LIVEKIT_URL=wss://turbo-ms4yz8cm.livekit.cloud
LIVEKIT_API_KEY=your_livekit_api_key_here
LIVEKIT_API_SECRET=your_livekit_api_secret_here
# Comma-separated origins allowed to call backend, e.g. https://your-frontend.vercel.app,http://localhost:3000
BACKEND_ORIGINS=*
3) Updated frontend/index.html — configurable backend URL (uses BACKEND_URL var). Place index.html in static/ for same-origin or deploy it separately and set BACKEND_URL to your API endpoint.
<script>
// Configure backend base URL when serving the frontend from another host.
// If null/empty, uses same origin.
const BACKEND_URL = (window.__BACKEND_URL__) ? window.__BACKEND_URL__ : ""; // Replace via hosting platform or set below
// Example override for local dev:
// const BACKEND_URL = "http://localhost:8000";
async function getTokenAndJoin() {
startBtn.disabled = true;
const endpoint = (BACKEND_URL || "") + "/start-lesson";
const res = await fetch(endpoint, { method: 'POST' });
...
}
</script>
Usage notes
• For local dev where frontend and backend run on different ports:
◦ Set BACKEND_ORIGINS in backend .env to include your frontend origin (e.g., http://localhost:3000).
◦ In the frontend, set BACKEND_URL to your backend (e.g., http://localhost:8000).
• For production:
◦ Set BACKEND_ORIGINS to the exact frontend origin(s) for security (do not use "*").
◦ Configure your hosting platform to replace window.BACKEND_URL or edit the frontend to point to the production backend URL.
If you want, I can:
• Add an environment-injected backend URL placeholder replacement step (e.g., small script) for Vercel deployments.
• Provide an explicit example of hosting the frontend on Vercel and the backend on a container host with the correct CORS and BACKEND_URL settings.modern-winter-66316
12/06/2025, 12:14 AMtall-airline-16756
12/06/2025, 12:14 AM<!doctype html>
<html>
<head>...</head>
<body>
...
<script>
// The build injector will replace __BACKEND_URL__ with the actual backend URL.
const BACKEND_URL = "__BACKEND_URL__"; // if empty string, frontend uses same origin
async function getTokenAndJoin() {
const endpoint = (BACKEND_URL || "") + "/start-lesson";
const res = await fetch(endpoint, { method: 'POST' });
...
}
// rest of your frontend JS
</script>
</body>
</html>
2) frontend/scripts/inject-backend.js
• A small Node script to read index.html, replace the placeholder, and write the file into the build output.
// scripts/inject-backend.js
const fs = require('fs');
const path = require('path');
const OUT_DIR = process.env.OUT_DIR || 'public'; // Vercel will serve from 'public'
const SRC_FILE = path.join(__dirname, '..', 'static', 'index.html');
const OUT_FILE = path.join(OUT_DIR, 'index.html');
const backendUrl = process.env.BACKEND_URL || '';
if (!fs.existsSync(OUT_DIR)) fs.mkdirSync(OUT_DIR, { recursive: true });
let html = fs.readFileSync(SRC_FILE, 'utf8');
html = html.replace(/__BACKEND_URL__/g, backendUrl);
fs.writeFileSync(OUT_FILE, html, 'utf8');
console.log(`Injected BACKEND_URL='${backendUrl}' into ${OUT_FILE}`);
3) frontend/package.json
• Add build script that runs the injector. Vercel runs npm run build by default for Node projects.
{
"name": "livekit-frontend",
"version": "1.0.0",
"scripts": {
"build": "node scripts/inject-backend.js"
}
}
4) frontend/vercel.json
• Tells Vercel to run build and serve the public folder (where we write index.html).
{
"builds": [
{
"src": "package.json",
"use": "@vercel/static-build",
"config": {}
}
],
"routes": [
{
"src": "/(.*)",
"dest": "/index.html"
}
]
}
5) Vercel project env var
• In your Vercel project settings, set:
◦ BACKEND_URL = https://your-backend.example.com
(do not include trailing slash)
How it works
• At build time Vercel runs npm run build, which executes the injector script.
• The script replaces __BACKEND_URL__ in static/index.html with the value of the BACKEND_URL environment variable and writes the output to public/index.html.
• The deployed site serves the injected index.html; frontend will use that BACKEND_URL to call your FastAPI endpoints cross-origin.
Local testing
• Locally you can run:
◦ BACKEND_URL=http://localhost:8000 npm run build
◦ Then serve the public folder (e.g., npx http-server public) to test.
Notes & recommendations
• Use exact origin in BACKEND_URL and configure BACKEND_ORIGINS in your FastAPI .env to allow that origin.
• Keep the placeholder string unique (__BACKEND_URL__) to avoid accidental replacements.
• If you later host frontend and backend same-origin via FastAPI static serving, set BACKEND_URL to empty string in Vercel env to make frontend use same-origin paths.
• If you want, I can provide a small buildpack that also copies other static assets (CSS/JS) into public/ automatically.
Would you like me to produce the completed frontend folder (static + scripts + package.json + vercel.json) as a zip-ready listing?modern-winter-66316
12/06/2025, 12:19 AMpublic/ automatically.tall-airline-16756
12/06/2025, 12:19 AM// frontend/scripts/inject-and-copy.js
const fs = require('fs');
const path = require('path');
const SRC_DIR = path.join(__dirname, '..', 'static');
const OUT_DIR = path.join(__dirname, '..', 'public');
const BACKEND_URL = process.env.BACKEND_URL || '';
function ensureOutDir() {
if (!fs.existsSync(OUT_DIR)) fs.mkdirSync(OUT_DIR, { recursive: true });
}
function copyRecursive(src, dest) {
const stat = fs.statSync(src);
if (stat.isDirectory()) {
if (!fs.existsSync(dest)) fs.mkdirSync(dest, { recursive: true });
for (const entry of fs.readdirSync(src)) {
copyRecursive(path.join(src, entry), path.join(dest, entry));
}
} else {
fs.copyFileSync(src, dest);
}
}
function injectBackendUrl(content) {
return content.replace(/__BACKEND_URL__/g, BACKEND_URL);
}
function main() {
ensureOutDir();
// Copy all assets
copyRecursive(SRC_DIR, OUT_DIR);
// Replace placeholder in index.html (if exists)
const indexPath = path.join(OUT_DIR, 'index.html');
if (fs.existsSync(indexPath)) {
let html = fs.readFileSync(indexPath, 'utf8');
html = injectBackendUrl(html);
fs.writeFileSync(indexPath, html, 'utf8');
console.log(`Injected BACKEND_URL='${BACKEND_URL}' into ${indexPath}`);
} else {
console.warn('No index.html found in static/, skipping injection.');
}
}
main();
2) frontend/package.json
{
"name": "livekit-frontend-build",
"version": "1.0.0",
"scripts": {
"build": "node scripts/inject-and-copy.js"
},
"devDependencies": {}
}
3) frontend/vercel.json
{
"builds": [
{
"src": "package.json",
"use": "@vercel/static-build"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "/index.html"
}
]
}
4) frontend/static/
• Put your static assets here (index.html, styles.css, app.js, images, etc.).
• Ensure index.html contains the placeholder BACKEND_URL where needed, for example:
<script>
const BACKEND_URL = "__BACKEND_URL__"; // replaced at build time
const START_LESSON_ENDPOINT = (BACKEND_URL || "") + "/start-lesson";
// ...
</script>
How it works on Vercel
• Add BACKEND_URL environment variable in your Vercel Project Settings (e.g., https://api.example.com).
• Vercel runs npm run build (calls our script).
• Script copies frontend/static/* -> public/* and injects BACKEND_URL into public/index.html.
• Vercel serves the public folder; frontend will call the configured backend.
Local testing
• From frontend/ run:
◦ BACKEND_URL=http://localhost:8000 npm run build
◦ Serve the public folder: npx http-server public
• Confirm public/index.html contains the injected BACKEND_URL.
Security & notes
• Use exact origins for BACKEND_URL and set FastAPI BACKEND_ORIGINS to the frontend origin(s).
• Keep placeholder unique (BACKEND_URL) to avoid accidental replacement.
• If you prefer other build outputs, adjust OUT_DIR accordingly.
Would you like me to:
• Provide a zip-ready listing of the frontend folder, or
• Add an example CI workflow for Vercel or GitHub Actions that sets BACKEND_URL automatically?modern-winter-66316
12/06/2025, 12:20 AMtall-airline-16756
12/06/2025, 12:21 AMname: Build & Deploy Frontend to Vercel
on:
push:
branches:
- main
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout repo
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: 18
- name: Install deps (frontend)
working-directory: frontend
run: npm ci
- name: Build frontend (inject BACKEND_URL and copy assets)
working-directory: frontend
env:
BACKEND_URL: ${{ secrets.BACKEND_URL }}
run: npm run build
- name: Install Vercel CLI
run: npm install -g vercel@latest
- name: Authenticate Vercel CLI
env:
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
run: vercel logout || true && echo "$VERCEL_TOKEN" | vercel login --token
- name: Deploy to Vercel (public folder)
env:
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
run: |
# Deploy the public directory produced by build
vercel --prod --token $VERCEL_TOKEN --local-config ./frontend/vercel.json --confirm --cwd frontend public
Secrets to set in your GitHub repository (Settings → Secrets):
• BACKEND_URL — e.g. https://api.yourdomain.com
• VERCEL_TOKEN — personal token from Vercel (Project > Settings > Tokens)
• VERCEL_ORG_ID — your Vercel organization ID
• VERCEL_PROJECT_ID — your Vercel project ID
Notes
• The workflow runs on pushes to main. Adjust triggers as needed.
• The frontend build script (frontend/package.json "build") must produce frontend/public/ (the inject-and-copy script does this).
• Ensure frontend/vercel.json exists and is configured as previously provided.
• For preview deployments, remove --prod to let Vercel create preview deployments automatically.
• If you prefer using the official Vercel GitHub integration instead of the CLI deploy step, you can skip the deploy step and rely on Vercel to build on pushes (but you must ensure Vercel has the BACKEND_URL env var set in its Project Settings).
Would you like a variant that:
• deploys only when frontend files changed, or
• uses Vercel's GitHub integration (no CLI) with instructions to set BACKEND_URL in Vercel UI?modern-winter-66316
12/06/2025, 12:23 AMtall-airline-16756
12/06/2025, 12:23 AMmodern-winter-66316
12/06/2025, 12:24 AMtall-airline-16756
12/06/2025, 12:24 AMmodern-winter-66316
12/06/2025, 12:27 AMtall-airline-16756
12/06/2025, 12:28 AMpersona (one of your list). The token’s RoomAgentDispatch.metadata should include "persona":"Taxi Driver" etc. The agent worker will read this metadata to choose persona.
Example (snippet to build room_config inside /start-lesson):
# inside /start-lesson handler
persona = requested_persona # validate against allowed list
room_config = proto_livekit.RoomConfiguration(
agents=[
proto_livekit.RoomAgentDispatch(
agent_name="cloud-english-teacher",
agent_id="CA_e7hLTus66nKZ",
metadata=f'{{"persona":"{persona}"}}',
)
]
)
2) Agent worker: base teaching agent + persona classes
• Create a TeachingAgent base that sets the shared system prompt (friendly, stay in character, one tip, adjust difficulty, no lists).
• Each persona provides a short role_description and a starter prompt (greeting + context).
• Worker reads job.dispatch_metadata (or job.request.metadata) to get persona and instantiates the right class.
Concise agent patterns:
TeachingAgent base (core rules)
class TeachingAgent(Agent):
def __init__(self, persona_name: str, role_description: str, starter_instructions: str, tts_voice: str = None):
system_prompt = f"""
You are {persona_name}, {role_description}.
Teaching style rules (apply always):
- Be human and friendly; stay in character.
- Speak naturally in English, 1–2 short sentences per turn (no lists).
- Adjust vocabulary and grammar to the learner's level.
- After a short conversational exchange, give one short actionable tip as spoken feedback.
- Do not output bullet lists or long explanations.
"""
super().__init__(chat_ctx=ChatContext())
# put the system prompt into the agent's chat context
self.chat_ctx.append({"role":"system","content": system_prompt})
# persona-specific starter
self.starter_instructions = starter_instructions
self.persona_name = persona_name
self.tts_voice = tts_voice
Example persona classes (two shown; repeat pattern for all 11)
class EnglishTeacher(TeachingAgent):
def __init__(self):
super().__init__(
persona_name="Alex (English Teacher)",
role_description="a general English teacher who guides conversational practice and corrects gently",
starter_instructions="Greet the student warmly and ask how they'd like to practice today."
)
class TaxiDriver(TeachingAgent):
def __init__(self):
super().__init__(
persona_name="Sam (Taxi Driver)",
role_description="a chatty taxi driver who speaks naturally about routes, destinations, and short small talk",
starter_instructions="Greet the passenger and ask where they'd like to go."
)
Persona registry (map persona string to class)
PERSONA_MAP = {
"English Teacher": EnglishTeacher,
"Taxi Driver": TaxiDriver,
"Hotel Receptionist": HotelReceptionist,
"Waiter": Waiter,
"Check-in Agent": CheckInAgent,
"Border Officer": BorderOfficer,
"Nurse": Nurse,
"Ticket Clerk": TicketClerk,
"Information Agent": InformationAgent,
"Museum Front Desk": MuseumFrontDesk,
"Bartender": Bartender,
}
3) Worker entrypoint: choose persona from dispatch metadata
• When dispatched, LiveKit provides metadata. Use it to pick the persona class; default to "English Teacher".
Concise entrypoint flow:
async def entrypoint(job: JobContext):
# read persona from dispatch metadata
md = {}
try:
md = job.request.metadata or {}
except Exception:
pass
persona_key = md.get("persona") or "English Teacher"
PersonaCls = PERSONA_MAP.get(persona_key, EnglishTeacher)
agent_instance = PersonaCls()
# Create AgentSession wired to LiveKit Inference model strings
session = AgentSession(
ctx=job,
agent=agent_instance,
stt="deepgram/nova-3",
llm="openai/gpt-4.1-mini",
tts="cartesia/sonic-2",
enable_noise_cancellation=True,
)
await session.start(room=job.room)
# Have persona produce greeting
await session.generate_reply(instructions=agent_instance.starter_instructions)
await session.wait_closed()
Note: exact metadata access may be job.request.metadata or job.dispatch_metadata depending on SDK version — check job object for available fields; print job to confirm.
4) Persona specifics to include
• persona_name (display)
• role_description (how to role-play)
• starter_instructions (first prompt)
• optional tts_voice variant string (cartesia voice id) — pass to AgentSession TTS param or override session.say voice if supported.
5) Prompt engineering tips (short)
• Keep system prompt concise and authoritative about “stay in character” and “only one tip after short exchange”.
• Use few-shot examples if needed (1–2 pairs) to demonstrate the feedback format.
• Track learner level in session userdata and prepend a line like "Learner level: intermediate" into prompts to influence vocabulary.
6) Persisting and using learner level
• Use AgentSession userdata to store { level: "beginner"/"intermediate"/"advanced" } and update it from agent logic or frontend controls.
• Example when building session:
session = AgentSession(..., userdata={"level":"A2"})
• When generating replies, include the current level in instructions:
"User level: A2. Use simple vocabulary."
7) Voice variants
• Use cartesia voice variants per persona: e.g., pass tts="cartesia/sonic-2:voice-male-1" if supported.
• If your TTS param supports a voice ID, expose persona.tts_voice and use it when creating the AgentSession or when calling say/generate_reply.
8) Minimal list of persona starter prompts (you can use these verbatim)
• English Teacher (Alex): "Hello — I'm Alex, your English teacher. How would you like to practice today?"
• Taxi Driver: "Hi, where can I take you today?"
• Hotel Receptionist: "Welcome. Do you have a reservation?"
• Waiter: "Hi, I'll be taking your order — what would you like?"
• Check-in Agent: "Good morning. May I have your name and reservation details?"
• Border Officer: "Passport and purpose of visit, please."
• Nurse: "Hello. What brings you in today? Describe your symptoms briefly."
• Ticket Clerk: "Hi — where are you traveling and when?"
• Information Agent: "How can I help you find information today?"
• Museum Front Desk: "Welcome to the museum — would you like a map or a guided tour?"
• Bartender: "What can I get you? Any preferences?"
9) Testing & validation
• Add logging in the agent to print persona selection on startup.
• Test by calling /start-lesson with persona set and verify the agent greets in that role.
• For remote frontend builds (Vercel), ensure BACKEND_URL and CORS are set.
10) Expansion ideas
• Provide an endpoint /start-lesson?persona=Taxi%20Driver so frontend can let user pick persona.
• Add small persona selector UI and pass chosen persona to backend.
If you’d like, I can:
• Produce the full agent.py file with all 11 persona classes and starter prompts wired exactly into your existing worker code, or
• Update FastAPI /start-lesson to accept persona in the request body and validate it.
Which of those would you like me to produce next?
Sources: Agents and handoffs | LiveKit docs | Deepgram STT | LiveKit docs | OpenAI LLM models | LiveKit Docs | Build voice, video, and physical AI | LiveKit | Agents (Node.js) | livekit/livekit_composite | DeepWikimodern-winter-66316
12/06/2025, 12:29 AMtall-airline-16756
12/06/2025, 12:30 AM