broad-librarian-92914
12/12/2025, 5:44 AMtall-airline-16756
12/12/2025, 5:44 AMtall-airline-16756
12/12/2025, 5:44 AMbroad-librarian-92914
12/12/2025, 5:46 AMtall-airline-16756
12/12/2025, 5:47 AMbroad-librarian-92914
12/12/2025, 5:48 AMtall-airline-16756
12/12/2025, 5:49 AMbroad-librarian-92914
12/12/2025, 5:51 AMtall-airline-16756
12/12/2025, 5:51 AMbroad-librarian-92914
12/12/2025, 5:52 AMtall-airline-16756
12/12/2025, 5:53 AM.env.local and set:
• LIVEKIT_API_KEY=your_api_key
• LIVEKIT_API_SECRET=your_api_secret
• NEXT_PUBLIC_LIVEKIT_URL=wss://<your-project>.livekit.cloud
• SANDBOX_ID=<sandbox-id> (if starter expects it)
4.2. Restart dev server.
5) Use the built-in token source / sandbox token 5.1. The starter supports TokenSource fetching from the sandbox. Confirm code uses something like:
• TokenSource.sandboxTokenServer('<sandbox-id>') or TokenSource.fetch('/api/token?name=Visitor')
5.2. If the starter uses a local token API, ensure the API route uses your LIVEKIT_API_KEY / SECRET to generate AccessToken (server-side).
6) Provision/Connect an Agent backend (via LiveKit Cloud sandbox) 6.1. In the LiveKit Cloud UI, create a sandbox deployment (Agent Builder) using the starter templates or upload your agent code. 6.2. If you want to use LiveKit’s hosted sandbox quickly, choose the sandbox instance for your project and note its ID and configuration.
Part B — Integrate Gemini Live into the agent backend (Python example)
1) Prepare environment & plugin 1.1. Install agent dependencies and Google plugin:
• pip install livekit-agents
• pip install 'livekit-agents[google]' (or use uv add "livekit-agents[google]~=1.2" if using the agent CLI)
1.2. Set environment variables in the agent runtime:
• GOOGLE_API_KEY=your_gemini_api_key
• LIVEKIT_API_KEY and LIVEKIT_API_SECRET (if agent needs to generate tokens or call LiveKit admin APIs)
2) Minimal Python agent using Gemini Live 2.1. Example entrypoint (replace model/voice per your key’s availability):
from livekit import agents
from livekit.plugins import google
async def entrypoint(ctx: agents.JobContext):
await ctx.connect(auto_subscribe=agents.AutoSubscribe.AUDIO_ONLY)
session = agents.AgentSession(
llm=google.realtime.RealtimeModel(
model="gemini-2.5-flash-native-audio-preview-09-2025",
voice="Puck",
instructions="You are a friendly assistant.",
temperature=0.8,
)
)
await session.start(ctx.room)
session.say("Hello! How can I help you today?")
2.2. Package and deploy this agent to your sandbox via the Agent Builder or your own host.
3) Confirm audio flow
• User on Next.js frontend connects via LiveKit client to the room.
• Agent sandbox auto-joins the same room, subscribes to user audio, forwards audio to Gemini Live model via the plugin, and plays TTS back into the room.
Part C — Verify end-to-end locally 1) Start Next.js frontend. 2) Ensure sandbox agent is running (LiveKit Cloud UI shows active session) or run locally if developing. 3) Connect from the browser, enable microphone, speak — agent should respond via audio.
Part D — Production considerations & token server 1) For production avoid embedding API secret in frontend. Use a server-side token endpoint to mint AccessTokens with livekit-server-sdk. 2) Next.js API example (server-side):
import { NextApiRequest, NextApiResponse } from 'next';
import { AccessToken } from 'livekit-server-sdk';
export default function handler(req: NextApiRequest, res: NextApiResponse) {
const at = new AccessToken(process.env.LIVEKIT_API_KEY!, process.env.LIVEKIT_API_SECRET!, { identity: 'user' });
at.addGrant({ room: 'my-room', roomJoin: true, canPublish: true, canSubscribe: true });
res.json({ token: at.toJwt() });
}
Cost-control tips (stay within free minutes, limit sessions, monitor) 1) Use the free Build plan
• You get 1,000 free agent session minutes per month. Keep development/testing to this quota.
2) Limit concurrent sessions & session duration
• Implement server-side rate limits: restrict how many agent sessions a single user or API key can create.
• Enforce maximum session length: close sessions automatically after N minutes of inactivity.
3) Use sandboxes for prototyping only
• Sandboxes are inexpensive for dev; for predictable production costs, schedule jobs or use on-demand start/stop.
4) Monitor usage in LiveKit Cloud
• Use the LiveKit Cloud dashboard to track agent session minutes and inference credits.
• Set up alerts (if available in UI) when you approach quota.
5) Reduce inference cost
• Prefer lower-cost models or disable unnecessary modalities (e.g., use TEXT-only if audio not required).
• Reuse sessions for short back-and-forth conversations rather than creating new agent sessions each turn.
6) Local testing & batching
• Test locally with fewer minutes; batch test cases rather than long-running manual tests.
• Use short audio snippets and reduce polling frequency for logging/observability.
7) Cleanup idle resources
• Ensure your agent code disconnects from rooms on inactivity and frees resources.
If you want, I can:
• Provide a filled-in .env.local template and show exactly where to drop sandbox IDs in the starter project.
• Give the exact commands to deploy the Python agent to LiveKit Cloud sandbox.
Which would you like next?broad-librarian-92914
12/12/2025, 5:55 AMtall-airline-16756
12/12/2025, 5:56 AMbroad-librarian-92914
12/12/2025, 5:56 AMtall-airline-16756
12/12/2025, 5:57 AMpnpm init -y
pnpm add @livekit/agents @livekit/agents-plugin-google livekit-server-sdk dotenv
pnpm add -D typescript ts-node @types/node
2) tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "CommonJS",
"outDir": "dist",
"rootDir": "src",
"esModuleInterop": true,
"strict": true,
"skipLibCheck": true
}
}
3) .env
LIVEKIT_API_KEY=your_livekit_api_key
LIVEKIT_API_SECRET=your_livekit_api_secret
LIVEKIT_URL=wss://your-project.livekit.cloud
GOOGLE_API_KEY=your_gemini_api_key
PORT=3000
4) src/agent.ts (TypeScript agent using Gemini Live)
import dotenv from 'dotenv';
dotenv.config();
import * as livekit from '@livekit/agents';
import * as google from '@livekit/agents-plugin-google';
const {
LIVEKIT_API_KEY,
LIVEKIT_API_SECRET,
LIVEKIT_URL,
GOOGLE_API_KEY,
} = process.env;
if (!LIVEKIT_API_KEY || !LIVEKIT_API_SECRET || !LIVEKIT_URL || !GOOGLE_API_KEY) {
throw new Error('Missing required env vars');
}
const worker: livekit.WorkerOptions = {
apiKey: LIVEKIT_API_KEY,
apiSecret: LIVEKIT_API_SECRET,
callbackUrl: LIVEKIT_URL,
participantLimit: 0,
async workerInit() {
console.log('Worker initialized for Gemini Live agent');
},
async jobRequest(ctx: livekit.JobContext) {
console.log('Job requested — connecting to room', ctx.room.name);
await ctx.connect({ autoSubscribe: livekit.AutoSubscribe.AUDIO_ONLY });
const llm = new google.realtime.RealtimeModel({
apiKey: GOOGLE_API_KEY,
model: 'gemini-2.0-flash-exp', // pick available realtime model
voice: 'Puck',
temperature: 0.7,
instructions: 'You are a helpful assistant that speaks clearly.',
// optional: modalities: ['AUDIO'] (default)
});
const session = new livekit.AgentSession({
room: ctx.room,
llm,
// optional plugins or VAD can be added here
});
await session.start();
console.log('Agent session started in room', ctx.room.name);
// Optional: send initial greeting
try {
await session.say('Hello — I am your voice assistant. How can I help you today?');
} catch (err) {
console.error('Error sending greeting:', err);
}
// Keep job alive until room ends; cleanup handled by AgentSession on disconnect
},
};
// Run worker
livekit.runWorker(worker).catch((err) => {
console.error('Worker failed:', err);
process.exit(1);
});
5) Build & run
• Add scripts to package.json:
"scripts": {
"build": "tsc",
"start": "node dist/agent.js",
"dev": "ts-node src/agent.ts"
}
• Dev:
pnpm dev
• Production:
pnpm build
pnpm start
6) Dockerfile (optional)
FROM node:18-alpine
WORKDIR /app
COPY package.json pnpm-lock.yaml ./
RUN npm install -g pnpm
RUN pnpm install --frozen-lockfile --prod
COPY . .
RUN pnpm build
EXPOSE 3000
CMD ["node","dist/agent.js"]
7) Frontend (Next.js Voice Agent starter) — connection notes
• Ensure your .env.local in the Next.js app has:
NEXT_PUBLIC_LIVEKIT_URL=wss://your-project.livekit.cloud
LIVEKIT_API_KEY=your_livekit_api_key
LIVEKIT_API_SECRET=your_livekit_api_secret # only used for server token routes
SANDBOX_ID=<if using sandbox token source>
• When fetching tokens for a user, include the agent name if required by the starter:
// example token fetch
const token = await fetch(`/api/token?name=Visitor&agentName=gemini-live-agent`).then(r=>r.json());
• Starter will connect the user to a room; once connected the deployed agent will join and handle audio with Gemini Live.
8) Deploy to LiveKit Cloud agent sandbox
• Use LiveKit CLI or Cloud UI to deploy your built agent. If using the CLI:
◦ Build and bundle your agent (ensure dist/ exists)
◦ Run: lk agent deploy ./dist --name gemini-live-agent
• Confirm the agent appears active in LiveKit Cloud and test by joining a room from the frontend.
9) Cost-control tips (concise)
• Free tier: 1,000 free agent session minutes/month.
• Agent session price: $0.01 per active minute beyond free tier.
• Reduce cost:
◦ Enforce max session length and idle timeout: call session.end() after N seconds of silence.
◦ Limit concurrent sessions with participantLimit or worker-side checks.
◦ Reuse sessions for short back-and-forth instead of creating new sessions each turn.
◦ Prefer text-only mode or lower-tier models when voice quality can be relaxed.
◦ Monitor usage in LiveKit Cloud dashboard and set alerts.
◦ Run heavy testing locally to avoid cloud minutes.
If you want, I can:
• Provide a production-ready token server Next.js API route (TypeScript).
• Add VAD/silence detection snippet to auto-end sessions.
Which would you like next?broad-librarian-92914
12/12/2025, 6:02 AMtall-airline-16756
12/12/2025, 6:02 AMbroad-librarian-92914
12/12/2025, 6:08 AMtall-airline-16756
12/12/2025, 6:09 AMLIVEKIT_API_KEY=your_livekit_api_key
LIVEKIT_API_SECRET=your_livekit_api_secret
NEXT_PUBLIC_LIVEKIT_URL=wss://your-project.livekit.cloud
.env (agent process)
LIVEKIT_API_KEY=your_livekit_api_key
LIVEKIT_API_SECRET=your_livekit_api_secret
LIVEKIT_URL=wss://your-project.livekit.cloud
GOOGLE_API_KEY=your_gemini_api_key
2) Next.js: Token API (server-side) — pages/api/token.ts or app/api/token/route.ts
// pages/api/token.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { AccessToken, RoomGrant } from 'livekit-server-sdk';
export default function handler(req: NextApiRequest, res: NextApiResponse) {
const name = Array.isArray(req.query.name) ? req.query.name[0] : (req.query.name as string) || 'visitor';
const room = Array.isArray(req.query.room) ? req.query.room[0] : (req.query.room as string) || 'interview-room';
const at = new AccessToken(process.env.LIVEKIT_API_KEY!, process.env.LIVEKIT_API_SECRET!, { identity: name });
const grant = new RoomGrant({ room });
at.addGrant(grant);
res.status(200).json({ token: at.toJwt(), url: process.env.NEXT_PUBLIC_LIVEKIT_URL });
}
3) Next.js: simple client page using TokenSource + LiveKit React components Install: pnpm add livekit-client @livekit/components-react @livekit/components-styles
Client (pages/index.tsx or app/page.tsx — use client component)
'use client';
import React, { useRef, useEffect } from 'react';
import { TokenSource } from 'livekit-client';
import { SessionProvider, useSession, RoomAudioRenderer, ControlBar } from '@livekit/components-react';
function AppInner() {
const tokenSource = useRef(TokenSource.fetch(`/api/token?name=Candidate&room=interview-room`)).current;
const session = useSession(tokenSource);
useEffect(() => {
session.start();
return () => session.end();
}, [session]);
return (
<SessionProvider session={session}>
<div data-lk-theme="default" style={{ padding: 20 }}>
<h2>Voice AI Interview — Candidate</h2>
<ControlBar controls={{ microphone: true, camera: false, screenshare: false }} />
<RoomAudioRenderer />
</div>
</SessionProvider>
);
}
export default function Page() {
return <AppInner />;
}
4) In-memory transcript store (simple) — used by agent to persist turns src/transcriptStore.ts
type Turn = { speaker: 'candidate' | 'agent', text: string, ts: string };
const store: Record<string, Turn[]> = {};
export function appendTurn(sessionId: string, turn: Turn) {
if (!store[sessionId]) store[sessionId] = [];
store[sessionId].push(turn);
}
export function getRecentContext(sessionId: string, maxTurns = 10) {
const arr = store[sessionId] || [];
return arr.slice(-maxTurns).map(t => `${t.speaker}: ${t.text}`).join('\n');
}
5) TypeScript Node agent integrating Gemini Live via LiveKit plugin Install: pnpm add @livekit/agents @livekit/agents-plugin-google dotenv pnpm add -D typescript ts-node @types/node
src/agent.ts
import dotenv from 'dotenv';
dotenv.config();
import * as livekit from '@livekit/agents';
import * as google from '@livekit/agents-plugin-google';
import { appendTurn, getRecentContext } from './transcriptStore';
const { LIVEKIT_API_KEY, LIVEKIT_API_SECRET, LIVEKIT_URL, GOOGLE_API_KEY } = process.env;
if (!LIVEKIT_API_KEY || !LIVEKIT_API_SECRET || !GOOGLE_API_KEY || !LIVEKIT_URL) {
throw new Error('Missing env vars');
}
const worker: livekit.WorkerOptions = {
apiKey: LIVEKIT_API_KEY,
apiSecret: LIVEKIT_API_SECRET,
callbackUrl: LIVEKIT_URL,
participantLimit: 0,
async workerInit() {
console.log('Agent worker initialized');
},
async jobRequest(ctx: livekit.JobContext) {
console.log('Job request for room:', ctx.room.name);
// Connect and subscribe to audio only
await ctx.connect({ autoSubscribe: livekit.AutoSubscribe.AUDIO_ONLY });
// Create Gemini realtime model
const llm = new google.realtime.RealtimeModel({
apiKey: GOOGLE_API_KEY,
model: 'gemini-2.0-flash-exp', // pick available realtime model
voice: 'Puck',
temperature: 0.7,
instructions: 'You are an interviewer. Ask clarifying and structured questions; keep prompts concise.',
});
// Create session tying LLM to the room
const session = new livekit.AgentSession({ room: ctx.room, llm });
// Hook: when model emits transcript / partial text, store it
session.on('transcript', (evt: any) => {
// evt: { text, speaker: 'participant'|'agent', final }
const sessionId = ctx.room.name;
const speaker = evt.speaker === 'participant' ? 'candidate' : 'agent';
if (evt.final) {
appendTurn(sessionId, { speaker, text: evt.text, ts: new Date().toISOString() });
}
});
// Optional: hook model turn-end to provide context to next response
session.on('response', async (resp: any) => {
// resp contains final agent text when model speaks
const sessionId = ctx.room.name;
appendTurn(sessionId, { speaker: 'agent', text: resp.text, ts: new Date().toISOString() });
});
// Start session
await session.start();
// On agent join, optionally prime it with recent context
const sessionId = ctx.room.name;
const recent = getRecentContext(sessionId, 20);
if (recent) {
// Provide context via session.prompt or instructions depending on plugin API
try {
// Example: send a short system message
await session.sendSystemMessage(`Conversation history:\n${recent}`);
} catch (e) {
console.warn('sendSystemMessage not supported, skipping priming');
}
}
// Optional: send greeting
try { await session.say('Hello — I will interview you now. Please tell me about your most recent project.'); }
catch (e) { console.warn('greeting failed', e); }
// Keep session alive until room ends; cleanup handled by livekit when job ends
},
};
livekit.runWorker(worker).catch(err => {
console.error('Worker failed', err);
process.exit(1);
});
Notes about hooks:
• The session.on('transcript', ...) and session.on('response', ...) handlers are illustrative: check the exact event names from the installed @livekit/agents package; adapt to events emitted by the RealtimeModel plugin you use. If the plugin provides callbacks for partial/final transcripts and final responses, use those to append turns.
6) How context is provided to Gemini Live
• You maintain a transcript store (example above). When the agent starts or before generating a response, send the recent N turns (or a summarized version) as system instructions or as part of the prompt to the Gemini RealtimeModel. That gives the model session continuity.
• For long interviews: store full transcript server-side and send only the most relevant recent turns or a compact summary (reduce token usage & latency).
7) Full-session transcript vs streaming transcript
• Streaming transcript: the agent receives audio and produces partial/final transcripts during the session — append these to your store for near-real-time logs and context.
• Full-session transcript: at session end, the store contains the full turn-by-turn transcript. You can also record audio and run batch STT for higher accuracy.
8) Production suggestions
• Replace in-memory store with durable DB (Postgres, Firestore, S3).
• Save timestamps, speaker IDs, confidence scores.
• Implement idle timeout and enforce max session length to control costs.
• Use summarization to limit prompt size sent to Gemini Live.
• Securely store keys and restrict token minting to server-side endpoints.
9) Cost-control recap
• Keep sessions short and reuse session where possible.
• Enforce idle timeouts and max duration.
• Monitor LiveKit Cloud dashboard and Google billing for Gemini usage.
• Use lower-cost models or text-only fallback when appropriate.
If you want, I can:
• Convert event handlers to exact method names after you confirm the version of @livekit/agents you’ll use.
• Provide a production-ready token API (with room creation and room-to-session mapping).
• Show how to persist transcripts to Postgres with example schema.
Which would you like next?broad-librarian-92914
12/12/2025, 11:52 AMtall-airline-16756
12/12/2025, 11:52 AMbroad-librarian-92914
12/12/2025, 11:53 AMtall-airline-16756
12/12/2025, 11:54 AMimport React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './globals.css';
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode><App /></React.StrictMode>
);
frontend/src/App.tsx
'use client';
import React, { useEffect, useRef } from 'react';
import { TokenSource } from 'livekit-client';
import {
SessionProvider,
useSession,
ControlBar,
RoomAudioRenderer,
} from '@livekit/components-react';
import '@livekit/components-styles';
function Inner() {
// fetch token from token server
const tokenSource = useRef(TokenSource.fetch(`/api/token?name=Candidate&room=interview-room`)).current;
const session = useSession(tokenSource);
useEffect(() => {
session.start();
return () => session.end();
}, [session]);
return (
<SessionProvider session={session}>
<div style={{ padding: 20 }}>
<h2>AI Interview — Candidate</h2>
<ControlBar controls={{ microphone: true, camera: false, screenshare: false }} />
<RoomAudioRenderer />
</div>
</SessionProvider>
);
}
export default function App() { return <Inner />; }
frontend/src/globals.css
@import '@livekit/components-styles';
body { font-family: system-ui, sans-serif; margin:0; }
package.json scripts (frontend)
• "dev": "vite"
• "build": "vite build"
• "preview": "vite preview"
Run cd frontend pnpm dev Open http://localhost:5173
Notes
• Token endpoint is proxied to token-server at /api/token (see token-server setup).
• For production, set NEXT_PUBLIC_LIVEKIT_URL and use secure token generation.
---
2) TOKEN SERVER — Express (JavaScript) Create a separate folder token-server.
Commands cd .. mkdir token-server && cd token-server pnpm init -y pnpm add express livekit-server-sdk dotenv cors
Files
token-server/.env
LIVEKIT_API_KEY=your_livekit_api_key
LIVEKIT_API_SECRET=your_livekit_api_secret
NEXT_PUBLIC_LIVEKIT_URL=wss://your-project.livekit.cloud
PORT=3000
token-server/server.js
import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import path from 'path';
import { AccessToken, RoomGrant } from 'livekit-server-sdk';
dotenv.config();
const app = express();
app.use(cors());
app.use(express.json());
const PORT = process.env.PORT || 3000;
const LIVEKIT_URL = process.env.NEXT_PUBLIC_LIVEKIT_URL;
app.get('/api/token', (req, res) => {
const identity = Array.isArray(req.query.name) ? req.query.name[0] : (req.query.name || 'user');
const room = Array.isArray(req.query.room) ? req.query.room[0] : (req.query.room || 'interview-room');
if (!process.env.LIVEKIT_API_KEY || !process.env.LIVEKIT_API_SECRET) {
return res.status(500).json({ error: 'Missing server env vars' });
}
const at = new AccessToken(process.env.LIVEKIT_API_KEY, process.env.LIVEKIT_API_SECRET, { identity });
const grant = new RoomGrant({ room });
at.addGrant(grant);
res.json({ token: at.toJwt(), url: LIVEKIT_URL });
});
// Optional: serve frontend built files if you place them here
app.use(express.static(path.join(process.cwd(), '../frontend/dist')));
app.get('*', (req, res) => {
res.sendFile(path.join(process.cwd(), '../frontend/dist/index.html'));
});
app.listen(PORT, () => console.log(`Token server listening ${PORT}`));
Run cd token-server pnpm node server.js Frontend fetches token from http://localhost:3000/api/token. If frontend runs on different port, set up proxy or CORS.
---
3) AGENT — TypeScript Node agent (Gemini Live) (recommended to deploy to LiveKit Cloud) Commands cd .. mkdir agent && cd agent pnpm init -y pnpm add @livekit/agents @livekit/agents-plugin-google dotenv pnpm add -D typescript ts-node @types/node npx tsc --init
agent/.env
LIVEKIT_API_KEY=your_livekit_api_key
LIVEKIT_API_SECRET=your_livekit_api_secret
LIVEKIT_URL=wss://your-project.livekit.cloud
GOOGLE_API_KEY=your_gemini_api_key
agent/tsconfig.json (ensure outDir set to dist)
{
"compilerOptions": {
"target": "ES2022",
"module": "CommonJS",
"outDir": "dist",
"rootDir": "src",
"esModuleInterop": true,
"strict": true,
"skipLibCheck": true
}
}
agent/src/transcriptStore.ts
export type Turn = { speaker: 'candidate'|'agent', text: string, ts: string };
const store: Record<string, Turn[]> = {};
export function appendTurn(sessionId: string, turn: Turn) {
if (!store[sessionId]) store[sessionId] = [];
store[sessionId].push(turn);
}
export function getRecentContext(sessionId: string, max = 10) {
const arr = store[sessionId] || [];
return arr.slice(-max).map(t => `${t.speaker}: ${t.text}`).join('\n');
}
agent/src/agent.ts
import dotenv from 'dotenv';
dotenv.config();
import * as livekit from '@livekit/agents';
import * as google from '@livekit/agents-plugin-google';
import { appendTurn, getRecentContext } from './transcriptStore';
const { LIVEKIT_API_KEY, LIVEKIT_API_SECRET, LIVEKIT_URL, GOOGLE_API_KEY } = process.env;
if (!LIVEKIT_API_KEY || !LIVEKIT_API_SECRET || !LIVEKIT_URL || !GOOGLE_API_KEY) {
throw new Error('Missing env vars');
}
const worker: livekit.WorkerOptions = {
apiKey: LIVEKIT_API_KEY,
apiSecret: LIVEKIT_API_SECRET,
callbackUrl: LIVEKIT_URL,
participantLimit: 0,
async workerInit() {
console.log('Agent worker initialized');
},
async jobRequest(ctx: livekit.JobContext) {
console.log('Job requested for room', ctx.room.name);
await ctx.connect({ autoSubscribe: livekit.AutoSubscribe.AUDIO_ONLY });
const llm = new google.realtime.RealtimeModel({
apiKey: GOOGLE_API_KEY,
model: 'gemini-2.0-flash-exp',
voice: 'Puck',
temperature: 0.7,
instructions: 'You are an interviewer. Ask one question at a time and be concise.',
});
const session = new livekit.AgentSession({ room: ctx.room, llm });
// Example hooks (event names may vary by version)
session.on('transcript', (evt: any) => {
if (evt.final) {
const sessionId = ctx.room.name;
const speaker = evt.speaker === 'participant' ? 'candidate' : 'agent';
appendTurn(sessionId, { speaker, text: evt.text, ts: new Date().toISOString() });
}
});
session.on('response', (resp: any) => {
const sessionId = ctx.room.name;
appendTurn(sessionId, { speaker: 'agent', text: resp.text, ts: new Date().toISOString() });
});
await session.start();
// Prime with recent context if exists
const recent = getRecentContext(ctx.room.name, 20);
if (recent) {
try { await session.sendSystemMessage(`Conversation history:\n${recent}`); } catch {}
}
try { await session.say('Hello — I will be your interviewer. Tell me about your most recent project.'); }
catch (e) { console.warn('greeting failed', e); }
},
};
livekit.runWorker(worker).catch(err => { console.error('Worker failed', err); process.exit(1); });
package.json scripts (agent)
"scripts": {
"dev": "ts-node src/agent.ts",
"build": "tsc",
"start": "node dist/agent.js"
}
Run (dev) cd agent pnpm run dev
Deploy
• Build: pnpm run build
• Deploy to LiveKit Cloud via lk agent deploy (see LiveKit CLI docs) or run agent on your host.
Notes on events
• Event names `transcript`/`response` are illustrative; adapt to your @livekit/agents version’s API for transcript/response callbacks.
---
4) Wiring & session context
• Room name ties frontend user → token server → agent. Use consistent room names or generate unique session IDs per interview.
• Transcript store: appends final transcripts; use DB in production.
• Before generating replies, prime the model with recent context via sendSystemMessage or the plugin’s API so Gemini Live has session history.
---
5) Transcription & full-session transcript
• LiveKit routes audio; STT/transcription is produced by your agent via Gemini Live plugin (or separate STT). Save partial/final transcripts to transcript store for full-session history.
• For higher accuracy, record audio and run offline STT on recordings, then store final transcript.
---
6) Cost-control tips (brief)
• Free Build plan: 1,000 free agent minutes/month.
• Agent session billing: $0.01/minute beyond free allotment.
• Enforce idle timeout and max session length; call session.end() on inactivity.
• Limit concurrent sessions with worker settings and server-side checks.
• Use summarization to reduce context sent to model.
---
7) Next steps I can provide (pick one)
• Provide exact LiveKit CLI deploy commands & Dockerfile for agent.
• Replace in-memory transcript store with Postgres example.
• Add VAD/silence detection snippet to auto-end sessions.
Which next?broad-librarian-92914
12/12/2025, 12:01 PMUncaught TypeError: TokenSource.fetch is not a function
getting this error when opening http://localhost:5173 after first steptall-airline-16756
12/12/2025, 12:01 PMTokenSource.fetch wasn't called correctly or your import/version doesn't expose that static method. Use one of TokenSource's static factories instead. Quick fixes:
1) If you have a backend token endpoint (recommended):
• Use TokenSource.fetch with the token URL:
import { TokenSource } from 'livekit-client';
const tokenSource = TokenSource.fetch('/api/token?name=Candidate&room=interview-room');
or in React with ref:
const tokenSourceRef = useRef(TokenSource.fetch('/api/token?name=Candidate&room=interview-room')).current;
2) If you want the sandbox token server:
const tokenSourceRef = useRef(TokenSource.sandboxTokenServer('your-sandbox-id')).current;
3) If you already have a JWT token:
const tokenSourceRef = useRef(TokenSource.constant('YOUR_JWT_TOKEN')).current;
Checklist if it still fails:
• Ensure livekit-client is installed and up-to-date: pnpm add livekit-client
• Import from the package: import { TokenSource } from 'livekit-client';
• Confirm your build isn't using an older cached bundle — restart dev server.
If you want, paste the exact import line and the TokenSource line from your App.tsx and I’ll correct it for you.
Sources: React quickstart | LiveKit docsbroad-librarian-92914
12/12/2025, 12:36 PMtall-airline-16756
12/12/2025, 12:37 PMparticipant_token. I'll show how to fix the token endpoint, how to verify the response, and what to change in the frontend.
1) Fix your token server response
• Return JSON: { token: "<JWT>", url: "<wss://...>" }
Example Express handler (JavaScript):
import { AccessToken, RoomGrant } from 'livekit-server-sdk';
app.get('/api/token', (req, res) => {
const identity = req.query.name || 'user';
const room = req.query.room || 'interview-room';
const at = new AccessToken(process.env.LIVEKIT_API_KEY, process.env.LIVEKIT_API_SECRET, { identity });
at.addGrant(new RoomGrant({ room }));
res.json({ token: at.toJwt(), url: process.env.NEXT_PUBLIC_LIVEKIT_URL });
});
2) Verify the token endpoint manually
• Open in browser or curl:
curl 'http://localhost:3000/api/token?name=Candidate&room=interview-room'
• You should see JSON like:
{ "token": "eyJ...", "url":"wss://your-project.livekit.cloud" }
• If you see participant_token or another field name, change it to token.
3) Use TokenSource.fetch correctly in the frontend
• Import and create token source:
import { TokenSource } from 'livekit-client';
const tokenSource = TokenSource.fetch('/api/token?name=Candidate&room=interview-room');
• In React with ref:
const tokenSourceRef = useRef(TokenSource.fetch('/api/token?name=Candidate&room=interview-room')).current;
• Or use TokenSource.constant('<JWT>') to test with a known token.
4) Quick debug checklist
• Confirm token-server returns { token, url } (not participant_token).
• Confirm no proxy or middleware rewrites response fields.
• Confirm frontend uses latest livekit-client and imports TokenSource from 'livekit-client'.
• Check browser network tab: inspect /api/token response body and HTTP status.
• If token looks correct but client still errors, paste the JSON response here and I’ll inspect it.
If you want, paste the exact /api/token JSON you get (or the token-server code you’re running) and I’ll point out the necessary change. Would you like me to provide a curl command and expected sample response?broad-librarian-92914
12/12/2025, 12:49 PM{
"source": "microphone",
"muted": false,
"enabled": true,
"kind": "audio",
"streamID": "13ab8f89-b516-47f2-8d71-65ac649d0b21",
"streamTrackID": "13ab8f89-b516-47f2-8d71-65ac649d0b21"
}tall-airline-16756
12/12/2025, 12:49 PMbroad-librarian-92914
12/12/2025, 12:49 PMcurl 'http://localhost:5173/api/token?name=Candidate&room=interview-room' \
-H 'Accept: */*' \
-H 'Accept-Language: en-US,en;q=0.9' \
-H 'Connection: keep-alive' \
-b '__clerk_db_jwt_soCcRTYm=dvb_33YhGK1Yb5htZEI3W1wL4S8FYFe; __client_uat_soCcRTYm=0; __clerk_db_jwt_NE4Ccp9w=dvb_33YiqMooKzFaIlSiKcle1FZ8GUP; __clerk_db_jwt=dvb_33YiqMooKzFaIlSiKcle1FZ8GUP; __refresh_NE4Ccp9w=tbcqCKpSIdyCktYrpKKX; __client_uat_NE4Ccp9w=0; __client_uat=0; sb-ugyuuydyrkclbbbsldho-auth-token=base64-eyJhY2Nlc3NfdG9rZW4iOiJleUpoYkdjaU9pSklVekkxTmlJc0ltdHBaQ0k2SWt0U2FHaHNZa2MwTDNGSFQxbE1jRmtpTENKMGVYQWlPaUpLVjFRaWZRLmV5SnBjM01pT2lKb2RIUndjem92TDNWbmVYVjFlV1I1Y210amJHSmlZbk5zWkdodkxuTjFjR0ZpWVhObExtTnZMMkYxZEdndmRqRWlMQ0p6ZFdJaU9pSXdZelkyTmpVMVl5MHpaVEl3TFRRMk1tRXRZVGc1TmkxbU9XWTRNRGs1T0dWbU5EY2lMQ0poZFdRaU9pSmhkWFJvWlc1MGFXTmhkR1ZrSWl3aVpYaHdJam94TnpZMU16a3lPREl6TENKcFlYUWlPakUzTmpVek9Ea3lNak1zSW1WdFlXbHNJam9pYzNWeWVXRkFaMjFoYVd3dVkyOXRJaXdpY0dodmJtVWlPaUlpTENKaGNIQmZiV1YwWVdSaGRHRWlPbnNpY0hKdmRtbGtaWElpT2lKbGJXRnBiQ0lzSW5CeWIzWnBaR1Z5Y3lJNld5SmxiV0ZwYkNKZGZTd2lkWE5sY2w5dFpYUmhaR0YwWVNJNmV5SmxiV0ZwYkNJNkluTjFjbmxoUUdkdFlXbHNMbU52YlNJc0ltVnRZV2xzWDNabGNtbG1hV1ZrSWpwMGNuVmxMQ0ptZFd4c1gyNWhiV1VpT2lKemRYSjVZU0lzSW5Cb2IyNWxYM1psY21sbWFXVmtJanBtWVd4elpTd2ljM1ZpSWpvaU1HTTJOalkxTldNdE0yVXlNQzAwTmpKaExXRTRPVFl0WmpsbU9EQTVPVGhsWmpRM0luMHNJbkp2YkdVaU9pSmhkWFJvWlc1MGFXTmhkR1ZrSWl3aVlXRnNJam9pWVdGc01TSXNJbUZ0Y2lJNlczc2liV1YwYUc5a0lqb2ljR0Z6YzNkdmNtUWlMQ0owYVcxbGMzUmhiWEFpT2pFM05qUXhOVGMzTkRsOVhTd2ljMlZ6YzJsdmJsOXBaQ0k2SWpFNU9EQmlPRFkxTFdRMVpHVXROREl4T1MwNE1UVmlMVFV5WlRJMU5tWTRObUZtTnlJc0ltbHpYMkZ1YjI1NWJXOTFjeUk2Wm1Gc2MyVjkuQWp3bnJ2VkRSUmhrdDNwN2t5Sy1qbkJlckhfZmEwMklFd1JkeF9QZGN5dyIsInRva2VuX3R5cGUiOiJiZWFyZXIiLCJleHBpcmVzX2luIjozNjAwLCJleHBpcmVzX2F0IjoxNzY1MzkyODIzLCJyZWZyZXNoX3Rva2VuIjoic2Y2aG8zNmZ4a2t3IiwidXNlciI6eyJpZCI6IjBjNjY2NTVjLTNlMjAtNDYyYS1hODk2LWY5ZjgwOTk4ZWY0NyIsImF1ZCI6ImF1dGhlbnRpY2F0ZWQiLCJyb2xlIjoiYXV0aGVudGljYXRlZCIsImVtYWlsIjoic3VyeWFAZ21haWwuY29tIiwiZW1haWxfY29uZmlybWVkX2F0IjoiMjAyNS0xMS0yNVQxNToyNzowNi41MDI0MjlaIiwicGhvbmUiOiIiLCJjb25maXJtZWRfYXQiOiIyMDI1LTExLTI1VDE1OjI3OjA2LjUwMjQyOVoiLCJsYXN0X3NpZ25faW5fYXQiOiIyMDI1LTEyLTA0VDEyOjIyOjQ0Ljc5MTcxN1oiLCJhcHBfbWV0YWRhdGEiOnsicHJvdmlkZXIiOiJlbWFpbCIsInByb3ZpZGVycyI6WyJlbWFpbCJdfSwidXNlcl9tZXRhZGF0YSI6eyJlbWFpbCI6InN1cnlhQGdtYWlsLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLCJmdWxsX25hbWUiOiJzdXJ5YSIsInBob25lX3ZlcmlmaWVkIjpmYWxzZSwic3ViIjoiMGM2NjY1NWMtM2UyMC00NjJhLWE4OTYtZjlmODA5OThlZjQ3In0sImlkZW50aXRpZXMiOlt7ImlkZW50aXR5X2lkIjoiN2U1ZWZhOGItMDQ5ZC00NjY0LWFiM2EtOWVmMjU5Y2E3MzlhIiwiaWQiOiIwYzY2NjU1Yy0zZTIwLTQ2MmEtYTg5Ni1mOWY4MDk5OGVmNDciLCJ1c2VyX2lkIjoiMGM2NjY1NWMtM2UyMC00NjJhLWE4OTYtZjlmODA5OThlZjQ3IiwiaWRlbnRpdHlfZGF0YSI6eyJlbWFpbCI6InN1cnlhQGdtYWlsLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwiZnVsbF9uYW1lIjoic3VyeWEiLCJwaG9uZV92ZXJpZmllZCI6ZmFsc2UsInN1YiI6IjBjNjY2NTVjLTNlMjAtNDYyYS1hODk2LWY5ZjgwOTk4ZWY0NyJ9LCJwcm92aWRlciI6ImVtYWlsIiwibGFzdF9zaWduX2luX2F0IjoiMjAyNS0xMS0yNVQxNToyNzowNi40OTMzMzdaIiwiY3JlYXRlZF9hdCI6IjIwMjUtMTEtMjVUMTU6Mjc6MDYuNDkzMzg5WiIsInVwZGF0ZWRfYXQiOiIyMDI1LTExLTI1VDE1OjI3OjA2LjQ5MzM4OVoiLCJlbWFpbCI6InN1cnlhQGdtYWlsLmNvbSJ9XSwiY3JlYXRlZF9hdCI6IjIwMjUtMTEtMjVUMTU6Mjc6MDYuNDcyMjQ4WiIsInVwZGF0ZWRfYXQiOiIyMDI1LTEyLTEwVDE3OjUzOjQzLjM0OTk2MloiLCJpc19hbm9ueW1vdXMiOmZhbHNlfX0; __next_hmr_refresh_hash__=ce9b78108324a8c279ae336d5a57e2e2d979b9f54407855f' \
-H 'Referer: http://localhost:5173/' \
-H 'Sec-Fetch-Dest: empty' \
-H 'Sec-Fetch-Mode: cors' \
-H 'Sec-Fetch-Site: same-origin' \
-H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36' \
-H 'sec-ch-ua: "Chromium";v="142", "Google Chrome";v="142", "Not_A Brand";v="99"' \
-H 'sec-ch-ua-mobile: ?0' \
-H 'sec-ch-ua-platform: "macOS"'tall-airline-16756
12/12/2025, 12:50 PMbroad-librarian-92914
12/12/2025, 1:11 PMcurl 'http://localhost:3000/api/token?name=Candidate&room=interview-room' \
-H 'Accept: */*' \
-H 'Accept-Language: en-US,en;q=0.9' \
-H 'Connection: keep-alive' \
-H 'If-None-Match: W/"c-CU3ik6vAPXw2b/e+4jqew5kHg/w"' \
-H 'Origin: http://localhost:5173' \
-H 'Referer: http://localhost:5173/' \
-H 'Sec-Fetch-Dest: empty' \
-H 'Sec-Fetch-Mode: cors' \
-H 'Sec-Fetch-Site: same-site' \
-H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36' \
-H 'sec-ch-ua: "Chromium";v="142", "Google Chrome";v="142", "Not_A Brand";v="99"' \
-H 'sec-ch-ua-mobile: ?0' \
-H 'sec-ch-ua-platform: "macOS"'tall-airline-16756
12/12/2025, 1:11 PMbroad-librarian-92914
12/12/2025, 1:12 PM{
"token": {}
}tall-airline-16756
12/12/2025, 1:12 PM"token": {} means your token route is returning an empty object instead of a JWT string. That’s why the LiveKit client can’t decode the token. Let’s fix it.
1) Confirm env vars
• Ensure LIVEKIT_API_KEY and LIVEKIT_API_SECRET are set in token-server/.env and your server is restarted after changes.
2) Replace your /api/token handler with this minimal, correct code (JavaScript/Express):
import express from 'express';
import dotenv from 'dotenv';
import cors from 'cors';
import { AccessToken, RoomGrant } from 'livekit-server-sdk';
dotenv.config();
const app = express();
app.use(cors());
app.get('/api/token', (req, res) => {
const identity = req.query.name || 'user';
const room = req.query.room || 'interview-room';
if (!process.env.LIVEKIT_API_KEY || !process.env.LIVEKIT_API_SECRET) {
return res.status(500).json({ error: 'Missing LIVEKIT_API_KEY/SECRET' });
}
const at = new AccessToken(process.env.LIVEKIT_API_KEY, process.env.LIVEKIT_API_SECRET, { identity });
const grant = new RoomGrant({ room });
at.addGrant(grant);
// Return JWT string, not an object
res.json({ token: at.toJwt(), url: process.env.NEXT_PUBLIC_LIVEKIT_URL });
});
app.listen(process.env.PORT || 3000, () => console.log('token server running'));
3) Verify the endpoint manually
• Run:
curl -s 'http://localhost:3000/api/token?name=Candidate&room=interview-room' | jq
• Expected:
{ "token": "eyJhbGciOiJ...", "url": "wss://your-project.livekit.cloud" }
4) Frontend
• Point TokenSource.fetch at the token server:
TokenSource.fetch('http://localhost:3000/api/token?name=Candidate&room=interview-room')
• Or set a Vite proxy so /api routes forward to :3000.
5) If token is still empty
• Paste your token-server /api/token code here.
• Or run this Node snippet to test locally and paste output:
const { AccessToken, RoomGrant } = require('livekit-server-sdk');
const at = new AccessToken(process.env.LIVEKIT_API_KEY, process.env.LIVEKIT_API_SECRET, { identity: 'test' });
at.addGrant(new RoomGrant({ room: 'r' }));
console.log(at.toJwt());
I’ll review the output/code and help you finish wiring it.broad-librarian-92914
12/12/2025, 1:17 PMfile:///Users/prathammungekar/Git%20Repo/livekit-test/token-server/server.js:5
import { AccessToken, RoomGrant } from 'livekit-server-sdk';
^^^^^^^^^
SyntaxError: The requested module 'livekit-server-sdk' does not provide an export named 'RoomGrant'
at #_instantiate (node:internal/modules/esm/module_job:254:21)
at async ModuleJob.run (node:internal/modules/esm/module_job:369:5)
at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:691:26)
at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:101:5)
Node.js v24.10.0
ELIFECYCLE Command failed with exit code 1.tall-airline-16756
12/12/2025, 1:17 PMlivekit-server-sdk exports grants. Fix quickly by creating the grant via the AccessToken API instead of importing RoomGrant, or use the CommonJS require style.
Two easy fixes — pick one.
Option A — ESM + create grant object inline (recommended)
import express from 'express';
import dotenv from 'dotenv';
import cors from 'cors';
import { AccessToken } from 'livekit-server-sdk';
dotenv.config();
const app = express();
app.use(cors());
app.get('/api/token', (req, res) => {
const identity = req.query.name || 'user';
const room = req.query.room || 'interview-room';
if (!process.env.LIVEKIT_API_KEY || !process.env.LIVEKIT_API_SECRET) {
return res.status(500).json({ error: 'Missing LIVEKIT_API_KEY/SECRET' });
}
const at = new AccessToken(process.env.LIVEKIT_API_KEY, process.env.LIVEKIT_API_SECRET, { identity });
// create grant as plain object
at.addGrant({ room, roomJoin: true, canPublish: true, canSubscribe: true });
res.json({ token: at.toJwt(), url: process.env.NEXT_PUBLIC_LIVEKIT_URL });
});
app.listen(process.env.PORT || 3000, () => console.log('token server running'));
Option B — CommonJS require (if you prefer using RoomGrant)
// rename file server.cjs and run with node server.cjs
const express = require('express');
const dotenv = require('dotenv');
const cors = require('cors');
const { AccessToken, RoomGrant } = require('livekit-server-sdk');
dotenv.config();
const app = express();
app.use(cors());
app.get('/api/token', (req, res) => {
const identity = req.query.name || 'user';
const room = req.query.room || 'interview-room';
const at = new AccessToken(process.env.LIVEKIT_API_KEY, process.env.LIVEKIT_API_SECRET, { identity });
at.addGrant(new RoomGrant({ room }));
res.json({ token: at.toJwt(), url: process.env.NEXT_PUBLIC_LIVEKIT_URL });
});
app.listen(process.env.PORT || 3000, () => console.log('token server running'));
After applying one of these:
1. Restart the token server.
2. Run:
curl -s 'http://localhost:3000/api/token?name=Candidate&room=interview-room' | jq You should see: { "token": "eyJ...", "url":"wss://..." }
If you prefer, paste your current server.js and I’ll patch it in place. Which option do you want to use?broad-librarian-92914
12/12/2025, 1:23 PMtall-airline-16756
12/12/2025, 1:23 PMgrants. You need to add a Room grant before calling toJwt(). Use the ESM-friendly pattern below, then restart the token server and re-check the curl output.
Replace your token route with this exact handler:
import express from 'express';
import dotenv from 'dotenv';
import cors from 'cors';
import { AccessToken } from 'livekit-server-sdk';
dotenv.config();
const app = express();
app.use(cors());
app.get('/api/token', (req, res) => {
const identity = Array.isArray(req.query.name) ? req.query.name[0] : (req.query.name || 'user');
const room = Array.isArray(req.query.room) ? req.query.room[0] : (req.query.room || 'interview-room');
if (!process.env.LIVEKIT_API_KEY || !process.env.LIVEKIT_API_SECRET) {
return res.status(500).json({ error: 'Missing LIVEKIT_API_KEY/SECRET' });
}
const at = new AccessToken(process.env.LIVEKIT_API_KEY, process.env.LIVEKIT_API_SECRET, { identity });
// add a room grant as a plain object
at.addGrant({ room, roomJoin: true, canPublish: true, canSubscribe: true });
res.json({ token: at.toJwt(), url: process.env.NEXT_PUBLIC_LIVEKIT_URL });
});
app.listen(process.env.PORT || 3000, () => console.log(`token server running on ${process.env.PORT||3000}`));
Verify:
1. Restart token-server.
2. Run:
curl -s 'http://localhost:3000/api/token?name=Candidate&room=interview-room' | jq Expected: { "token": "eyJ...", "url":"wss://your-project.livekit.cloud" }
If you still see "token": {} or grants empty, paste the exact server.js you’re running and the output of console.log(at) right before res.json(...) and I’ll patch it.broad-librarian-92914
12/12/2025, 1:25 PMtall-airline-16756
12/12/2025, 1:25 PMimport express from 'express';
import dotenv from 'dotenv';
import cors from 'cors';
import { AccessToken } from 'livekit-server-sdk';
dotenv.config();
const app = express();
app.use(cors());
app.get('/api/token', (req, res) => {
const identity = Array.isArray(req.query.name) ? req.query.name[0] : (req.query.name || 'user');
const room = Array.isArray(req.query.room) ? req.query.room[0] : (req.query.room || 'interview-room');
if (!process.env.LIVEKIT_API_KEY || !process.env.LIVEKIT_API_SECRET) {
return res.status(500).json({ error: 'Missing LIVEKIT_API_KEY/SECRET' });
}
const at = new AccessToken(process.env.LIVEKIT_API_KEY, process.env.LIVEKIT_API_SECRET, { identity });
at.addGrant({ room, roomJoin: true, canPublish: true, canSubscribe: true });
// IMPORTANT: return the JWT string, not the AccessToken object
const jwt = at.toJwt();
console.log('generated token length:', jwt.length);
res.json({ token: jwt, url: process.env.NEXT_PUBLIC_LIVEKIT_URL });
});
app.listen(process.env.PORT || 3000, () => console.log(`token server running on ${process.env.PORT||3000}`));
2) Restart the token server, then verify: curl -s 'http://localhost:3000/api/token?name=Candidate&room=interview-room' | jq Expected: { "token": "eyJhbGciOiJ...", "url": "wss://vertex-ai-1879pkoh.livekit.cloud" }
3) Frontend: point TokenSource.fetch to the token server (or use Vite proxy)
import { TokenSource } from 'livekit-client';
const tokenSource = TokenSource.fetch('http://localhost:3000/api/token?name=Candidate&room=interview-room');
If after this you still see `"token": {}`:
• Paste the current server.js exactly as running.
• Paste console.log output from the server (the printed token length).
I’ll inspect and patch it.broad-librarian-92914
12/12/2025, 1:27 PMtall-airline-16756
12/12/2025, 1:28 PMtoken. That means the code is serializing the AccessToken object itself instead of the JWT string from at.toJwt().
Do this exact, minimal server.js (ESM) — it adds the room grant and returns the JWT string:
// token-server/server.js
import express from 'express';
import dotenv from 'dotenv';
import cors from 'cors';
import { AccessToken } from 'livekit-server-sdk';
dotenv.config();
const app = express();
app.use(cors());
app.get('/api/token', (req, res) => {
const identity = Array.isArray(req.query.name) ? req.query.name[0] : (req.query.name || 'user');
const room = Array.isArray(req.query.room) ? req.query.room[0] : (req.query.room || 'interview-room');
if (!process.env.LIVEKIT_API_KEY || !process.env.LIVEKIT_API_SECRET) {
return res.status(500).json({ error: 'Missing LIVEKIT_API_KEY/SECRET' });
}
const at = new AccessToken(process.env.LIVEKIT_API_KEY, process.env.LIVEKIT_API_SECRET, { identity });
// add grant as plain object (ESM-friendly)
at.addGrant({ room, roomJoin: true, canPublish: true, canSubscribe: true });
const jwt = at.toJwt(); // <--- important: produce the JWT string
console.log('generated token length:', jwt?.length);
res.json({ token: jwt, url: process.env.NEXT_PUBLIC_LIVEKIT_URL });
});
app.listen(process.env.PORT || 3000, () => {
console.log(`token server running on ${process.env.PORT || 3000}`);
});
After updating:
1. Restart the token server (kill + restart).
2. Verify output:
curl -s 'http://localhost:3000/api/token?name=Candidate&room=interview-room' | jq Expected: { "token": "eyJhbGciOiJ...", "url": "wss://vertex-ai-1879pkoh.livekit.cloud" }
If you still get `"token": {}`:
• Paste the exact contents of your running server.js (so I can spot any serialization before res.json).
• Also paste the console log printed for generated token length:.
If you prefer quick debugging, run this Node one-liner in the token-server folder (with env vars set) and paste output:
node -e "const { AccessToken } = require('livekit-server-sdk'); const at = new AccessToken(process.env.LIVEKIT_API_KEY, process.env.LIVEKIT_API_SECRET, {identity:'test'}); at.addGrant({room:'r',roomJoin:true}); console.log(typeof at.toJwt(), at.toJwt().slice(0,10));"
I’ll take the next step after you paste the server.js or the one-liner output.broad-librarian-92914
12/12/2025, 1:31 PMtall-airline-16756
12/12/2025, 1:31 PMtoken. Let’s narrow it down quickly — please run these two quick checks and paste their outputs.
1) Run this Node one-liner in your token-server folder (with your env vars loaded):
node -e "const { AccessToken } = require('livekit-server-sdk'); const at = new AccessToken(process.env.LIVEKIT_API_KEY, process.env.LIVEKIT_API_SECRET, {identity:'test'}); at.addGrant({room:'r',roomJoin:true,canPublish:true,canSubscribe:true}); console.log('type=',typeof at.toJwt(),'len=', at.toJwt()?.length);"
Paste the exact output.
2) Paste the full contents of the token-server file you are actually running (server.js). I’ll look for any place that might be serializing the AccessToken object instead of the JWT string and give the exact one-line fix.
If you prefer, I can also provide a minimal drop-in server.js you can copy-paste and run immediately. Which do you want?broad-librarian-92914
12/12/2025, 1:33 PMtall-airline-16756
12/12/2025, 1:33 PMimport dotenv from 'dotenv';
dotenv.config();
• Restart the server after any .env change.
2) Quick test with environment variables inline Run this in your token-server folder (replace with your real keys):
LIVEKIT_API_KEY=API6ioefkASKxwA LIVEKIT_API_SECRET=HiJgjL2ekf6l9ynzd5rIMm5dhiuiF4oP2PVp2Zp7coG node -e "const { AccessToken } = require('livekit-server-sdk'); const at=new AccessToken(process.env.LIVEKIT_API_KEY, process.env.LIVEKIT_API_SECRET,{identity:'test'}); at.addGrant({room:'r',roomJoin:true}); console.log(typeof at.toJwt(), at.toJwt().slice(0,10));"
Expected output: string <first 10 chars of JWT>
3) Minimal working token-server.js (copy-paste and run)
// token-server/server.js
import express from 'express';
import dotenv from 'dotenv';
import cors from 'cors';
import { AccessToken } from 'livekit-server-sdk';
dotenv.config();
const app = express();
app.use(cors());
app.get('/api/token', (req, res) => {
const identity = req.query.name || 'user';
const room = req.query.room || 'interview-room';
if (!process.env.LIVEKIT_API_KEY || !process.env.LIVEKIT_API_SECRET) {
return res.status(500).json({ error: 'Missing LIVEKIT_API_KEY/SECRET' });
}
const at = new AccessToken(process.env.LIVEKIT_API_KEY, process.env.LIVEKIT_API_SECRET, { identity });
at.addGrant({ room, roomJoin: true, canPublish: true, canSubscribe: true });
const jwt = at.toJwt();
console.log('generated token length:', jwt.length);
res.json({ token: jwt, url: process.env.NEXT_PUBLIC_LIVEKIT_URL });
});
app.listen(process.env.PORT || 3000, () => console.log('token server running'));
Run:
• Ensure .env contains the keys and NEXT_PUBLIC_LIVEKIT_URL
• Restart: node server.js
• Test: curl -s 'http://localhost:3000/api/token?name=Candidate&room=interview-room' | jq
4) If you still see "token": {}
• Paste the exact server.js you are running.
• Paste the console output from the server (including the generated token length log).
I will spot the bug and give the fix.broad-librarian-92914
12/12/2025, 1:35 PMtall-airline-16756
12/12/2025, 1:36 PMtoJwt() is async in your SDK version. Use async/await. Quick fixes:
1) Async one-liner to test (run in token-server folder, with env vars set):
LIVEKIT_API_KEY=... LIVEKIT_API_SECRET=... node -e "const { AccessToken } = require('livekit-server-sdk'); (async ()=>{ const at=new AccessToken(process.env.LIVEKIT_API_KEY, process.env.LIVEKIT_API_SECRET,{identity:'test'}); at.addGrant({room:'r',roomJoin:true}); const jwt=await at.toJwt(); console.log(typeof jwt, jwt.slice(0,10)); })()"
2) Update server handler (await toJwt()):
import express from 'express';
import dotenv from 'dotenv';
import cors from 'cors';
import { AccessToken } from 'livekit-server-sdk';
dotenv.config();
const app = express();
app.use(cors());
app.get('/api/token', async (req, res) => {
const identity = req.query.name || 'user';
const room = req.query.room || 'interview-room';
if (!process.env.LIVEKIT_API_KEY || !process.env.LIVEKIT_API_SECRET) {
return res.status(500).json({ error: 'Missing LIVEKIT_API_KEY/SECRET' });
}
const at = new AccessToken(process.env.LIVEKIT_API_KEY, process.env.LIVEKIT_API_SECRET, { identity });
at.addGrant({ room, roomJoin: true, canPublish: true, canSubscribe: true });
try {
const jwt = await at.toJwt();
console.log('generated token length:', jwt.length);
res.json({ token: jwt, url: process.env.NEXT_PUBLIC_LIVEKIT_URL });
} catch (err) {
console.error('toJwt error', err);
res.status(500).json({ error: 'token generation failed' });
}
});
app.listen(process.env.PORT || 3000, () => console.log('token server running'));
3) Verify:
• Restart server.
• Run:
curl -s 'http://localhost:3000/api/token?name=Candidate&room=interview-room' | jq
You should see { "token":"eyJ...", "url":"wss://..." }. Paste the curl output if it still shows an empty object and I’ll help further.broad-librarian-92914
12/12/2025, 1:37 PM{
"token": "eyJhbGciOiJIUzI1NiJ9.eyJ2aWRlbyI6eyJyb29tIjoiaW50ZXJ2aWV3LXJvb20iLCJyb29tSm9pbiI6dHJ1ZSwiY2FuUHVibGlzaCI6dHJ1ZSwiY2FuU3Vic2NyaWJlIjp0cnVlfSwiaXNzIjoiQVBJNmlvZWZrQVNLeHdBIiwiZXhwIjoxNzY1NTY4MjExLCJuYmYiOjAsInN1YiI6IkNhbmRpZGF0ZSJ9.PT3R4fXk51A4cFFY3bB2w-OSkbe9wmImMfqMYsybb_c"
}tall-airline-16756
12/12/2025, 1:37 PMimport { TokenSource } from 'livekit-client';
const tokenSource = TokenSource.fetch('http://localhost:3000/api/token?name=Candidate&room=interview-room');
• In React (useRef):
const tokenSourceRef = useRef(TokenSource.fetch('/api/token?name=Candidate&room=interview-room')).current;
(If you use a Vite proxy, /api/token can forward to <http://localhost:3000.>)
2) Restart dev servers
• Restart the token server (if changed).
• Restart Vite dev server so it picks up any config/proxy changes.
3) Verify in browser
• Open DevTools → Network → find the /api/token request.
• Response should be:
{ "token": "eyJ…", "url":"wss://your-project.livekit.cloud" }
• Client should no longer show the "cannot decode LiveKitTokenResponse.participant_token" error.
4) If you still see errors
• Paste the Network response body for /api/token from the browser.
• Or paste the exact TokenSource line from your App.tsx and I’ll correct it.
Optional: For quick local testing you can also use:
const tokenSourceRef = useRef(TokenSource.constant('eyJ...')).current;
This verifies the frontend flow without calling the token server.
Want me to show how to add a Vite proxy config to forward /api to port 3000?broad-librarian-92914
12/12/2025, 1:40 PMtall-airline-16756
12/12/2025, 1:40 PMtall-airline-16756
12/12/2025, 1:49 PMbroad-librarian-92914
12/12/2025, 1:58 PMtall-airline-16756
12/12/2025, 2:00 PMconst at = new AccessToken(process.env.LIVEKIT_API_KEY, process.env.LIVEKIT_API_SECRET, { identity });
at.addGrant({ room, roomJoin: true, canPublish: true, canSubscribe: true });
const jwt = await at.toJwt();
res.json({ token: jwt, url: process.env.NEXT_PUBLIC_LIVEKIT_URL });
2) Confirm NEXT_PUBLIC_LIVEKIT_URL is set and correct
• In token-server/.env and frontend env (if used) set:
NEXT_PUBLIC_LIVEKIT_URL=wss://vertex-ai-1879pkoh.livekit.cloud
• Restart the token server after changing .env.
• Test:
curl -s 'http://localhost:3000/api/token?name=Candidate&room=interview-room' | jq Expected shows both token (string) and url (wss://...)
3) Ensure frontend requests the correct token URL and reads response
• If token server runs on :3000, create token source:
const tokenSource = TokenSource.fetch('http://localhost:3000/api/token?name=Candidate&room=interview-room');
• Or use Vite proxy so /api/token forwards to :3000.
• Verify in browser Network tab the JSON includes the url field.
If you still get "URL is missing":
• Paste the exact curl output for /api/token (you showed token earlier — include url now).
• Paste the TokenSource line from App.tsx.
• Paste the token-server console log right after generating the JWT (add console.log(jwt.length, process.env.NEXT_PUBLIC_LIVEKIT_URL)).
I’ll use those to pinpoint the final fix.broad-librarian-92914
12/12/2025, 2:07 PMtall-airline-16756
12/12/2025, 2:07 PMkind: "audio", trackSid, and non-empty streamId).
• Verify frontend is publishing:
◦ If using LiveKit components, ensure your session/room connect includes audio: true.
◦ Manually publish to test:
const lp = room.localParticipant;
const tracks = await navigator.mediaDevices.getUserMedia({ audio: true });
lp.publishTrack(tracks.getAudioTracks()[0]);
• After calling publish, check agent logs for a new participant/audio subscription.
2) Agent subscription and response (agent → browser)
• Confirm agent joined the same room name (agent logs should show join/subscribe events).
• In agent logs, search for lines like “Agent session started”, “participant joined”, response_started / response_finished, or any Gemini plugin errors.
• If you see response logs but no audio in browser, ensure frontend is rendering audio:
◦ Add or confirm <RoomAudioRenderer /> is mounted in your React tree.
◦ Check browser Audio Autoplay policies: open Console for any “play() was prevented” messages — if present, require a user gesture (click) before joining/playing audio.
3) LiveKit Inspector / Tracks
• Use LiveKit Inspector for your project or watch the Cloud UI to confirm tracks:
◦ Do you see both candidate’s outgoing audio and agent’s outgoing audio tracks in the room?
• If agent audio track exists but browser not playing, check Track `muted`/`enabled` flags and volume.
4) Quick runtime tests to run now
• In browser console (after connect), run:
◦ List published local tracks:
console.log(room.localParticipant.getTracks());
• List remote participants and tracks:
room.participants.forEach(p => console.log(p.identity, p.getTracks()));
• In agent terminal, paste the last 20 lines of logs after you join and try to speak.
5) Common fixes
• Missing RoomAudioRenderer → add it.
• Browser blocked autoplay → require a user click before session.start().
• Agent not subscribed to audio → ensure autoSubscribe: AUTO_SUBSCRIBE.AUDIO_ONLY (or agent subscribes) and that the agent session uses the RealtimeModel with audio enabled.
• Token created without proper publish grant → confirm token grants include canPublish: true (you added these earlier).
If you paste:
• (A) browser console logs around connect + the objects from the quick runtime tests, and
• (B) agent logs (last ~20 lines),
I’ll pinpoint the exact action—whether to change frontend publishing code, add RoomAudioRenderer, adjust autoplay/user gesture, or fix agent subscription.
Sources: Gemini Live API plugin | LiveKit docs | OpenAI and LiveKit partner to turn Advanced Voice into an APIbroad-librarian-92914
12/12/2025, 2:36 PM{
"enabled": true,
"muted": false,
"trackSid": "TR_AMMA9QeWc3UZBr"
}tall-airline-16756
12/12/2025, 2:37 PMenabled: true, muted: false, trackSid present). Audio is leaving the client. Next, let’s confirm the agent is receiving it and that agent audio is reaching the browser. Please do the following and paste the results:
1) In the browser console (after connecting), run and paste output:
• room local tracks:
room.localParticipant.getTracks().map(t => ({ kind: t.kind, trackSid: t.trackSid, muted: t.isMuted(), enabled: t.isEnabled() }))
• remote participants & tracks:
Array.from(room.participants.values()).map(p => ({
id: p.identity,
tracks: p.getTracks().map(t => ({ kind: t.kind, trackSid: t.trackSid, muted: t.isMuted(), enabled: t.isEnabled() }))
}))
2) In your agent logs (last ~30 lines) paste any lines showing:
• participant joined / subscribed events
• transcript / response / TTS events
• errors from Gemini plugin or “Agent session started” / “Agent started speaking”
3) Confirm frontend audio renderer:
• Do you have <RoomAudioRenderer /> mounted? If not, add it.
• Check console for any autoplay/play() blocked warnings.
4) Quick runtime test (one-click):
• If you suspect autoplay blocked, try clicking a button before session.start() then run session.start() — report if agent audio plays.
Paste the outputs for (1) and (2). I’ll tell you exactly which flag to flip or code to add next.broad-librarian-92914
12/12/2025, 2:47 PMtall-airline-16756
12/12/2025, 2:47 PMbroad-librarian-92914
12/12/2025, 2:48 PM'use client';
import { useRef, useEffect, useState } from 'react';
import { TokenSource, ConnectionState, Track, TrackPublication } from 'livekit-client';
import {
SessionProvider,
useSession,
ControlBar,
RoomAudioRenderer,
useRoomContext,
} from '@livekit/components-react';
import '@livekit/components-styles';
function RoomContent() {
const room = useRoomContext();
const [isConnected, setIsConnected] = useState(false);
const [error, setError] = useState<string | null>(null);
const [connectionState, setConnectionState] = useState<ConnectionState>(room.state);
const [micEnabled, setMicEnabled] = useState(false);
const [micMuted, setMicMuted] = useState(true);
const [remoteParticipants, setRemoteParticipants] = useState<string[]>([]);
useEffect(() => {
const handleConnected = () => {
console.log('✅ Connected to room:', room.name);
setIsConnected(true);
setError(null);
setConnectionState(room.state);
// Check microphone state
const micTrack = room.localParticipant.getTrackPublication(Track.Source.Microphone);
if (micTrack) {
setMicEnabled(true);
setMicMuted(micTrack.isMuted);
console.log('🎤 Microphone track:', {
enabled: true,
muted: micTrack.isMuted,
subscribed: micTrack.isSubscribed,
});
}
};
const handleDisconnected = () => {
console.log('❌ Disconnected from room');
setIsConnected(false);
setConnectionState(room.state);
setMicEnabled(false);
setRemoteParticipants([]);
};
const handleConnectionStateChanged = (state: ConnectionState) => {
console.log('Connection state changed:', state);
setConnectionState(state);
if (state === ConnectionState.Connected) {
handleConnected();
} else if (state === ConnectionState.Disconnected) {
handleDisconnected();
}
};
const handleTrackPublished = (publication: TrackPublication, participant: any) => {
console.log('📡 Track published:', {
source: publication.source,
kind: publication.kind,
participant: participant.identity,
isLocal: participant === room.localParticipant,
});
if (publication.source === Track.Source.Microphone && participant === room.localParticipant) {
setMicEnabled(true);
setMicMuted(publication.isMuted);
}
};
const handleTrackSubscribed = (track: any, publication: TrackPublication, participant: any) => {
console.log('🎧 Track subscribed:', {
source: publication.source,
kind: publication.kind,
participant: participant.identity,
isLocal: participant === room.localParticipant,
});
// If it's a remote audio track, attach it
if (track.kind === Track.Kind.Audio && participant !== room.localParticipant) {
track.attach();
console.log('🔊 Remote audio track attached');
}
};
const handleParticipantConnected = (participant: any) => {
console.log('👤 Participant connected:', participant.identity);
setRemoteParticipants(prev => [...prev, participant.identity]);
};
const handleParticipantDisconnected = (participant: any) => {
console.log('👤 Participant disconnected:', participant.identity);
setRemoteParticipants(prev => prev.filter(id => id !== participant.identity));
};
// Set initial state
setConnectionState(room.state);
if (room.state === ConnectionState.Connected) {
setIsConnected(true);
const micTrack = room.localParticipant.getTrackPublication(Track.Source.Microphone);
if (micTrack) {
setMicEnabled(true);
setMicMuted(micTrack.isMuted);
}
}
// Set up event listeners
room.on('connected', handleConnected);
room.on('disconnected', handleDisconnected);
room.on('connectionStateChanged', handleConnectionStateChanged);
room.on('trackPublished', handleTrackPublished);
room.on('trackSubscribed', handleTrackSubscribed);
room.on('participantConnected', handleParticipantConnected);
room.on('participantDisconnected', handleParticipantDisconnected);
// Enable microphone track when connected
const enableMicrophone = async () => {
if (room.state === ConnectionState.Connected) {
try {
console.log('🎤 Attempting to enable microphone...');
await room.localParticipant.setMicrophoneEnabled(true);
// Wait a bit and check the track
setTimeout(() => {
const micTrack = room.localParticipant.getTrackPublication(Track.Source.Microphone);
if (micTrack) {
setMicEnabled(true);
setMicMuted(micTrack.isMuted);
console.log('✅ Microphone enabled:', {
enabled: true,
muted: micTrack.isMuted,
trackSid: micTrack.trackSid,
});
} else {
console.warn('⚠️ Microphone track not found after enabling');
}
}, 500);
} catch (err) {
console.error('❌ Failed to enable microphone:', err);
setError(err instanceof Error ? err.message : 'Failed to enable microphone');
}
}
};
if (room.state === ConnectionState.Connected) {
enableMicrophone();
} else {
room.once('connected', enableMicrophone);
}
// Check for existing remote participants
room.remoteParticipants.forEach((participant) => {
setRemoteParticipants(prev => [...prev, participant.identity]);
console.log('👤 Existing remote participant:', participant.identity);
// Check for audio tracks
participant.audioTrackPublications.forEach((publication) => {
if (publication.track) {
console.log('🔊 Found remote audio track:', publication.trackSid);
}
});
});
return () => {
room.off('connected', handleConnected);
room.off('disconnected', handleDisconnected);
room.off('connectionStateChanged', handleConnectionStateChanged);
room.off('trackPublished', handleTrackPublished);
room.off('trackSubscribed', handleTrackSubscribed);
room.off('participantConnected', handleParticipantConnected);
room.off('participantDisconnected', handleParticipantDisconnected);
};
}, [room]);
console.log('🚀 ~ RoomContent ~ room:', room.localParticipant.getTrackPublications())
return (
<div style={{ padding: 20 }}>
<h2>AI Interview — Candidate</h2>
{error && (
<div style={{ color: 'red', marginBottom: 10, padding: 10, background: '#fee' }}>
<strong>Error:</strong> {error}
</div>
)}
<div style={{ marginBottom: 10, padding: 10, background: '#f0f0f0' }}>
<div><strong>Connection State:</strong> {connectionState}</div>
{isConnected && (
<div style={{ color: 'green', marginTop: 5 }}>
✅ Connected to room: {room.name}
</div>
)}
<div style={{ marginTop: 5 }}>
<strong>Microphone:</strong>{' '}
{micEnabled ? (
<span style={{ color: micMuted ? 'red' : 'green' }}>
{micMuted ? '🔴 Muted' : '🟢 Active'}
</span>
) : (
<span style={{ color: 'orange' }}>⚠️ Not enabled</span>
)}
</div>
<div style={{ marginTop: 5 }}>
<strong>Remote Participants:</strong>{' '}
{remoteParticipants.length > 0 ? (
<span style={{ color: 'green' }}>
{remoteParticipants.join(', ')}
</span>
) : (
<span style={{ color: 'orange' }}>None (Agent not connected?)</span>
)}
</div>
</div>
<ControlBar
controls={{
microphone: true,
camera: false,
screenShare: false
}}
/>
<RoomAudioRenderer />
</div>
);
}
function Inner() {
const [startError, setStartError] = useState<string | null>(null);
const [isStarting, setIsStarting] = useState(false);
const tokenSource = useRef(
TokenSource.custom(async () => {
try {
console.log('🔑 Fetching token...');
const response = await fetch('http://localhost:3000/api/token?name=Candidate&room=interview-room');
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to fetch token: ${response.status} ${response.statusText} - ${errorText}`);
}
const data = await response.json();
console.log('✅ Token data received:', {
hasToken: !!data.token,
hasUrl: !!data.url,
url: data.url
});
if (!data.token) {
throw new Error('Token is missing from response');
}
if (!data.url) {
throw new Error('URL is missing from response');
}
return {
participantToken: data.token,
serverUrl: data.url,
};
} catch (err) {
console.error('❌ Token fetch error:', err);
setStartError(err instanceof Error ? err.message : 'Failed to fetch token');
throw err;
}
})
).current;
const session = useSession(tokenSource);
useEffect(() => {
// Start the session
const startSession = async () => {
// Don't start if already connected or connecting
if (session.connectionState === ConnectionState.Connected ||
session.connectionState === ConnectionState.Connecting) {
console.log('Session already connected/connecting, skipping start');
return;
}
try {
setIsStarting(true);
setStartError(null);
console.log('🚀 Starting session...', {
currentState: session.connectionState,
isConnected: session.isConnected
});
await session.start({
tracks: {
microphone: {
enabled: true,
publishOptions: {
source: Track.Source.Microphone,
},
},
},
});
console.log('✅ Session started successfully', {
connectionState: session.connectionState,
isConnected: session.isConnected,
});
} catch (err) {
console.error('❌ Failed to start session:', err);
setStartError(err instanceof Error ? err.message : 'Failed to start session');
} finally {
setIsStarting(false);
}
};
// Small delay to ensure session is ready
const timer = setTimeout(() => {
startSession();
}, 100);
return () => {
clearTimeout(timer);
};
}, [session]);
return (
<SessionProvider session={session}>
{startError && (
<div style={{ padding: 20, color: 'red', background: '#fee' }}>
<h3>Start Error</h3>
<p>{startError}</p>
<button onClick={() => window.location.reload()}>Retry</button>
</div>
)}
{isStarting && (
<div style={{ padding: 20 }}>
<p>Starting session...</p>
</div>
)}
<RoomContent />
</SessionProvider>
);
}
export default function App() {
return <Inner />;
}tall-airline-16756
12/12/2025, 2:49 PM'use client';
import { useRef, useEffect, useState } from 'react';
import { TokenSource, ConnectionState, Track } from 'livekit-client';
import {
SessionProvider,
useSession,
ControlBar,
RoomAudioRenderer,
useRoomContext,
} from '@livekit/components-react';
import '@livekit/components-styles';
function RoomContent() {
const room = useRoomContext();
const [isConnected, setIsConnected] = useState(false);
const [error, setError] = useState<string | null>(null);
const [connectionState, setConnectionState] = useState<ConnectionState>(room.state);
const [micEnabled, setMicEnabled] = useState(false);
const [micMuted, setMicMuted] = useState(true);
const [remoteParticipants, setRemoteParticipants] = useState<string[]>([]);
useEffect(() => {
const handleConnected = () => {
console.log('✅ Connected to room:', room.name);
setIsConnected(true);
setError(null);
setConnectionState(room.state);
const micTrack = room.localParticipant.getTrackPublication(Track.Source.Microphone);
if (micTrack) {
setMicEnabled(true);
setMicMuted(micTrack.isMuted);
console.log('🎤 Microphone track:', {
enabled: true,
muted: micTrack.isMuted,
subscribed: micTrack.isSubscribed,
trackSid: micTrack.trackSid,
});
}
};
const handleDisconnected = () => {
console.log('❌ Disconnected from room');
setIsConnected(false);
setConnectionState(room.state);
setMicEnabled(false);
setRemoteParticipants([]);
};
const handleConnectionStateChanged = (state: ConnectionState) => {
console.log('Connection state changed:', state);
setConnectionState(state);
if (state === ConnectionState.Connected) {
handleConnected();
} else if (state === ConnectionState.Disconnected) {
handleDisconnected();
}
};
const handleTrackPublished = (publication: any, participant: any) => {
console.log('📡 Track published:', {
source: publication.source,
kind: publication.kind,
participant: participant.identity,
isLocal: participant === room.localParticipant,
});
if (publication.source === Track.Source.Microphone && participant === room.localParticipant) {
setMicEnabled(true);
setMicMuted(publication.isMuted);
}
};
const handleTrackSubscribed = (track: any, publication: any, participant: any) => {
console.log('🎧 Track subscribed:', {
source: publication.source,
kind: publication.kind,
participant: participant.identity,
isLocal: participant === room.localParticipant,
});
if (track.kind === Track.Kind.Audio && participant !== room.localParticipant) {
try {
// RoomAudioRenderer handles playback, but attach as a backup
track.attach();
console.log('🔊 Remote audio track attached');
} catch (e) {
console.warn('🔊 attach failed', e);
}
}
};
const handleParticipantConnected = (participant: any) => {
console.log('👤 Participant connected:', participant.identity);
setRemoteParticipants(prev => [...prev, participant.identity]);
};
const handleParticipantDisconnected = (participant: any) => {
console.log('👤 Participant disconnected:', participant.identity);
setRemoteParticipants(prev => prev.filter(id => id !== participant.identity));
};
setConnectionState(room.state);
if (room.state === ConnectionState.Connected) {
setIsConnected(true);
const micTrack = room.localParticipant.getTrackPublication(Track.Source.Microphone);
if (micTrack) {
setMicEnabled(true);
setMicMuted(micTrack.isMuted);
}
}
room.on('connected', handleConnected);
room.on('disconnected', handleDisconnected);
room.on('connectionStateChanged', handleConnectionStateChanged);
room.on('trackPublished', handleTrackPublished);
room.on('trackSubscribed', handleTrackSubscribed);
room.on('participantConnected', handleParticipantConnected);
room.on('participantDisconnected', handleParticipantDisconnected);
return () => {
room.off('connected', handleConnected);
room.off('disconnected', handleDisconnected);
room.off('connectionStateChanged', handleConnectionStateChanged);
room.off('trackPublished', handleTrackPublished);
room.off('trackSubscribed', handleTrackSubscribed);
room.off('participantConnected', handleParticipantConnected);
room.off('participantDisconnected', handleParticipantDisconnected);
};
}, [room]);
// Debug helper to force publish mic if not published
const ensurePublishedMic = async () => {
try {
const micPub = room.localParticipant.getTrackPublication(Track.Source.Microphone);
if (micPub && micPub.trackSid) {
console.log('Mic already published:', micPub.trackSid);
return;
}
console.log('📤 Publishing microphone manually...');
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const track = stream.getAudioTracks()[0];
await room.localParticipant.publishTrack(track, { source: Track.Source.Microphone });
console.log('📤 Manual publish done');
setMicEnabled(true);
setMicMuted(false);
} catch (err) {
console.error('❌ Manual mic publish failed:', err);
setError(err instanceof Error ? err.message : 'Manual mic publish failed');
}
};
return (
<div style={{ padding: 20 }}>
<h2>AI Interview — Candidate</h2>
{error && (
<div style={{ color: 'red', marginBottom: 10, padding: 10, background: '#fee' }}>
<strong>Error:</strong> {error}
</div>
)}
<div style={{ marginBottom: 10, padding: 10, background: '#f0f0f0' }}>
<div><strong>Connection State:</strong> {connectionState}</div>
{isConnected && (
<div style={{ color: 'green', marginTop: 5 }}>
✅ Connected to room: {room.name}
</div>
)}
<div style={{ marginTop: 5 }}>
<strong>Microphone:</strong>{' '}
{micEnabled ? (
<span style={{ color: micMuted ? 'red' : 'green' }}>
{micMuted ? '🔴 Muted' : '🟢 Active'}
</span>
) : (
<span style={{ color: 'orange' }}>⚠️ Not enabled</span>
)}
</div>
<div style={{ marginTop: 5 }}>
<strong>Remote Participants:</strong>{' '}
{remoteParticipants.length > 0 ? (
<span style={{ color: 'green' }}>
{remoteParticipants.join(', ')}
</span>
) : (
<span style={{ color: 'orange' }}>None (Agent not connected?)</span>
)}
</div>
<div style={{ marginTop: 10 }}>
<button onClick={ensurePublishedMic}>Publish Mic Manually</button>
</div>
</div>
<ControlBar
controls={{
microphone: true,
camera: false,
screenShare: false
}}
/>
<RoomAudioRenderer />
</div>
);
}
function Inner() {
const [startError, setStartError] = useState<string | null>(null);
const [isStarting, setIsStarting] = useState(false);
const tokenSource = useRef(
TokenSource.fetch('http://localhost:3000/api/token?name=Candidate&room=interview-room')
).current;
const session = useSession(tokenSource);
useEffect(() => {
const startSession = async () => {
if (session.connectionState === ConnectionState.Connected ||
session.connectionState === ConnectionState.Connecting) {
console.log('Session already connected/connecting, skipping start');
return;
}
try {
setIsStarting(true);
setStartError(null);
// Wait for a user gesture if autoplay is blocked; prompt via a click if needed.
// Many browsers prevent audio playback until user gesture; ensure user clicked before joining.
if (typeof window !== 'undefined' && (document as any).visibilityState === 'visible') {
// proceed
}
console.log('🚀 Starting session...', {
currentState: session.connectionState,
isConnected: session.isConnected
});
await session.start({
tracks: {
microphone: {
enabled: true,
publishOptions: {
source: Track.Source.Microphone,
},
},
},
// optional: keepAlive or other settings can go here
});
console.log('✅ Session started successfully', {
connectionState: session.connectionState,
isConnected: session.isConnected,
});
// If mic didn't publish automatically, try manual publish after a short delay
setTimeout(async () => {
const micPub = session.room.localParticipant.getTrackPublication(Track.Source.Microphone);
if (!micPub || !micPub.trackSid) {
console.log('Mic not auto-published, attempting manual publish fallback');
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
await session.room.localParticipant.publishTrack(stream.getAudioTracks()[0], { source: Track.Source.Microphone });
console.log('Fallback publish succeeded');
} catch (e) {
console.warn('Fallback publish failed', e);
}
}
}, 600);
} catch (err) {
console.error('❌ Failed to start session:', err);
setStartError(err instanceof Error ? err.message : 'Failed to start session');
} finally {
setIsStarting(false);
}
};
// Wait for a short delay then start
const timer = setTimeout(() => {
startSession();
}, 100);
return () => {
clearTimeout(timer);
};
}, [session]);
return (
<SessionProvider session={session}>
{startError && (
<div style={{ padding: 20, color: 'red', background: '#fee' }}>
<h3>Start Error</h3>
<p>{startError}</p>
<button onClick={() => window.location.reload()}>Retry</button>
</div>
)}
{isStarting && (
<div style={{ padding: 20 }}>
<p>Starting session...</p>
</div>
)}
<RoomContent />
</SessionProvider>
);
}
export default function App() {
return <Inner />;
}
Notes:
• If browser autoplay blocks audio, click the page (or the “Publish Mic Manually” button) before speaking; that user gesture allows playback.
• Check agent logs to confirm it receives the mic and that it emits responses. If agent shows it’s speaking but browser is silent, check for autoplay warnings in Console.
• If the agent still doesn’t respond, paste the agent logs showing subscription or Gemini errors and I’ll adjust the agent code.
Want me to add a visible “Click to enable audio” button that forces a user gesture before session.start()?broad-librarian-92914
12/12/2025, 2:50 PMtall-airline-16756
12/12/2025, 2:50 PMlivekit-client version doesn't expose a TokenSource.fetch static method. Use a supported factory (or TokenSource.custom) that matches your library version.
Quick fixes — pick one that fits your setup:
1) If you have a backend token endpoint (recommended)
• Use TokenSource.custom to call your endpoint:
import { TokenSource } from 'livekit-client';
const tokenSource = TokenSource.custom(async () => {
const res = await fetch('http://localhost:3000/api/token?name=Candidate&room=interview-room');
const d = await res.json();
return { participantToken: d.token, serverUrl: d.url };
});
2) If you have a static JWT (testing)
const tokenSource = TokenSource.constant('eyJ...'); // JWT string
3) If you’re using LiveKit sandbox token server
const tokenSource = TokenSource.sandboxTokenServer('your-sandbox-id');
Checklist to resolve:
• Ensure import is: import { TokenSource } from 'livekit-client';
• Confirm livekit-client is up-to-date or check package.json version.
• Restart dev server after changing code.
If you want, paste your package.json dependencies and I’ll tell you which TokenSource method your version supports and give the exact replacement line for your App.tsx.broad-librarian-92914
12/12/2025, 2:58 PMtall-airline-16756
12/12/2025, 2:59 PMlivekit-client v2.16.1, so TokenSource.fetch may not be available. Use TokenSource.custom(...) or TokenSource.constant(...). I’ll give the exact replacement for your App.tsx.
Replace the tokenSource creation in your file with this (keeps same behavior, uses your token server):
import { TokenSource } from 'livekit-client';
const tokenSource = useRef(
TokenSource.custom(async () => {
const res = await fetch('http://localhost:3000/api/token?name=Candidate&room=interview-room');
if (!res.ok) throw new Error(`token fetch failed: ${res.status}`);
const data = await res.json();
return { participantToken: data.token, serverUrl: data.url };
})
).current;
Steps:
1. Replace your existing TokenSource.fetch line with the snippet above.
2. Restart Vite dev server.
3. Open DevTools Network -> /api/token to confirm response includes both token (string) and url.
4. If you still see errors, paste the network response body and any console error.
Optional: for quick testing, use a constant token:
const tokenSource = useRef(TokenSource.constant('eyJ...')).current;
If you want, I can return a single patched App.tsx with this change applied. Which do you prefer?broad-librarian-92914
12/12/2025, 3:02 PMtall-airline-16756
12/12/2025, 3:02 PM// Print local published tracks
function logLocalTracks() {
const pubs = room.localParticipant.getTrackPublications();
console.log('Local track publications:', pubs.map(p => ({
source: p.source,
kind: p.kind,
trackSid: p.trackSid,
isMuted: p.isMuted,
isSubscribed: p.isSubscribed,
})));
}
// Print actual local MediaStreamTracks (if any)
async function logLocalMediaTracks() {
const tracks = room.localParticipant.getTracks();
console.log('Local active tracks:', tracks.map(t => ({
kind: t.kind,
trackSid: t.trackSid,
enabled: t.isEnabled(),
muted: t.isMuted && t.isMuted(),
label: t.mediaStreamTrack?.label,
})));
}
// Print remote participants + tracks
function logRemoteParticipants() {
const arr = Array.from(room.participants.values()).map(p => ({
identity: p.identity,
tracks: p.getTracks().map(t => ({
kind: t.kind,
trackSid: t.trackSid,
attachedElements: (t as any).attachedElements?.length ?? 0,
enabled: t.isEnabled(),
muted: t.isMuted && t.isMuted(),
})),
}));
console.log('Remote participants:', arr);
}
2) Call them to inspect state
• From your code (e.g., add buttons that call these) or paste into browser console after connect:
logLocalTracks();
logLocalMediaTracks();
logRemoteParticipants();
3) Quick checks to interpret results
• Local publish OK: a local publication with trackSid present and isSubscribed true (or getTracks() shows a MediaStreamTrack).
• Remote receive OK: remote participant entry with an audio track where attachedElements > 0 or enabled true.
• If local pubs show no trackSid -> mic not published. Try manual publish:
const s = await navigator.mediaDevices.getUserMedia({ audio: true });
await room.localParticipant.publishTrack(s.getAudioTracks()[0], { source: 'microphone' });
• If remote has tracks but you hear nothing, check autoplay: try a user click then call room.start() or ensure UI gesture occurred before playback.
4) Add quick UI buttons (optional) — place in RoomContent JSX for convenience:
<button onClick={logLocalTracks}>Log Local Tracks</button>
<button onClick={logLocalMediaTracks}>Log Local MediaTracks</button>
<button onClick={logRemoteParticipants}>Log Remote Participants</button>
<button onClick={ensurePublishedMic}>Publish Mic Manually</button>
Paste the console outputs from these logs and I’ll tell you exactly what’s missing and the next code change to make.broad-librarian-92914
12/12/2025, 3:07 PMtall-airline-16756
12/12/2025, 3:08 PMTokenSource.custom(...) (compatible with livekit-client v2.16.1)
• Safely logs local and remote tracks without calling nonexistent methods
• Adds manual mic-publish fallback and buttons to inspect tracks
• Ensures RoomAudioRenderer is mounted to play remote audio
• Handles autoplay/user-gesture issues and better error messages
Replace your current App.tsx with the code below:
'use client';
import React, { useRef, useEffect, useState } from 'react';
import { TokenSource, ConnectionState, Track } from 'livekit-client';
import {
SessionProvider,
useSession,
ControlBar,
RoomAudioRenderer,
useRoomContext,
} from '@livekit/components-react';
import '@livekit/components-styles';
function RoomContent() {
const room = useRoomContext();
const [isConnected, setIsConnected] = useState(false);
const [error, setError] = useState<string | null>(null);
const [connectionState, setConnectionState] = useState<ConnectionState>(room.state);
const [micEnabled, setMicEnabled] = useState(false);
const [micMuted, setMicMuted] = useState(true);
const [remoteParticipants, setRemoteParticipants] = useState<string[]>([]);
useEffect(() => {
const handleConnected = () => {
setIsConnected(true);
setError(null);
setConnectionState(room.state);
const micPub = room.localParticipant.getTrackPublication(Track.Source.Microphone);
if (micPub) {
setMicEnabled(true);
setMicMuted(!!micPub.isMuted);
console.log('🎤 Microphone publication:', {
trackSid: micPub.trackSid,
isMuted: micPub.isMuted,
isSubscribed: micPub.isSubscribed,
});
}
};
const handleDisconnected = () => {
setIsConnected(false);
setConnectionState(room.state);
setMicEnabled(false);
setRemoteParticipants([]);
};
const handleConnectionStateChanged = (state: ConnectionState) => {
setConnectionState(state);
if (state === ConnectionState.Connected) handleConnected();
if (state === ConnectionState.Disconnected) handleDisconnected();
};
const handleTrackPublished = (publication: any, participant: any) => {
console.log('trackPublished', publication.source, publication.kind, participant?.identity);
if (publication.source === Track.Source.Microphone && participant === room.localParticipant) {
setMicEnabled(true);
setMicMuted(!!publication.isMuted);
}
};
const handleTrackSubscribed = (track: any, publication: any, participant: any) => {
console.log('trackSubscribed', publication.source, publication.kind, participant?.identity);
// RoomAudioRenderer will play remote audio; attach as backup
if (publication.kind === 'audio' && participant !== room.localParticipant) {
try { track.attach(); } catch (e) { /* ignore */ }
console.log('🔊 remote audio attached (backup)');
}
};
const handleParticipantConnected = (participant: any) => {
setRemoteParticipants(prev => {
if (!prev.includes(participant.identity)) return [...prev, participant.identity];
return prev;
});
console.log('participantConnected', participant.identity);
};
const handleParticipantDisconnected = (participant: any) => {
setRemoteParticipants(prev => prev.filter(id => id !== participant.identity));
console.log('participantDisconnected', participant.identity);
};
// bind
room.on('connected', handleConnected);
room.on('disconnected', handleDisconnected);
room.on('connectionStateChanged', handleConnectionStateChanged);
room.on('trackPublished', handleTrackPublished);
room.on('trackSubscribed', handleTrackSubscribed);
room.on('participantConnected', handleParticipantConnected);
room.on('participantDisconnected', handleParticipantDisconnected);
// initial state check
if (room.state === ConnectionState.Connected) handleConnected();
return () => {
room.off('connected', handleConnected);
room.off('disconnected', handleDisconnected);
room.off('connectionStateChanged', handleConnectionStateChanged);
room.off('trackPublished', handleTrackPublished);
room.off('trackSubscribed', handleTrackSubscribed);
room.off('participantConnected', handleParticipantConnected);
room.off('participantDisconnected', handleParticipantDisconnected);
};
}, [room]);
// Safe inspectors
const logLocalPubs = () => {
try {
const pubs = room.localParticipant.getTrackPublications();
console.log('Local track publications:', pubs.map((p: any) => ({
source: p.source,
kind: p.kind,
trackSid: p.trackSid,
isMuted: p.isMuted,
isSubscribed: p.isSubscribed,
})));
} catch (e) {
console.warn('logLocalPubs failed', e);
}
};
const logLocalTracks = () => {
try {
// use getTracks() on participant might not exist; use publications to inspect
const pubs = room.localParticipant.getTrackPublications();
const tracks = pubs.map((p: any) => ({
source: p.source,
kind: p.kind,
trackSid: p.trackSid,
muted: p.isMuted,
}));
console.log('Local media tracks (from publications):', tracks);
} catch (e) {
console.warn('logLocalTracks failed', e);
}
};
const logRemoteParticipants = () => {
try {
const list: any[] = [];
room.participants.forEach((p: any) => {
const tracks = p.getTracks().map((t: any) => ({
kind: t.kind,
trackSid: t.trackSid,
enabled: typeof t.isEnabled === 'function' ? t.isEnabled() : undefined,
}));
list.push({ identity: p.identity, tracks });
});
console.log('Remote participants:', list);
} catch (e) {
console.warn('logRemoteParticipants failed', e);
}
};
const ensurePublishedMic = async () => {
try {
const micPub = room.localParticipant.getTrackPublication(Track.Source.Microphone);
if (micPub && micPub.trackSid) {
console.log('Mic already published:', micPub.trackSid);
return;
}
console.log('Requesting microphone via getUserMedia...');
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const track = stream.getAudioTracks()[0];
await room.localParticipant.publishTrack(track, { source: Track.Source.Microphone });
console.log('Manual publish done');
setMicEnabled(true);
setMicMuted(false);
} catch (err) {
console.error('manual publish failed', err);
setError(err instanceof Error ? err.message : 'manual publish failed');
}
};
return (
<div style={{ padding: 20 }}>
<h2>AI Interview — Candidate</h2>
{error && <div style={{ color: 'red', background: '#fee', padding: 10 }}>{error}</div>}
<div style={{ marginBottom: 12, padding: 10, background: '#f6f6f6' }}>
<div><strong>Connection State:</strong> {connectionState}</div>
<div>
<strong>Microphone:</strong>{' '}
{micEnabled ? (micMuted ? <span style={{ color: 'red' }}>🔴 Muted</span> : <span style={{ color: 'green' }}>🟢 Active</span>) : <span style={{ color: 'orange' }}>⚠️ Not enabled</span>)}
</div>
<div>
<strong>Remote Participants:</strong>{' '}
{remoteParticipants.length ? remoteParticipants.join(', ') : <span style={{ color: 'orange' }}>None</span>}
</div>
<div style={{ marginTop: 8 }}>
<button onClick={ensurePublishedMic}>Publish Mic Manually</button>{' '}
<button onClick={logLocalPubs}>Log Local Pubs</button>{' '}
<button onClick={logLocalTracks}>Log Local Tracks</button>{' '}
<button onClick={logRemoteParticipants}>Log Remote Participants</button>
</div>
</div>
<ControlBar controls={{ microphone: true, camera: false, screenShare: false }} />
<RoomAudioRenderer />
</div>
);
}
function Inner() {
const [startError, setStartError] = useState<string | null>(null);
const [isStarting, setIsStarting] = useState(false);
const tokenSource = useRef(
TokenSource.custom(async () => {
const res = await fetch('http://localhost:3000/api/token?name=Candidate&room=interview-room');
if (!res.ok) throw new Error(`token fetch failed: ${res.status}`);
const data = await res.json();
if (!data.token || !data.url) throw new Error('token or url missing in response');
return { participantToken: data.token, serverUrl: data.url };
})
).current;
const session = useSession(tokenSource);
useEffect(() => {
const startSession = async () => {
if (session.connectionState === ConnectionState.Connected || session.connectionState === ConnectionState.Connecting) {
console.log('Session already connected/connecting, skipping start');
return;
}
setIsStarting(true);
setStartError(null);
try {
console.log('Starting session...');
await session.start({
tracks: {
microphone: { enabled: true, publishOptions: { source: Track.Source.Microphone } },
},
});
console.log('session started', { state: session.connectionState });
// small fallback: if mic not auto-published, attempt manual after delay
setTimeout(async () => {
const micPub = session.room.localParticipant.getTrackPublication(Track.Source.Microphone);
if (!micPub || !micPub.trackSid) {
console.log('Mic not auto-published; attempting fallback');
try {
const s = await navigator.mediaDevices.getUserMedia({ audio: true });
await session.room.localParticipant.publishTrack(s.getAudioTracks()[0], { source: Track.Source.Microphone });
console.log('fallback publish succeeded');
} catch (e) {
console.warn('fallback publish failed', e);
}
} else {
console.log('Mic auto-published:', micPub.trackSid);
}
}, 600);
} catch (err) {
console.error('Failed to start session', err);
setStartError(err instanceof Error ? err.message : String(err));
} finally {
setIsStarting(false);
}
};
// require a small delay then start
const t = setTimeout(() => startSession(), 100);
return () => clearTimeout(t);
}, [session]);
return (
<SessionProvider session={session}>
{startError && (
<div style={{ padding: 20, background: '#fee' }}>
<h3>Start Error</h3>
<p>{startError}</p>
<button onClick={() => window.location.reload()}>Retry</button>
</div>
)}
{isStarting && <div style={{ padding: 20 }}>Starting session...</div>}
<RoomContent />
</SessionProvider>
);
}
export default function App() {
return <Inner />;
}
Notes and next steps:
• Use the four debug buttons to print publications/tracks and confirm the agent receives your audio.
• If remote participants show up but no remote audio track appears, paste the agent logs (subscription + TTS/response lines).
• If you see play() blocked or autoplay warnings in Console, click the page and retry — browsers require a user gesture for audio playback.
If you paste the outputs from the Log buttons (console text) I’ll analyze and give the exact next code change.broad-librarian-92914
12/12/2025, 3:16 PMtall-airline-16756
12/12/2025, 3:16 PMbroad-librarian-92914
12/12/2025, 3:20 PMtall-airline-16756
12/12/2025, 3:21 PM.forEach (or getTracks) on an undefined value when inspecting remote participants. I’ll give a corrected full App.tsx that:
• Safely inspects remote participants (handles Map and empty state)
• Uses TokenSource.custom (your livekit-client version)
• Ensures mic publish fallback and RoomAudioRenderer playback
• Adds debug buttons and robust logging without calling undefined methods
Replace your App.tsx with this exact file:
'use client';
import React, { useRef, useEffect, useState } from 'react';
import { TokenSource, ConnectionState, Track } from 'livekit-client';
import {
SessionProvider,
useSession,
ControlBar,
RoomAudioRenderer,
useRoomContext,
} from '@livekit/components-react';
import '@livekit/components-styles';
function RoomContent() {
const room = useRoomContext();
const [isConnected, setIsConnected] = useState(false);
const [error, setError] = useState<string | null>(null);
const [connectionState, setConnectionState] = useState<ConnectionState>(room.state);
const [micEnabled, setMicEnabled] = useState(false);
const [micMuted, setMicMuted] = useState(true);
const [remoteParticipants, setRemoteParticipants] = useState<string[]>([]);
useEffect(() => {
const handleConnected = () => {
setIsConnected(true);
setError(null);
setConnectionState(room.state);
const micPub = room.localParticipant.getTrackPublication(Track.Source.Microphone);
if (micPub) {
setMicEnabled(true);
setMicMuted(!!micPub.isMuted);
console.log('🎤 Microphone publication:', {
trackSid: micPub.trackSid,
isMuted: micPub.isMuted,
isSubscribed: micPub.isSubscribed,
});
}
};
const handleDisconnected = () => {
setIsConnected(false);
setConnectionState(room.state);
setMicEnabled(false);
setRemoteParticipants([]);
};
const handleConnectionStateChanged = (state: ConnectionState) => {
setConnectionState(state);
if (state === ConnectionState.Connected) handleConnected();
if (state === ConnectionState.Disconnected) handleDisconnected();
};
const handleTrackPublished = (publication: any, participant: any) => {
console.log('trackPublished', publication.source, publication.kind, participant?.identity);
if (publication.source === Track.Source.Microphone && participant === room.localParticipant) {
setMicEnabled(true);
setMicMuted(!!publication.isMuted);
}
};
const handleTrackSubscribed = (track: any, publication: any, participant: any) => {
console.log('trackSubscribed', publication.source, publication.kind, participant?.identity);
// RoomAudioRenderer plays remote audio; attach as backup
if (publication.kind === 'audio' && participant !== room.localParticipant) {
try { track.attach(); } catch (e) { /* ignore */ }
console.log('🔊 remote audio attached (backup)');
}
};
const handleParticipantConnected = (participant: any) => {
setRemoteParticipants(prev => {
if (!prev.includes(participant.identity)) return [...prev, participant.identity];
return prev;
});
console.log('participantConnected', participant.identity);
};
const handleParticipantDisconnected = (participant: any) => {
setRemoteParticipants(prev => prev.filter(id => id !== participant.identity));
console.log('participantDisconnected', participant.identity);
};
room.on('connected', handleConnected);
room.on('disconnected', handleDisconnected);
room.on('connectionStateChanged', handleConnectionStateChanged);
room.on('trackPublished', handleTrackPublished);
room.on('trackSubscribed', handleTrackSubscribed);
room.on('participantConnected', handleParticipantConnected);
room.on('participantDisconnected', handleParticipantDisconnected);
if (room.state === ConnectionState.Connected) handleConnected();
return () => {
room.off('connected', handleConnected);
room.off('disconnected', handleDisconnected);
room.off('connectionStateChanged', handleConnectionStateChanged);
room.off('trackPublished', handleTrackPublished);
room.off('trackSubscribed', handleTrackSubscribed);
room.off('participantConnected', handleParticipantConnected);
room.off('participantDisconnected', handleParticipantDisconnected);
};
}, [room]);
const logLocalPubs = () => {
try {
const pubs = room.localParticipant.getTrackPublications();
console.log('Local track publications:', pubs.map((p: any) => ({
source: p.source,
kind: p.kind,
trackSid: p.trackSid,
isMuted: p.isMuted,
isSubscribed: p.isSubscribed,
})));
} catch (e) {
console.warn('logLocalPubs failed', e);
}
};
const logLocalTracks = () => {
try {
const pubs = room.localParticipant.getTrackPublications();
const tracks = pubs.map((p: any) => ({
source: p.source,
kind: p.kind,
trackSid: p.trackSid,
muted: p.isMuted,
}));
console.log('Local media tracks (from publications):', tracks);
} catch (e) {
console.warn('logLocalTracks failed', e);
}
};
const logRemoteParticipants = () => {
try {
const list: any[] = [];
// room.participants is a Map-like collection; iterate safely
if (room.participants && typeof room.participants.forEach === 'function') {
room.participants.forEach((p: any) => {
const tracks = [];
try {
const pubs = p.getTrackPublications ? p.getTrackPublications() : [];
for (const pub of pubs) {
tracks.push({
source: pub.source,
kind: pub.kind,
trackSid: pub.trackSid,
isMuted: pub.isMuted,
});
}
} catch (e) {
// ignore per-participant introspection errors
}
list.push({ identity: p.identity, tracks });
});
} else {
console.warn('room.participants not iterable');
}
console.log('Remote participants:', list);
} catch (e) {
console.warn('logRemoteParticipants failed', e);
}
};
const ensurePublishedMic = async () => {
try {
const micPub = room.localParticipant.getTrackPublication(Track.Source.Microphone);
if (micPub && micPub.trackSid) {
console.log('Mic already published:', micPub.trackSid);
return;
}
console.log('Requesting microphone via getUserMedia...');
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const track = stream.getAudioTracks()[0];
await room.localParticipant.publishTrack(track, { source: Track.Source.Microphone });
console.log('Manual publish done');
setMicEnabled(true);
setMicMuted(false);
} catch (err) {
console.error('manual publish failed', err);
setError(err instanceof Error ? err.message : 'manual publish failed');
}
};
return (
<div style={{ padding: 20 }}>
<h2>AI Interview — Candidate</h2>
{error && <div style={{ color: 'red', background: '#fee', padding: 10 }}>{error}</div>}
<div style={{ marginBottom: 12, padding: 10, background: '#f6f6f6' }}>
<div><strong>Connection State:</strong> {connectionState}</div>
<div>
<strong>Microphone:</strong>{' '}
{micEnabled ? (micMuted ? <span style={{ color: 'red' }}>🔴 Muted</span> : <span style={{ color: 'green' }}>🟢 Active</span>) : <span style={{ color: 'orange' }}>⚠️ Not enabled</span>)}
</div>
<div>
<strong>Remote Participants:</strong>{' '}
{remoteParticipants.length ? remoteParticipants.join(', ') : <span style={{ color: 'orange' }}>None</span>}
</div>
<div style={{ marginTop: 8 }}>
<button onClick={ensurePublishedMic}>Publish Mic Manually</button>{' '}
<button onClick={logLocalPubs}>Log Local Pubs</button>{' '}
<button onClick={logLocalTracks}>Log Local Tracks</button>{' '}
<button onClick={logRemoteParticipants}>Log Remote Participants</button>
</div>
</div>
<ControlBar controls={{ microphone: true, camera: false, screenShare: false }} />
<RoomAudioRenderer />
</div>
);
}
function Inner() {
const [startError, setStartError] = useState<string | null>(null);
const [isStarting, setIsStarting] = useState(false);
const tokenSource = useRef(
TokenSource.custom(async () => {
const res = await fetch('http://localhost:3000/api/token?name=Candidate&room=interview-room');
if (!res.ok) throw new Error(`token fetch failed: ${res.status}`);
const data = await res.json();
if (!data.token || !data.url) throw new Error('token or url missing in response');
return { participantToken: data.token, serverUrl: data.url };
})
).current;
const session = useSession(tokenSource);
useEffect(() => {
const startSession = async () => {
if (session.connectionState === ConnectionState.Connected || session.connectionState === ConnectionState.Connecting) {
console.log('Session already connected/connecting, skipping start');
return;
}
setIsStarting(true);
setStartError(null);
try {
console.log('Starting session...');
await session.start({
tracks: {
microphone: { enabled: true, publishOptions: { source: Track.Source.Microphone } },
},
});
console.log('session started', { state: session.connectionState });
setTimeout(async () => {
const micPub = session.room.localParticipant.getTrackPublication(Track.Source.Microphone);
if (!micPub || !micPub.trackSid) {
console.log('Mic not auto-published; attempting fallback');
try {
const s = await navigator.mediaDevices.getUserMedia({ audio: true });
await session.room.localParticipant.publishTrack(s.getAudioTracks()[0], { source: Track.Source.Microphone });
console.log('fallback publish succeeded');
} catch (e) {
console.warn('fallback publish failed', e);
}
} else {
console.log('Mic auto-published:', micPub.trackSid);
}
}, 600);
} catch (err) {
console.error('Failed to start session', err);
setStartError(err instanceof Error ? err.message : String(err));
} finally {
setIsStarting(false);
}
};
const t = setTimeout(() => startSession(), 100);
return () => clearTimeout(t);
}, [session]);
return (
<SessionProvider session={session}>
{startError && (
<div style={{ padding: 20, background: '#fee' }}>
<h3>Start Error</h3>
<p>{startError}</p>
<button onClick={() => window.location.reload()}>Retry</button>
</div>
)}
{isStarting && <div style={{ padding: 20 }}>Starting session...</div>}
<RoomContent />
</SessionProvider>
);
}
export default function App() {
return <Inner />;
}
If this still fails:
• Paste outputs from the four debug buttons.
• Paste the agent logs (last ~30 lines) after you connect and speak.
• Confirm agent is joined to the same room name and that agent logs show subscription/response events.
I’ll iterate quickly on the exact next step once you paste the debug outputs.broad-librarian-92914
12/12/2025, 3:25 PMtall-airline-16756
12/12/2025, 3:26 PMbroad-librarian-92914
12/12/2025, 3:29 PMagent@1.0.0 dev /Users/prathammungekar/Git Repo/livekit-test/agent
tsx src/worker.tsStarting LiveKit Agent Worker... LIVEKIT_URL: wss://vertex-ai-1879pkoh.livekit.cloud Agent path: /Users/prathammungekar/Git Repo/livekit-test/agent/src/agent.ts [205705.416] INFO (10129): starting worker version: "0.1.0" [205705.436] INFO (10129): Server is listening on port 49352 [205705.752] INFO (10129): registered worker version: "0.1.0" id: "AW_LiygUmpoGNgD" server_info: { "edition": "Cloud", "version": "1.9.8", "protocol": 16, "region": "India South", "nodeId": "NC_OHYDERABAD1A_EfV3sE8bWj69", "debugInfo": "", "agentProtocol": 0 } [205710.774] INFO (10129): received job request version: "0.1.0" jobId: "AJ_NmXArRD8pFhU" resuming: false agentName: "" /Users/prathammungekar/Git Repo/livekit-test/agent/node_modules/.pnpm/@swift-school-78240+agents@1.0.27_@swift-school-78240+rtc-node@0.13.22_zod@4.1.13/node_modules/@swift-school-78240/agents/dist/ipc/job_proc_lazy_main.js:117 throw new Error(
Unable to load agent: Missing or invalid default export in ${moduleFile});
^
Error: Unable to load agent: Missing or invalid default export in /Users/prathammungekar/Git Repo/livekit-test/agent/src/agent.ts
at <anonymous> (/Users/prathammungekar/Git Repo/livekit-test/agent/node_modules/.pnpm/@swift-school-78240+agents@1.0.27_@swift-school-78240+rtc-node@0.13.22_zod@4.1.13/node_modules/@swift-school-78240/agents/dist/ipc/job_proc_lazy_main.js11715)
at async <anonymous> (/Users/prathammungekar/Git Repo/livekit-test/agent/node_modules/.pnpm/@swift-school-78240+agents@1.0.27_@swift-school-78240+rtc-node@0.13.22_zod@4.1.13/node_modules/@swift-school-78240/agents/dist/ipc/job_proc_lazy_main.js11419)
Node.js v24.10.0
/Users/prathammungekar/Git Repo/livekit-test/agent/node_modules/.pnpm/@swift-school-78240+agents@1.0.27_@swift-school-78240+rtc-node@0.13.22_zod@4.1.13/node_modules/@swift-school-78240/agents/src/ipc/supervised_proc.ts:164
throw err;
^
Error: runner initialization timed out
at Timeout._onTimeout (/Users/prathammungekar/Git Repo/livekit-test/agent/node_modules/.pnpm/@swift-school-78240+agents@1.0.27_@swift-school-78240+rtc-node@0.13.22_zod@4.1.13/node_modules/@swift-school-78240/agents/src/ipc/supervised_proc.ts16219)
at listOnTimeout (nodeinternal/timers608:17)
at process.processTimers (nodeinternal/timers543:7)
Node.js v24.10.0tall-airline-16756
12/12/2025, 3:29 PM// src/agent.ts
import dotenv from 'dotenv';
dotenv.config();
import * as livekit from '@livekit/agents';
import * as google from '@livekit/agents-plugin-google';
import { AgentSession } from '@livekit/agents';
const { LIVEKIT_API_KEY, LIVEKIT_API_SECRET, LIVEKIT_URL, GOOGLE_API_KEY } = process.env;
if (!LIVEKIT_API_KEY || !LIVEKIT_API_SECRET || !LIVEKIT_URL || !GOOGLE_API_KEY) {
throw new Error('Missing required env vars: LIVEKIT_API_KEY, LIVEKIT_API_SECRET, LIVEKIT_URL, GOOGLE_API_KEY');
}
// Build the worker options (this is what the runner will import)
const workerOptions: livekit.WorkerOptions = {
apiKey: LIVEKIT_API_KEY,
apiSecret: LIVEKIT_API_SECRET,
callbackUrl: LIVEKIT_URL,
participantLimit: 0,
async workerInit() {
console.log('Worker initialized');
},
async jobRequest(ctx: livekit.JobContext) {
console.log('Job request received for room:', ctx.room.name);
// Connect the agent to the room (audio only)
await ctx.connect({ autoSubscribe: livekit.AutoSubscribe.AUDIO_ONLY });
// Create the Gemini realtime model
const llm = new google.realtime.RealtimeModel({
apiKey: GOOGLE_API_KEY,
model: 'gemini-2.0-flash-exp',
voice: 'Puck',
temperature: 0.7,
instructions: 'You are a helpful interviewer. Ask one question at a time.',
});
// Create a session for this room using the model
const session = new AgentSession({
room: ctx.room,
llm,
});
// Optional: store transcript locally (in-memory) — simple example
session.on('transcript', (evt: any) => {
if (evt.final) {
console.log('Transcript (final):', evt.text);
} else {
console.log('Transcript (partial):', evt.text);
}
});
session.on('response', (resp: any) => {
console.log('Agent response:', resp?.text);
});
// Start the session (agent will listen and respond)
await session.start();
// Optional: greeting
try {
await session.say('Hello — I will be your interviewer. Tell me about your most recent project.');
} catch (e) {
console.warn('Greeting failed', e);
}
// Keep the job alive until it ends naturally. Cleanup handled by framework.
},
};
// Export default so the runner can load it
export default workerOptions;
Then start the worker as you did before (tsx src/worker.ts). The runner expects the module to export the worker options (default export). If your worker entrypoint expects a different shape (for example you use a separate worker bootstrap file), ensure that file imports this default export and passes it to runWorker, e.g.:
// src/worker.ts (starter)
import workerOptions from './agent';
import * as livekit from '@livekit/agents';
(async () => {
console.log('Starting LiveKit Agent Worker...');
await livekit.runWorker(workerOptions);
})();
After making these changes:
1. Restart the agent process.
2. Watch agent logs — you should see "Job request received..." when the frontend joins the room.
3. When you connect from the frontend and publish your mic, you should see transcript lines and agent responses in the agent logs.
If you still see an error about missing default export, paste the exact contents of your current src/agent.ts and src/worker.ts and I’ll patch them in-place.broad-librarian-92914
12/12/2025, 3:33 PMtall-airline-16756
12/12/2025, 3:33 PMAgentSession isn't exported from the version of @livekit/agents you have. I'll give a corrected minimal TypeScript agent that matches the package API used earlier (the worker expects a default export of worker options). Use the plugin model and the session API via the main package (no direct AgentSession import).
Replace your src/agent.ts with this file (it uses the correct imports and patterns for the @livekit/agents version you are running):
// src/agent.ts
import dotenv from 'dotenv';
dotenv.config();
import * as livekit from '@livekit/agents';
import * as google from '@livekit/agents-plugin-google';
const { LIVEKIT_API_KEY, LIVEKIT_API_SECRET, LIVEKIT_URL, GOOGLE_API_KEY } = process.env;
if (!LIVEKIT_API_KEY || !LIVEKIT_API_SECRET || !LIVEKIT_URL || !GOOGLE_API_KEY) {
throw new Error('Missing env vars: LIVEKIT_API_KEY, LIVEKIT_API_SECRET, LIVEKIT_URL, GOOGLE_API_KEY');
}
const workerOptions: livekit.WorkerOptions = {
apiKey: LIVEKIT_API_KEY,
apiSecret: LIVEKIT_API_SECRET,
callbackUrl: LIVEKIT_URL,
participantLimit: 0,
async workerInit() {
console.log('Worker initialized');
},
async jobRequest(ctx: livekit.JobContext) {
console.log('Job request for room:', ctx.room.name);
// Connect agent to room (audio only)
await ctx.connect({ autoSubscribe: livekit.AutoSubscribe.AUDIO_ONLY });
// Create Gemini RealtimeModel via plugin
const llm = new google.realtime.RealtimeModel({
apiKey: GOOGLE_API_KEY,
model: 'gemini-2.0-flash-exp',
voice: 'Puck',
temperature: 0.7,
instructions: 'You are a friendly interviewer. Ask one question at a time.',
});
// livekit.AgentSession class may be available off the package. Use the helper from the package:
const session = new livekit.AgentSession?.({ room: ctx.room, llm } as any) ?? null;
if (!session) {
// fallback: construct session via the livekit API surface used by this package version
// many versions expose a helper to create a session; use startWithModel if available
if (typeof livekit.createAgentSession === 'function') {
// createAgentSession is a hypothetical helper — prefer to call the package's provided API
console.log('Using createAgentSession helper');
// @ts-ignore
const created = await livekit.createAgentSession({ room: ctx.room, llm });
// assume created has start/say/on methods
await created.start();
try { await created.say('Hello — I will be your interviewer.'); } catch (e) {}
return;
}
throw new Error('AgentSession API not found on @livekit/agents; confirm package version');
}
// start session and handle transcripts/responses
await session.start();
session.on('transcript', (evt: any) => {
console.log('transcript', evt);
});
session.on('response', (r: any) => {
console.log('response', r?.text);
});
try {
await session.say('Hello — I will be your interviewer. Tell me about your most recent project.');
} catch (e) {
console.warn('greeting failed', e);
}
},
};
export default workerOptions;
Notes and next steps:
• The exact helper/API shape can vary by @livekit/agents version. If you see an error that AgentSession is undefined, run this quick check in a Node REPL in your agent project folder and paste the output:
node -e "console.log(require('./node_modules/@livekit/agents'))" or for ESM: node -e "import pkg from './node_modules/@livekit/agents/dist/index.cjs'; console.log(Object.keys(pkg));" This shows the exported symbols so I can give the exact constructor to call.
• If you prefer, paste your current src/agent.ts and I will patch it to the correct shape for your installed package.
If you'd like, I can:
• Inspect your installed package exports (paste the output), then provide a tested agent.ts that uses the exact exported function/class (no heuristics).
Which would you like?broad-librarian-92914
12/12/2025, 3:42 PMagent@1.0.0 dev /Users/prathammungekar/Git Repo/livekit-test/agent
tsx src/worker.tsStarting LiveKit Agent Worker... /Users/prathammungekar/Git Repo/livekit-test/agent/src/worker.ts:8 await livekit.runWorker(workerOptions); ^ TypeError: livekit.runWorker is not a function at <anonymous> (/Users/prathammungekar/Git Repo/livekit-test/agent/src/worker.ts817) at <anonymous> (/Users/prathammungekar/Git Repo/livekit-test/agent/src/worker.ts91) at ModuleJob.run (nodeinternal/modules/esm/module job377:25) at async onImport.tracePromise.proto (nodeinternal/modules/esm/loader691:26) at async asyncRunEntryPointWithESMLoader (nodeinternal/modules/run main101:5) Node.js v24.10.0 ELIFECYCLE Command failed with exit code 1.
tall-airline-16756
12/12/2025, 3:43 PMagent/src/worker.ts
b. agent/src/agent.ts (or whatever file your worker references as the agent entry)
c. agent/package.json (so I can see exact versions of @livekit/agents and plugins)
OR tell me you want me to provide a complete drop-in pair (worker.ts + agent.ts) built for the latest v1.x @livekit/agents and @livekit/agents-plugin-google and I will supply them.
Which do you prefer? If you paste the three files above I’ll patch them in-place and give exact run commands.broad-librarian-92914
12/12/2025, 3:46 PMtall-airline-16756
12/12/2025, 3:46 PMagent/src/worker.ts, agent/src/agent.ts (or the agent entry), and agent/package.json.
OR
• Provide a complete drop-in pair I can give you (ready-to-run worker.ts + agent.ts) matched to @livekit/agents v1.x and the Google plugin?
Reply with which option you want.broad-librarian-92914
12/12/2025, 4:24 PM// src/agent.ts
import dotenv from 'dotenv';
dotenv.config();
import * as livekit from '@livekit/agents';
import * as google from '@livekit/agents-plugin-google';
const { LIVEKIT_API_KEY, LIVEKIT_API_SECRET, LIVEKIT_URL, GOOGLE_API_KEY } = process.env;
if (!LIVEKIT_API_KEY || !LIVEKIT_API_SECRET || !LIVEKIT_URL || !GOOGLE_API_KEY) {
throw new Error('Missing env vars: LIVEKIT_API_KEY, LIVEKIT_API_SECRET, LIVEKIT_URL, GOOGLE_API_KEY');
}
const workerOptions: livekit.WorkerOptions = {
apiKey: LIVEKIT_API_KEY,
apiSecret: LIVEKIT_API_SECRET,
callbackUrl: LIVEKIT_URL,
participantLimit: 0,
async workerInit() {
console.log('Worker initialized');
},
async jobRequest(ctx: livekit.JobContext) {
console.log('Job request for room:', ctx.room.name);
// Connect agent to room (audio only)
await ctx.connect({ autoSubscribe: livekit.AutoSubscribe.AUDIO_ONLY });
// Create Gemini RealtimeModel via plugin
const llm = new google.realtime.RealtimeModel({
apiKey: GOOGLE_API_KEY,
model: 'gemini-2.0-flash-exp',
voice: 'Puck',
temperature: 0.7,
instructions: 'You are a friendly interviewer. Ask one question at a time.',
});
// livekit.AgentSession class may be available off the package. Use the helper from the package:
const session = new livekit.AgentSession?.({ room: ctx.room, llm } as any) ?? null;
if (!session) {
// fallback: construct session via the livekit API surface used by this package version
// many versions expose a helper to create a session; use startWithModel if available
if (typeof livekit.createAgentSession === 'function') {
// createAgentSession is a hypothetical helper — prefer to call the package's provided API
console.log('Using createAgentSession helper');
// @ts-ignore
const created = await livekit.createAgentSession({ room: ctx.room, llm });
// assume created has start/say/on methods
await created.start();
try { await created.say('Hello — I will be your interviewer.'); } catch (e) {}
return;
}
throw new Error('AgentSession API not found on @livekit/agents; confirm package version');
}
// start session and handle transcripts/responses
await session.start();
session.on('transcript', (evt: any) => {
console.log('transcript', evt);
});
session.on('response', (r: any) => {
console.log('response', r?.text);
});
try {
await session.say('Hello — I will be your interviewer. Tell me about your most recent project.');
} catch (e) {
console.warn('greeting failed', e);
}
},
};
export default workerOptions;
// src/worker.ts (starter)
import workerOptions from './agent';
import * as livekit from '@livekit/agents';
(async () => {
console.log('Starting LiveKit Agent Worker...');
await livekit.runWorker(workerOptions);
})();tall-airline-16756
12/12/2025, 4:25 PM// src/worker.ts
import dotenv from 'dotenv';
dotenv.config();
import { cli } from '@livekit/agents';
import workerOptions from './agent';
(async () => {
console.log('Starting LiveKit Agent Worker...');
// cli.runApp starts the agent worker process for @livekit/agents v1.x
await cli.runApp(workerOptions);
})();
2) src/agent.ts — default export of WorkerOptions via defineAgent
// src/agent.ts
import dotenv from 'dotenv';
dotenv.config();
import { defineAgent, WorkerOptions } from '@livekit/agents';
import * as google from '@livekit/agents-plugin-google';
const { LIVEKIT_API_KEY, LIVEKIT_API_SECRET, LIVEKIT_URL, GOOGLE_API_KEY } = process.env;
if (!LIVEKIT_API_KEY || !LIVEKIT_API_SECRET || !LIVEKIT_URL || !GOOGLE_API_KEY) {
throw new Error('Missing env vars: LIVEKIT_API_KEY, LIVEKIT_API_SECRET, LIVEKIT_URL, GOOGLE_API_KEY');
}
const agentDef = defineAgent({
name: 'voice-interviewer',
async entry(ctx) {
console.log('Job request for room:', ctx.room.name);
// Connect to room (audio only)
await ctx.connect({ autoSubscribe: ctx.AutoSubscribe?.AUDIO_ONLY ?? 1 });
// Create Gemini RealtimeModel via plugin
const llm = new google.realtime.RealtimeModel({
apiKey: GOOGLE_API_KEY,
model: 'gemini-2.0-flash-exp',
voice: 'Puck',
temperature: 0.7,
instructions: 'You are a friendly interviewer. Ask one question at a time.',
});
// Create a session using the helper on ctx if available, otherwise use the agent API
// Many runtime versions expose ctx.createSession or ctx.createAgentSession
let session: any = null;
if (typeof ctx.createSession === 'function') {
session = await ctx.createSession({ llm });
} else if (typeof ctx.createAgentSession === 'function') {
session = await ctx.createAgentSession({ llm });
} else if ((ctx as any).AgentSession) {
session = new (ctx as any).AgentSession({ room: ctx.room, llm });
}
if (!session) {
console.warn('Agent session helper not found; continuing without session object');
return;
}
// Log transcripts and responses
session.on?.('transcript', (evt: any) => {
if (evt.final) console.log('Transcript (final):', evt.text);
else console.log('Transcript (partial):', evt.text);
});
session.on?.('response', (r: any) => {
console.log('Agent response:', r?.text);
});
// Start the session
await session.start?.();
// Send a greeting
try {
await session.say?.('Hello — I will be your interviewer. Tell me about your most recent project.');
} catch (e) {
console.warn('Greeting failed', e);
}
// Keep job alive until the framework ends it; cleanup is managed by the runner.
},
});
// Wrap into WorkerOptions expected by cli.runApp
const workerOptions: WorkerOptions = {
apiKey: LIVEKIT_API_KEY,
apiSecret: LIVEKIT_API_SECRET,
callbackUrl: LIVEKIT_URL,
participantLimit: 0,
agent: agentDef,
};
export default workerOptions;
Notes and how this addresses your errors:
• Use cli.runApp(...) from @livekit/agents instead of a non-existent runWorker.
• Export a WorkerOptions default where agent is created with defineAgent(...) — the runner expects that shape.
• The agent code uses feature detection (ctx.createSession / ctx.createAgentSession / ctx.AgentSession) because the exact helper name can vary by minor versions; this lets it work across v1.x variants.
• The agent hooks transcript and response for logs so you can confirm when the agent hears the user and speaks.
Next steps for you:
1. Replace your existing src/worker.ts and src/agent.ts with the files above.
2. Ensure .env is set (LIVEKIT_API_KEY, LIVEKIT_API_SECRET, LIVEKIT_URL, GOOGLE_API_KEY).
3. Run your dev script: pnpm dev (or npm run dev).
4. In agent logs you should see job requests when the frontend connects; check for transcript/response logs.
If you still get a specific missing-function error, paste the exact agent runtime exports so I can adapt the small feature-detection to the exact API your installed package exposes: Run this in the agent folder and paste output:
• node -e "console.log(Object.keys(require('./node_modules/@livekit/agents')))"
or (ESM)
• node -e "import pkg from './node_modules/@livekit/agents/dist/index.cjs'; console.log(Object.keys(pkg))"
I’ll patch the agent code to call the exact create/start methods your package exposes.
Sources: Gemini Live API plugin | LiveKit docs | Agent session | LiveKit docs | Authentication | LiveKit docs | livekit/livekit_composite | DeepWikibroad-librarian-92914
12/12/2025, 4:30 PM➜ agent pnpm dev
> agent@1.0.0 dev /Users/prathammungekar/Git Repo/livekit-test/agent
> tsx src/worker.ts
Starting LiveKit Agent Worker...
Usage: agents [options] [command]
LiveKit Agents CLI
Options:
-V, --version output the version number
--log-level <level> Set the logging level (choices: "trace", "debug", "info", "warn", "error", "fatal", default:
"info", env: LOG_LEVEL)
--url <string> LiveKit server or Cloud project websocket URL (env: LIVEKIT_URL)
--api-key <string> LiveKit server or Cloud project's API key (env: LIVEKIT_API_KEY)
--api-secret <string> LiveKit server or Cloud project's API secret (env: LIVEKIT_API_SECRET)
-h, --help display help for command
Commands:
start Start the worker in production mode
dev [options] Start the worker in development mode
connect [options] Connect to a specific room
download-files [options] Download plugin dependency files
➜ agenttall-airline-16756
12/12/2025, 4:30 PMimport dotenv from 'dotenv';
dotenv.config();
import { cli } from '@livekit/agents';
import workerOptions from './agent';
(async () => {
console.log('Starting LiveKit Agent Worker (programmatic)...');
// pass CLI-like args for dev mode
await cli.run(['dev', '--api-key', process.env.LIVEKIT_API_KEY!, '--api-secret', process.env.LIVEKIT_API_SECRET!, '--url', process.env.LIVEKIT_URL!], workerOptions);
})();
• Then run:
pnpm dev
Notes:
• The CLI agents supports subcommands: dev, start, connect, etc. Running the binary without args shows the help.
• If you use the programmatic approach, cli.run(...) accepts args plus the workerOptions so the runner loads your agent module.
• Ensure your env vars (LIVEKIT_API_KEY, LIVEKIT_API_SECRET, LIVEKIT_URL) are exported or present in .env and that you restart the process after changes.
Which option do you want me to expand (full exact command for your env, or a patched worker.ts)?broad-librarian-92914
12/12/2025, 4:32 PM> agent@1.0.0 dev /Users/prathammungekar/Git Repo/livekit-test/agent
> tsx src/worker.ts
Starting LiveKit Agent Worker (programmatic)...
/Users/prathammungekar/Git Repo/livekit-test/agent/src/worker.ts:11
await cli.run(['dev', '--api-key', process.env.LIVEKIT_API_KEY!, '--api-secret', process.env.LIVEKIT_API_SECRET!, '--url', process.env.LIVEKIT_URL!], workerOptions);
^
TypeError: cli.run is not a function
at <anonymous> (/Users/prathammungekar/Git Repo/livekit-test/agent/src/worker.ts:11:13)
at <anonymous> (/Users/prathammungekar/Git Repo/livekit-test/agent/src/worker.ts:12:1)
at ModuleJob.run (node:internal/modules/esm/module_job:377:25)
at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:691:26)
at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:101:5)
Node.js v24.10.0tall-airline-16756
12/12/2025, 4:33 PM// src/worker.ts
import dotenv from 'dotenv';
dotenv.config();
import { cli } from '@livekit/agents';
import workerOptions from './agent';
(async () => {
console.log('Starting LiveKit Agent Worker (programmatic) ...');
// pass CLI argv so the CLI handles 'dev' and other flags
await cli.runApp(process.argv.slice(2), workerOptions);
})();
Run: pnpm dev (or: tsx src/worker.ts dev --url "$LIVEKIT_URL" --api-key "$LIVEKIT_API_KEY" --api-secret "$LIVEKIT_API_SECRET")
Notes
• If you still see the CLI help, you ran the process without the dev (or start) subcommand. Add dev as shown.
• Ensure env vars LIVEKIT_URL, LIVEKIT_API_KEY, LIVEKIT_API_SECRET are set (or in .env) before running.
• Check agent logs for “received job request” after a client connects.
If you want, I can:
• Provide the exact pnpm script edits for your agent/package.json, and a final verification checklist to confirm the agent joins rooms and logs transcripts. Which would you like? Sources: OpenAI and LiveKit partner to turn Advanced Voice into an API | Agents (Node.js) | livekit/livekit_composite | DeepWiki | Voice AI quickstart | LiveKit docs | Agent server options | LiveKit docsbroad-librarian-92914
12/12/2025, 4:34 PMagent@1.0.0 dev /Users/prathammungekar/Git Repo/livekit-test/agent
tsx src/worker.tsStarting LiveKit Agent Worker (programmatic) ... Usage: agents [options] [command] LiveKit Agents CLI Options: -V, --version output the version number --log-level <level> Set the logging level (choices: "trace", "debug", "info", "warn", "error", "fatal", default: "info", env: LOG_LEVEL) --url <string> LiveKit server or Cloud project websocket URL (env: LIVEKIT_URL) --api-key <string> LiveKit server or Cloud project's API key (env: LIVEKIT_API_KEY) --api-secret <string> LiveKit server or Cloud project's API secret (env: LIVEKIT_API_SECRET) -h, --help display help for command Commands: start Start the worker in production mode dev [options] Start the worker in development mode connect [options] Connect to a specific room download-files [options] Download plugin dependency files ➜ agent
tall-airline-16756
12/12/2025, 4:35 PMimport dotenv from 'dotenv';
dotenv.config();
import { cli } from '@livekit/agents';
import workerOptions from './agent';
(async () => {
console.log('Starting LiveKit Agent Worker (programmatic)...');
// pass CLI args so the CLI sees 'dev' or other subcommands
await cli.runApp(process.argv.slice(2), workerOptions);
})();
How to verify success
• Start agent using one of the options.
• Open frontend and join the room.
• Agent terminal should show a "received job request" or "Job request for room:" log.
• If you still see CLI help after running the commands, run this to test quickly:
pnpm exec agents dev -- --url "wss://vertex-ai-1879pkoh.livekit.cloud" --api-key "YOUR_KEY" --api-secret "YOUR_SECRET"
If you want, tell me which option you prefer and I’ll:
• Provide the exact package.json edits (Option A), or
• Patch your worker.ts and show the exact pnpm command to run (Option B).