modern-winter-66316
12/06/2025, 8:34 PMtall-airline-16756
12/06/2025, 8:34 PMtall-airline-16756
12/06/2025, 8:34 PMmodern-winter-66316
12/06/2025, 8:37 PMtall-airline-16756
12/06/2025, 8:38 PMmodern-winter-66316
12/06/2025, 8:39 PMtall-airline-16756
12/06/2025, 8:39 PMmodern-winter-66316
12/06/2025, 8:41 PMtall-airline-16756
12/06/2025, 8:41 PM{
"name": "livekit-vercel-token",
"version": "1.0.0",
"dependencies": {
"livekit-server-sdk": "^1.2.0"
}
}
3) Vercel serverless function: api/getToken.js
const { AccessToken, RoomServiceClient } = require('livekit-server-sdk');
module.exports = async (req, res) => {
try {
if (req.method !== 'POST') {
res.status(405).json({ error: 'Method not allowed' });
return;
}
const { identity, room } = req.body || {};
if (!identity || !room) {
res.status(400).json({ error: 'Missing identity or room' });
return;
}
const apiKey = process.env.LIVEKIT_API_KEY;
const apiSecret = process.env.LIVEKIT_API_SECRET;
const url = process.env.LIVEKIT_URL || 'https://your-project.livekit.cloud';
if (!apiKey || !apiSecret) {
res.status(500).json({ error: 'Server not configured' });
return;
}
// Create token valid for 1 hour
const at = new AccessToken(apiKey, apiSecret, { identity });
at.addGrant({
// Join room grant
roomJoin: true,
room: room
});
at.setExpiresAt(Math.floor(Date.now() / 1000) + 60 * 60);
const token = at.toJwt();
res.status(200).json({ token });
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Token generation failed' });
}
};
4) Vercel environment variables
• Set these in your Vercel project settings:
◦ LIVEKIT_API_KEY — your LiveKit API key
◦ LIVEKIT_API_SECRET — your LiveKit API secret
◦ LIVEKIT_URL — optional, your LiveKit Cloud URL (default used in code if omitted)
5) How the frontend calls it
• POST to: https://<your-vercel-deploy>/api/getToken
• Body (JSON): { "identity": "student1", "room": "english-lesson" }
• The function returns: { "token": "<JWT>" }
6) Notes and security
• Keep API key/secret only in Vercel env vars.
• Use short token expiry for production.
• Optionally verify authentication before issuing tokens (e.g., check a session cookie or JWT) so only authenticated users get tokens.
Would you like the complete agent + HTML frontend now (Python or Node agent)? I can produce the full code tailored to your preferred agent runtime.modern-winter-66316
12/06/2025, 8:41 PMtall-airline-16756
12/06/2025, 8:42 PMimport asyncio
from livekit import agents
from livekit.agents import JobContext, WorkerOptions, cli
from livekit.agents.llm import ChatContext
from livekit.plugins import openai, cartesia
async def entrypoint(ctx: JobContext):
# System prompt: English teacher persona
chat_context = ChatContext(
messages=[
{
"role": "system",
"content": (
"You are a friendly English teacher helping a student practice conversation. "
"Be supportive, correct grammar gently, ask open-ended questions, and keep responses concise."
),
}
]
)
# Create an AgentSession using LiveKit Inference stack (STT via OpenAI, LLM via OpenAI, TTS via Cartesia)
session = agents.voice.AgentSession(
ctx=ctx,
stt=openai.STT(language="en"),
llm=openai.LLM(model="gpt-4o-mini"), # adjust to available model
tts=cartesia.TTS(voice="sonic-3"),
)
await session.start(
agent="""
You are an English teacher. Help the user improve their speaking skills through conversation.
Be polite, ask open-ended questions, and correct small errors gently.
""",
chat_context=chat_context,
allow_interruptions=True,
)
# Initial greeting
await session.say("Hello! I'm your English teacher. Let's practice speaking together.")
# Keep the session open until job ends/terminated by LiveKit (the room/agent lifecycle controls stop)
await session.wait()
2) agent/requirements.txt
livekit-agents[openai,cartesia]==1.2.0
3) agent/Dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY agent.py .
ENV PYTHONUNBUFFERED=1
CMD ["python", "agent.py"]
4) agent/livekit.toml
# minimal livekit agent config for LK CLI
name = "english-teacher-agent"
region = "us-east-1"
[secrets]
# Provide on deploy (or via LK CLI) e.g. OPENAI_API_KEY, CARTESIA_KEY
# Example:
# OPENAI_API_KEY = "..."
# CARTESIA_API_KEY = "..."
[build]
dockerfile = "Dockerfile"
5) frontend/index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>English Teacher Lesson</title>
<script src="https://cdn.livekit.io/compat/2.16.0/livekit-client.min.js"></script>
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
#controls { margin-bottom: 12px; }
</style>
</head>
<body>
<h1>English Teacher Lesson</h1>
<div id="controls">
<input id="identity" placeholder="Your name" value="student1" />
<button id="startLesson">Start Lesson</button>
<button id="endLesson" disabled>End Lesson</button>
</div>
<div id="logs"></div>
<script>
const WS_URL = "wss://your-project.livekit.cloud"; // replace with your LiveKit URL
let room = null;
function log(msg) {
const d = document.getElementById('logs');
d.innerHTML += `<div>${msg}</div>`;
}
async function fetchToken(identity, roomName) {
const res = await fetch('/api/getToken', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ identity, room: roomName })
});
if (!res.ok) throw new Error('Token fetch failed');
const j = await res.json();
return j.token;
}
document.getElementById('startLesson').onclick = async () => {
const identity = document.getElementById('identity').value || 'student1';
const roomName = 'english-lesson';
try {
const token = await fetchToken(identity, roomName);
room = new LiveKit.Room();
await room.connect(WS_URL, token);
// publish microphone
const pc = await navigator.mediaDevices.getUserMedia({ audio: true });
await room.localParticipant.publishTrack(pc.getAudioTracks()[0]);
document.getElementById('startLesson').disabled = true;
document.getElementById('endLesson').disabled = false;
log('Connected. Talk to the English teacher.');
room.on('trackSubscribed', (track, publication, participant) => {
if (track.kind === 'audio') {
const audio = document.createElement('audio');
audio.autoplay = true;
audio.srcObject = new MediaStream([track.mediaStreamTrack]);
document.body.appendChild(audio);
log('Subscribed to audio track from ' + participant.identity);
}
});
} catch (e) {
console.error(e);
alert('Could not start lesson. See console.');
}
};
document.getElementById('endLesson').onclick = () => {
if (room) {
room.disconnect();
room = null;
document.getElementById('startLesson').disabled = false;
document.getElementById('endLesson').disabled = true;
log('Lesson ended.');
}
};
</script>
</body>
</html>
6) Quick deploy steps
• From your terminal, create the agent folder and files above.
• Set required secrets before deploying the agent:
◦ OPENAI_API_KEY (OpenAI for STT/LLM)
◦ CARTESIA_API_KEY (or other TTS key if needed)
◦ Any other keys used by plugins.
• Use LK CLI to create and deploy the agent:
1. Initialize agent (in agent/ directory)
lk agent create --region us-east
Replace region as needed. This creates the deployment config.
1. Deploy
lk agent deploy
• Frontend:
◦ Host index.html on any static host (Vercel, Netlify, local server).
◦ Ensure the frontend POSTs to your Vercel function at /api/getToken (for production supply full URL or proxy from same domain).
• Vercel:
◦ Deploy the api/getToken.js you already have.
◦ Configure env vars in Vercel: LIVEKIT_API_KEY, LIVEKIT_API_SECRET, LIVEKIT_URL (your LiveKit URL).
Notes and adjustments
• Model names (e.g., gpt-4o-mini) should match what your OpenAI/LiveKit environment supports—adjust if needed.
• The agent uses LiveKit Inference plugins openai and `cartesia`; ensure those plugins are enabled and keys are provided as secrets.
• The session ends when the room/agent lifecycle signals termination; the frontend disconnects when the user presses "End Lesson." That will end the user's session with the agent.
Would you like me to:
• provide a one-file zip-friendly layout for copying, or
• switch model names / plugin choices to match specific API keys you have?modern-winter-66316
12/06/2025, 10:01 PMtall-airline-16756
12/06/2025, 10:02 PMimport asyncio
from livekit import agents
from livekit.agents import JobContext, WorkerOptions, cli
from livekit.agents import voice as agent_voice
from livekit.agents.llm import ChatContext
async def entrypoint(ctx: JobContext):
# System prompt for English teacher
chat_context = ChatContext(
messages=[
{
"role": "system",
"content": (
"You are a friendly English teacher helping a student practice conversation. "
"Correct grammar gently, ask open questions, and keep replies concise."
),
}
]
)
# Use LiveKit Inference model identifiers for STT, LLM, TTS
session = agent_voice.AgentSession(
ctx=ctx,
stt="livekit/assemblyai/universal-streaming:en", # LiveKit Inference STT
llm="livekit/openai/gpt-4.1-mini", # LiveKit Inference LLM
tts="livekit/cartesia/sonic-3" # LiveKit Inference TTS
)
await session.start(
agent="""
You are an English teacher. Help the user practice English by having natural conversations.
Give gentle corrections for grammar and pronunciation, encourage further dialogue.
""",
chat_context=chat_context,
allow_interruptions=True,
)
await session.say("Hello! I'm your English teacher. When you're ready, start speaking and I'll respond.")
await session.wait()
2) agent/requirements.txt
livekit-agents==1.2.0
3) agent/Dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY agent.py .
ENV PYTHONUNBUFFERED=1
CMD ["python", "agent.py"]
4) agent/livekit.toml
name = "english-teacher-agent"
region = "us-east-1"
[build]
dockerfile = "Dockerfile"
[secrets]
# Provide these when deploying via LK CLI or in LiveKit Cloud:
# LIVEKIT_API_KEY, LIVEKIT_API_SECRET, LIVEKIT_URL
Notes about model strings
• The stt, llm, and tts values use LiveKit Inference model identifiers. If your LiveKit project uses slightly different strings for those inference models, replace them with the identifiers shown in your LiveKit console. The examples above reference LiveKit Inference STT/LLM/TTS models.
5) frontend/index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>English Teacher Lesson</title>
<script src="https://cdn.livekit.io/sdk-js/2.16.0/livekit-client.min.js"></script>
<style>body{font-family:Arial;padding:20px}</style>
</head>
<body>
<h1>English Teacher Lesson</h1>
<input id="identity" placeholder="Your name" value="student1" />
<button id="startLesson">Start Lesson</button>
<button id="endLesson" disabled>End Lesson</button>
<div id="logs"></div>
<script>
const LIVEKIT_WS = "wss://your-project.livekit.cloud"; // replace
let room = null;
function log(msg){ document.getElementById('logs').innerHTML += `<div>${msg}</div>`; }
async function fetchToken(identity, roomName){
const res = await fetch('/api/getToken', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ identity, room: roomName })
});
if(!res.ok) throw new Error('token fetch failed');
return (await res.json()).token;
}
document.getElementById('startLesson').onclick = async () => {
const identity = document.getElementById('identity').value || 'student1';
const roomName = 'english-lesson';
try {
const token = await fetchToken(identity, roomName);
room = new LiveKit.Room();
await room.connect(LIVEKIT_WS, token);
// Publish microphone
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
await room.localParticipant.publishTrack(stream.getAudioTracks()[0]);
document.getElementById('startLesson').disabled = true;
document.getElementById('endLesson').disabled = false;
log('Connected. Speak to the English teacher.');
room.on('trackSubscribed', (track, pub, participant) => {
if (track.kind === 'audio') {
const audio = document.createElement('audio');
audio.autoplay = true;
audio.srcObject = new MediaStream([track.mediaStreamTrack]);
document.body.appendChild(audio);
log('Subscribed to audio from ' + participant.identity);
}
});
} catch (e) {
console.error(e);
alert('Could not start lesson. Check console.');
}
};
document.getElementById('endLesson').onclick = () => {
if(room){ room.disconnect(); room = null; document.getElementById('startLesson').disabled=false; document.getElementById('endLesson').disabled=true; log('Lesson ended.'); }
};
</script>
</body>
</html>
6) Vercel token endpoint
• Use your existing api/getToken.js. Ensure it issues a short-lived LiveKit token and set Vercel env vars:
◦ LIVEKIT_API_KEY
◦ LIVEKIT_API_SECRET
◦ LIVEKIT_URL (optional)
Deployment steps (summary)
1. Put agent files in a folder and ensure livekit-agents==1.2.0 is in requirements.
2. From that folder run:
◦ lk agent create --region us-east-1 (or initialize per LK CLI)
◦ lk agent deploy (provide/live configure secrets LIVEKIT_API_KEY and LIVEKIT_API_SECRET)
1. Host frontend where it can call your Vercel function /api/getToken (same domain or CORS enabled).
2. Verify LiveKit Inference model identifiers in your LiveKit console and adjust the stt, llm, tts strings if needed.
If you want, I can:
• swap the exact model identifiers to those shown in your LiveKit project console; or
• provide a single zip/text blob containing all files for copy-paste.
Which would you prefer?
Sources: Voice AI quickstart | LiveKit docs | LiveKit turn detector plugin | LiveKit docs | Agent dispatch | LiveKit docs | Models | LiveKit Docs | Speech-to-text (STT) models | LiveKit Docsmodern-winter-66316
12/06/2025, 10:14 PMtall-airline-16756
12/06/2025, 10:15 PMmodern-winter-66316
12/06/2025, 10:16 PMtall-airline-16756
12/06/2025, 10:16 PMmodern-winter-66316
12/06/2025, 10:29 PMtall-airline-16756
12/06/2025, 10:29 PMlivekit.toml in your agent project root to create agent-02 in the turbo project:
# livekit.toml
[project]
subdomain = "turbo"
[agent]
id = "agent-02"
name = "agent-02"
region = "us-east-1"
[build]
dockerfile = "Dockerfile"
[secrets]
# Provide secrets at deploy time or via CLI / LiveKit Cloud:
# LIVEKIT_API_KEY = "..."
# LIVEKIT_API_SECRET = "..."
# Any plugin keys (if needed) can be listed here as well.
Next steps:
1. Place this file in the agent folder (with your Dockerfile and agent code).
2. Run lk agent create (or lk agent deploy) to register/deploy the agent to the turbo project. Sources: Deploying to production | LiveKit Docsmodern-winter-66316
12/06/2025, 10:34 PMtall-airline-16756
12/06/2025, 10:34 PMvercel dev) with body { "identity": "student1", "room": "english-lesson" } and observe logs.
d. Ensure package.json includes livekit-server-sdk and the deployment installed dependencies.
• Quick local curl example:
curl -v -X POST https://<your-vercel>/api/getToken -H "Content-Type: application/json" -d '{"identity":"test","room":"english-lesson"}'
• If log shows “Missing identity or room”, ensure your frontend sends JSON and includes headers: Content-Type: application/json.
4) Frontend: "Error fetching token: Token fetch failed"
• Cause: Your fetch saw a non-2xx response (the 500). Fix the /api/getToken 500 as above.
• Also confirm fetch URL:
◦ If frontend is hosted separately from Vercel function, call the full function URL (https://<your-vercel>.vercel.app/api/getToken).
◦ If using relative path /api/getToken, ensure the frontend and function are deployed on the same domain or proxy.
Suggested next quick actions (ordered)
1. Check Vercel function logs for /api/getToken to see the server-side error message.
2. Verify Vercel env vars: LIVEKIT_API_KEY and LIVEKIT_API_SECRET are present and correct.
3. From your dev machine run the curl test above; copy paste the full response or error here if it still fails.
4. Confirm frontend uses the correct token URL (absolute if cross-origin) and sets Content-Type header when POSTing JSON.
5. If DNS error persists, test the domain resolution with nslookup/dig and correct DNS records.
If you paste:
• the Vercel function log for the 500 error, and
• the exact fetch URL used by your frontend (the line where you call fetch('/api/getToken'...) or the configured LIVEKIT_WS),
I’ll pinpoint the failing line and give the exact code/config fix. Would you like me to show a hardened api/getToken.js that logs errors and returns clearer messages?modern-winter-66316
12/06/2025, 10:45 PMapi/getToken.js that logs errors and returns clearer messages?tall-airline-16756
12/06/2025, 10:45 PM// api/getToken.js
const { AccessToken, VideoGrant } = require('livekit-server-sdk');
/**
* Helper to send JSON responses with a consistent structure.
*/
function json(res, status, body) {
res.status(status).setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(body));
}
module.exports = async (req, res) => {
try {
// Only allow POST
if (req.method !== 'POST') {
json(res, 405, { error: 'Method not allowed. Use POST.' });
return;
}
// Ensure JSON body
if (!req.headers['content-type'] || !req.headers['content-type'].includes('application/json')) {
json(res, 400, { error: 'Content-Type must be application/json' });
return;
}
const { identity, room } = req.body || {};
if (!identity || typeof identity !== 'string' || identity.trim() === '') {
json(res, 400, { error: 'Missing or invalid "identity" field' });
return;
}
if (!room || typeof room !== 'string' || room.trim() === '') {
json(res, 400, { error: 'Missing or invalid "room" field' });
return;
}
// Read env vars
const apiKey = process.env.LIVEKIT_API_KEY;
const apiSecret = process.env.LIVEKIT_API_SECRET;
const livekitUrl = process.env.LIVEKIT_URL || process.env.NEXT_PUBLIC_LIVEKIT_URL || '';
if (!apiKey || !apiSecret) {
console.error('LIVEKIT_API_KEY or LIVEKIT_API_SECRET not set in environment');
json(res, 500, { error: 'Server not configured. Missing LIVEKIT_API_KEY or LIVEKIT_API_SECRET' });
return;
}
// Create AccessToken
try {
const at = new AccessToken(apiKey, apiSecret, { identity: identity.trim() });
const grant = new VideoGrant({
roomJoin: true,
room: room.trim(),
canPublish: true,
canSubscribe: true,
});
at.addGrant(grant);
// Set a short expiry (e.g., 1 hour)
const expirySeconds = 60 * 60;
at.setExpiresAt(Math.floor(Date.now() / 1000) + expirySeconds);
const token = at.toJwt();
// Helpful info for debugging in logs (do not log secrets!)
console.info(`Issued token for identity="${identity}" room="${room}" expires_in=${expirySeconds}s livekit_url="${livekitUrl || 'not-set'}"`);
json(res, 200, { token });
return;
} catch (tokenErr) {
console.error('Error creating LiveKit token:', tokenErr);
json(res, 500, { error: 'Failed to create token', details: tokenErr.message || String(tokenErr) });
return;
}
} catch (err) {
// Catch-all
console.error('Unexpected error in /api/getToken:', err);
json(res, 500, { error: 'Internal server error', details: err.message || String(err) });
}
};
Deployment & troubleshooting notes
• Environment variables: Set LIVEKIT_API_KEY and LIVEKIT_API_SECRET in your Vercel project settings. Optionally set LIVEKIT_URL for logging clarity.
• Test locally: Run vercel dev (or test with curl against deployed URL).
Example curl: curl -v -X POST "https://<your-vercel>.vercel.app/api/getToken" \ -H "Content-Type: application/json" \ -d '{"identity":"student1","room":"english-lesson"}'
• Check Vercel function logs if you still receive 500. Look for the console.error lines above.
• Common issues:
◦ Missing env vars → 500 with "Server not configured..."
◦ Bad request body / missing Content-Type → 400 with helpful message
◦ Dependency not installed → deployment logs will show install errors; ensure package.json includes "livekit-server-sdk".
• CORS: If your frontend is hosted on a different domain, enable CORS or call the full Vercel URL from the frontend. For quick debugging from local static file, fetch the full https://... URL.
Would you like me to:
• provide a version with explicit CORS headers, or
• show a minimal package.json that includes livekit-server-sdk for Vercel?modern-winter-66316
12/06/2025, 10:55 PMtall-airline-16756
12/06/2025, 10:56 PMmodern-winter-66316
12/06/2025, 10:57 PMtall-airline-16756
12/06/2025, 10:57 PMapi/getToken.js function. It includes the required dependency and a simple start script for local testing.
package.json
{
"name": "livekit-vercel-token",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "vercel dev"
},
"dependencies": {
"livekit-server-sdk": "^1.2.0"
}
}
Quick notes:
• Deploy this with your hardened api/getToken.js.
• Set Vercel env vars: LIVEKIT_API_KEY and LIVEKIT_API_SECRET (and optional LIVEKIT_URL).
• Run locally with vercel dev to test before deploying.
• If your frontend is on another domain, tell me and I’ll provide a CORS-enabled version of the function.modern-winter-66316
12/06/2025, 11:09 PMtall-airline-16756
12/06/2025, 11:09 PMexp claim was set to 3600 (an absolute Unix timestamp in 1970) instead of a future timestamp. Use a UNIX timestamp (seconds since epoch) for expiry.
Fix in your Vercel function: set expiry like this (seconds):
const expirySeconds = 60 * 60; // 1 hour at.setExpiresAt(Math.floor(Date.now() / 1000) + expirySeconds);
Or if using direct numeric exp claim, compute similarly: const exp = Math.floor(Date.now() / 1000) + 3600;
Replace the previous incorrect value (e.g., 3600) with the computed timestamp, redeploy, then re-test. If you still see expiry errors, check:
• Server clock is correct on Vercel (rare issue).
• Token returned by the function is the token the frontend actually uses (no cached/old token).
• Token TTL is short enough for your flow; regenerate before connect if needed.
If you’d like, I can update your hardened api/getToken.js to include this exact fix and return the expiry time in the response for debugging. Would you like that?modern-winter-66316
12/06/2025, 11:10 PMtall-airline-16756
12/06/2025, 11:10 PMapi/getToken.js that fixes the expiry bug and returns debugging info (expiry timestamp and TTL). It logs helpful messages and preserves previous validations.
// api/getToken.js
const { AccessToken, VideoGrant } = require('livekit-server-sdk');
function json(res, status, body) {
res.status(status).setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(body));
}
module.exports = async (req, res) => {
try {
if (req.method !== 'POST') {
json(res, 405, { error: 'Method not allowed. Use POST.' });
return;
}
if (!req.headers['content-type'] || !req.headers['content-type'].includes('application/json')) {
json(res, 400, { error: 'Content-Type must be application/json' });
return;
}
const { identity, room } = req.body || {};
if (!identity || typeof identity !== 'string' || identity.trim() === '') {
json(res, 400, { error: 'Missing or invalid "identity" field' });
return;
}
if (!room || typeof room !== 'string' || room.trim() === '') {
json(res, 400, { error: 'Missing or invalid "room" field' });
return;
}
const apiKey = process.env.LIVEKIT_API_KEY;
const apiSecret = process.env.LIVEKIT_API_SECRET;
const livekitUrl = process.env.LIVEKIT_URL || process.env.NEXT_PUBLIC_LIVEKIT_URL || '';
if (!apiKey || !apiSecret) {
console.error('LIVEKIT_API_KEY or LIVEKIT_API_SECRET not set in environment');
json(res, 500, { error: 'Server not configured. Missing LIVEKIT_API_KEY or LIVEKIT_API_SECRET' });
return;
}
try {
const at = new AccessToken(apiKey, apiSecret, { identity: identity.trim() });
const grant = new VideoGrant({
roomJoin: true,
room: room.trim(),
canPublish: true,
canSubscribe: true,
});
at.addGrant(grant);
// Correct expiry: compute absolute UNIX timestamp (seconds since epoch)
const ttlSeconds = 60 * 60; // 1 hour TTL — adjust as needed
const expiresAt = Math.floor(Date.now() / 1000) + ttlSeconds;
at.setExpiresAt(expiresAt);
const token = at.toJwt();
console.info(`Issued token for identity="${identity}" room="${room}" expires_at=${expiresAt} ttl_seconds=${ttlSeconds} livekit_url="${livekitUrl || 'not-set'}"`);
// Return token and debug info (do not return secrets)
json(res, 200, { token, expires_at: expiresAt, ttl_seconds: ttlSeconds });
return;
} catch (tokenErr) {
console.error('Error creating LiveKit token:', tokenErr);
json(res, 500, { error: 'Failed to create token', details: tokenErr.message || String(tokenErr) });
return;
}
} catch (err) {
console.error('Unexpected error in /api/getToken:', err);
json(res, 500, { error: 'Internal server error', details: err.message || String(err) });
}
};
Deploy this to Vercel, ensure LIVEKIT_API_KEY and LIVEKIT_API_SECRET are set, then test with:
curl -v -X POST "https://<your-vercel>.vercel.app/api/getToken" \ -H "Content-Type: application/json" \ -d '{"identity":"student1","room":"english-lesson"}'
The response will include expires_at (UNIX seconds) and ttl_seconds. If you still see expiry errors, paste the function logs here and I’ll pinpoint the issue.modern-winter-66316
12/06/2025, 11:13 PMtall-airline-16756
12/06/2025, 11:13 PMVideoGrant only controls join/publish/subscribe permissions; it does NOT automatically enable server-side recording. To enable recording you must explicitly grant recording rights and/or enable recording in your LiveKit project. Quick details and an updated token snippet follow.
What the existing VideoGrant does
• roomJoin: allows the identity to join the room
• canPublish / canSubscribe: allow publishing/subscribing tracks
• It does not enable room or participant recording by itself
How to enable recording
• LiveKit Cloud recording: enable recording for your project/room via the LiveKit Cloud settings or control it via the LiveKit Server API / recording agent. This is a project-side feature; toggling it enables the service to record sessions.
• Recording grant: to let a server or service create/manage recordings, issue a token with recording permissions (grant with roomRecord: true) for the identity/service that will perform recording.
• Recording agent: you can deploy a recording agent (or use LiveKit Cloud recording features) that joins with a token that has recording permission and then captures the room.
Hardened token: add recording grant (example)
• Below is a minimal change to your Vercel api/getToken.js to optionally include recording permissions when you request it. Only include roomRecord: true for trusted server identities — do NOT give recording permission to arbitrary clients.
Add a query field or JSON flag like { "identity":"recorder", "room":"english-lesson", "record": true } and the function will add recording rights when requested.
Snippet (conceptual):
// when building the grant
const grant = new VideoGrant({
roomJoin: true,
room: room.trim(),
canPublish: true,
canSubscribe: true,
// only set if explicitly requested
roomRecord: !!req.body.record
});
at.addGrant(grant);
Notes and recommendations
• Only grant roomRecord: true to trusted server/service identities (e.g., a recording agent), not regular student clients.
• If you want automatic recording for every lesson, enable project-level recording in LiveKit Cloud or have a recording agent join each lesson with a recorder identity that holds roomRecord: true.
• After enabling recording, confirm in LiveKit Cloud logs or the recording storage location that recordings are being created.
If you want, I can:
• provide the full api/getToken.js with an optional record flag included,
• show an example of a recorder identity token and how to deploy a recording agent, or
• show how to enable project/room recording in the LiveKit Cloud console (if you want step-by-step). Which would you like?modern-winter-66316
12/06/2025, 11:20 PMtall-airline-16756
12/06/2025, 11:21 PMlk logs agent-02 (or view LiveKit Cloud agent logs) and paste recent errors or any lines containing "session", "start", "say", or "error".
2) Token payload returned by /api/getToken
• Paste the JSON response your Vercel endpoint returns (you can omit the token string itself). I mainly need expires_at, ttl_seconds, and that the body returned 200.
3) Browser console after Start Lesson
• After clicking Start Lesson, copy the browser console messages (including any publish/subscribe errors, trackSubscribed logs, or "Connected" messages).
4) Confirm mic and subscription
• In the frontend, confirm you see a published local audio track (your code should log or you can check room.localParticipant.getTracks()).
• Confirm trackSubscribed fires for an audio track and that an <audio> element is appended (or say “no” if not).
Quick likely fixes to try now
• If logs show token expired: redeploy function with the fixed expiry (we already updated it), then request a fresh token.
• If Vercel shows token creation errors: ensure LIVEKIT_API_KEY and LIVEKIT_API_SECRET are set.
• If agent logs show model id errors: replace STT/LLM/TTS strings with the exact model IDs from your LiveKit Console.
• If frontend publishes mic but never subscribes: ensure both client and agent are in the same room name and the token grant includes canSubscribe:true.
• If trackSubscribed runs but no sound: make sure the created audio element is not muted and the element is attached before playback.
Send the four items above and I’ll give the exact change to make the agent speak.modern-winter-66316
12/06/2025, 11:38 PMtall-airline-16756
12/06/2025, 11:38 PMimport asyncio
import os
import logging
from livekit import agents
from livekit.agents import JobContext, WorkerOptions, cli
from livekit.agents import voice as agent_voice
from livekit.agents.llm import ChatContext
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("english-teacher-agent")
# System prompt
CHAT_SYSTEM = """You are a friendly English teacher helping a student practice conversation.
Correct grammar gently, ask open-ended questions, and keep replies concise."""
async def entrypoint(ctx: JobContext):
log.info("Agent entrypoint started; waiting for room/session info from LiveKit...")
# Wait until a participant joins the room before starting voice session
# Poll for participants in the JobContext room or use the provided event hooks
wait_seconds = 30
poll_interval = 1
elapsed = 0
while elapsed < wait_seconds:
participants = ctx.room.participants if hasattr(ctx, "room") else []
# ctx.room may be None depending on lifecycle; guard accordingly
if participants:
log.info(f"Detected participant(s): {[p.identity for p in participants]}")
break
await asyncio.sleep(poll_interval)
elapsed += poll_interval
if elapsed >= wait_seconds:
log.info("No participants joined within wait window; agent will continue to wait for connections via session lifecycle.")
else:
log.info("Participant found — starting AgentSession now.")
# Chat context / instructions
chat_context = ChatContext(
messages=[{"role": "system", "content": CHAT_SYSTEM}]
)
# Configure LiveKit Inference model identifiers (LiveKit Cloud inference)
stt_model = os.environ.get("INFERENCE_STT", "livekit/assemblyai/universal-streaming:en")
llm_model = os.environ.get("INFERENCE_LLM", "livekit/openai/gpt-4.1-mini")
tts_model = os.environ.get("INFERENCE_TTS", "livekit/cartesia/sonic-3")
log.info(f"Using models stt={stt_model} llm={llm_model} tts={tts_model}")
session = agent_voice.AgentSession(
ctx=ctx,
stt=stt_model,
llm=llm_model,
tts=tts_model,
)
# Start session with instructions
await session.start(
agent=CHAT_SYSTEM,
chat_context=chat_context,
allow_interruptions=True,
)
log.info("AgentSession started; sending initial greeting.")
await session.say("Hello! I'm your English teacher. Speak when you're ready and I'll respond.")
# Keep the session alive while participants remain
try:
await session.wait()
except Exception as e:
log.exception("Error while session running: %s", e)
finally:
log.info("Agent session ended or was terminated.")
What this change does
• Waits up to 30 seconds for a participant to appear before explicitly starting the session flow. If no participant appears, the agent still starts normally when LiveKit routes a session event — this polling reduces race conditions where the agent starts before the user arrives.
• Adds clear logging for lifecycle events (start, detected participants, model selection, greeting, session end).
• Model identifiers are read from env vars INFERENCE_STT, INFERENCE_LLM, INFERENCE_TTS so you can override without changing code.
Critical: LiveKit Cloud inference keys and project config
• The agent must have access to your LiveKit Cloud project API key/secret (LIVEKIT_API_KEY, LIVEKIT_API_SECRET) so it can authenticate and use Inference.
• In LiveKit Cloud, configure the Inference keys/plugins for STT/LLM/TTS or ensure your project is allowed to use the referenced inference models. If your LiveKit console shows different model identifiers, set those in Vercel/agent secrets.
• Set the following secrets when deploying the agent via LK CLI or LiveKit Cloud:
◦ LIVEKIT_API_KEY
◦ LIVEKIT_API_SECRET
◦ (Optional) LIVEKIT_URL
◦ INFERENCE_STT (optional override)
◦ INFERENCE_LLM (optional override)
◦ INFERENCE_TTS (optional override)
Recommended quick checks if agent still silent
1. Agent logs: check lk logs agent-02 for these log lines:
◦ "Detected participant(s): ..."
◦ "AgentSession started; sending initial greeting."
◦ Any errors mentioning model id or inference permission.
1. Ensure the frontend publishes audio and both client & agent share the exact same room name.
2. Confirm LiveKit Cloud shows the agent is running and has inference configured (and not missing plugin keys).
3. If logs show model identifier errors, set correct identifiers via the env var overrides above and redeploy.
4. Add debug logging to session events if you want more detail (I can provide snippets).
If you want, I can:
• provide an alternate version that uses LiveKit event hooks (on_participant_join) instead of polling; or
• add a short snippet to the Vercel token response to return the token expiry and room name for quick verification.
Which do you prefer?modern-winter-66316
12/06/2025, 11:39 PMtall-airline-16756
12/06/2025, 11:40 PMimport os, asyncio, logging
from livekit import agents
from livekit.agents import JobContext, cli
from livekit.agents import voice as agent_voice
from livekit.agents.llm import ChatContext
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("english-teacher-agent")
CHAT_SYSTEM = (
"You are a friendly English teacher. Correct grammar gently, ask open-ended questions, "
"and keep responses short and encouraging."
)
async def entrypoint(ctx: JobContext):
log.info("Agent entrypoint: waiting for participant join events...")
# Model identifiers (override with env vars if needed)
stt_model = os.getenv("INFERENCE_STT", "livekit/assemblyai/universal-streaming:en")
llm_model = os.getenv("INFERENCE_LLM", "livekit/openai/gpt-4.1-mini")
tts_model = os.getenv("INFERENCE_TTS", "livekit/cartesia/sonic-3")
log.info(f"Models: stt={stt_model} llm={llm_model} tts={tts_model}")
# Subscribe to participant join events provided by JobContext
async def on_participant_join(participant):
try:
log.info(f"Participant joined: {participant.identity}")
# Create session per participant and start immediately
session = agent_voice.AgentSession(
ctx=ctx,
stt=stt_model,
llm=llm_model,
tts=tts_model,
)
await session.start(
agent=CHAT_SYSTEM,
chat_context=ChatContext(messages=[{"role":"system","content":CHAT_SYSTEM}]),
allow_interruptions=True,
)
log.info("AgentSession started — sending greeting.")
await session.say("Hello! I'm your English teacher. Please speak when ready and I'll respond.")
# Keep this session alive until the participant leaves or session ends.
await session.wait()
log.info("Session ended for participant: %s", participant.identity)
except Exception as e:
log.exception("Error handling participant join: %s", e)
# Attach event handler exposed by JobContext (name may vary by SDK version)
try:
ctx.on_participant_join(on_participant_join)
log.info("Registered on_participant_join handler; agent ready.")
except Exception:
# Fallback: some SDK versions expose events differently; poll as last resort
log.warning("Event hook unavailable; falling back to polling for participants.")
while True:
participants = getattr(ctx, "room", None) and getattr(ctx.room, "participants", [])
if participants:
for p in participants:
await on_participant_join(p)
await asyncio.sleep(1)
if __name__ == "__main__":
cli.run_app(agents.WorkerOptions(entrypoint_fnc=entrypoint))
2) agent/livekit.toml
[project]
subdomain = "turbo"
[agent]
id = "agent-02"
name = "agent-02"
region = "us-east-1"
[build]
dockerfile = "Dockerfile"
3) frontend/index.html (key points: obtain mic, then fetch token, then connect; ensure full Vercel URL if cross-domain)
<!doctype html><html><head><meta charset="utf-8"/><title>English Lesson</title>
<script src="https://cdn.livekit.io/sdk-js/2.16.0/livekit-client.min.js"></script></head><body>
<input id="identity" placeholder="Name" value="student1"/><button id="start">Start Lesson</button><button id="end" disabled>End Lesson</button>
<div id="log"></div>
<script>
const VERCEL_TOKEN_URL = 'https://<your-vercel>.vercel.app/api/getToken'; // full URL
const LIVEKIT_WS = 'wss://your-project.livekit.cloud'; // replace
let room=null, localStream=null;
function log(msg){ document.getElementById('log').innerHTML += '<div>'+msg+'</div>'; }
document.getElementById('start').onclick = async () => {
try {
// 1) get mic permission and prepare local audio (do this before requesting token to avoid race)
localStream = await navigator.mediaDevices.getUserMedia({ audio: true });
log('Microphone acquired.');
// 2) request fresh token (ensure backend returns token for same room)
const identity = document.getElementById('identity').value || 'student1';
const roomName = 'english-lesson-' + Math.floor(Math.random()*100000); // unique per student for 1:1
const res = await fetch(VERCEL_TOKEN_URL, {
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({ identity, room: roomName })
});
if(!res.ok) throw new Error('Token fetch failed: ' + res.status);
const body = await res.json();
log('Token received; expires_at: ' + body.expires_at);
// 3) connect to LiveKit and publish mic
room = new LiveKit.Room();
await room.connect(LIVEKIT_WS, body.token);
await room.localParticipant.publishTrack(localStream.getAudioTracks()[0]);
log('Connected and published mic. Waiting for agent audio...');
document.getElementById('start').disabled=true;
document.getElementById('end').disabled=false;
room.on('trackSubscribed', (track, pub, participant) => {
if(track.kind==='audio'){
const audio = document.createElement('audio');
audio.autoplay = true;
audio.srcObject = new MediaStream([track.mediaStreamTrack]);
document.body.appendChild(audio);
log('Subscribed to audio from ' + participant.identity);
}
});
} catch (e) { console.error(e); alert(e.message); log('Start error: '+e.message); }
};
document.getElementById('end').onclick = () => {
if(room){ room.disconnect(); room=null; if(localStream){ localStream.getTracks().forEach(t=>t.stop()); localStream=null; } document.getElementById('start').disabled=false; document.getElementById('end').disabled=true; log('Lesson ended.'); }
};
</script></body></html>
Why this is foolproof
• The frontend obtains microphone permission before requesting a token and connecting — avoids browser autoplay/permission race conditions.
• The frontend requests a fresh token immediately before connect (no cached/expired token).
• The agent uses a participant-joined event handler to create a session and immediately say a greeting on participant connect.
• Use unique room names per student for 1:1 sessions to avoid routing ambiguity.
• Agent logs each step so you can see join/start/greeting in LiveKit logs.
Final checklist to ensure success
• Deploy agent with LIVEKIT_API_KEY and LIVEKIT_API_SECRET set and INFERENCE_* vars if needed.
• Deploy hardened /api/getToken.js to Vercel and set LIVEKIT_* env vars there.
• Replace placeholders: VERCEL_TOKEN_URL, LIVEKIT_WS, and your Vercel domain in frontend.
• Test a single student flow. Check agent logs for "Participant joined" and "AgentSession started — sending greeting."
• If no audio from agent: confirm LiveKit Cloud inference is enabled for your project and model IDs are correct; check agent logs for inference errors.
If you want, I will:
• produce a single zip of all files ready to deploy, or
• switch the agent to use an explicit recorder/bridge identity so the agent always joins first and then accepts students.
Which would you like me to prepare next?modern-winter-66316
12/06/2025, 11:45 PMtall-airline-16756
12/06/2025, 11:45 PMmodern-winter-66316
12/06/2025, 11:46 PMtall-airline-16756
12/06/2025, 11:47 PMlk logs agent-02) showing inference/model errors. Once I have that, I’ll tell you exactly whether Inference must be enabled for your account, where those settings appear, or what to request from your LiveKit admin and provide the exact text to send.modern-winter-66316
12/06/2025, 11:54 PMtall-airline-16756
12/06/2025, 11:54 PMimport os
from livekit.agents import voice as agent_voice
from livekit.agents.llm import ChatContext
stt_model = os.getenv("INFERENCE_STT")
llm_model = os.getenv("INFERENCE_LLM")
tts_model = os.getenv("INFERENCE_TTS")
session = agent_voice.AgentSession(
ctx=ctx,
stt=stt_model,
llm=llm_model,
tts=tts_model,
)
4) Deploy the agent with those env vars and the LiveKit credentials
• Ensure livekit.toml lists the secrets or provide them to lk agent deploy.
• After deploy, confirm logs show the models being used (look for a log line like: "Using models stt=..., llm=..., tts=...").
5) Verify end-to-end
• Start the frontend (fresh token), publish mic, join same room.
• Check agent logs: participant join → session start → session.say (greeting) → any inference errors.
• If agent logs show "model not found" or "permission denied", replace model strings with the ones shown in your project console or ensure your project has quota/permission for those models.
If you want, I can:
• produce the exact livekit.toml entry and CLI deploy command with those secrets filled in, or
• replace the model strings with the exact identifiers from your LiveKit Console if you paste them here.
Which would you like me to do next?modern-winter-66316
12/07/2025, 12:42 AMtall-airline-16756
12/07/2025, 12:42 AMmodern-winter-66316
12/07/2025, 12:45 AMtall-airline-16756
12/07/2025, 12:46 AMmodern-winter-66316
12/07/2025, 12:48 AMtall-airline-16756
12/07/2025, 12:49 AMmodern-winter-66316
12/07/2025, 12:52 AMtall-airline-16756
12/07/2025, 12:53 AM