wonderful-kilobyte-85140
11/26/2025, 4:46 PMtall-airline-16756
11/26/2025, 4:46 PMtall-airline-16756
11/26/2025, 4:46 PMagentName and JSON metadata
• Return JSON: { token, url }
2) Agent server (Node.js using @livekit/agents)
• Runs continuously (one or more workers) and registers an agent with the same agentName.
• In the agent entry, parse ctx.info.agent.metadata to apply per-deployment config (prompts, voices, STT/LLM choices).
• Start the session pipeline (STT → LLM → TTS or other pipeline) and publish/subscribes to the room tracks.
3) Frontend flow
• User config UI → POST to backend to create agent/token → Receive token & LiveKit URL → Connect via LiveKit JS SDK using token → Agent auto-dispatched into the room
Key implementation snippets (conceptual)
• Token creation: create AccessToken with VideoGrant, set roomConfig.agents = [{ agentName, metadata: JSON.stringify(agentConfig) }], return token JWT.
• Agent server: defineAgent({ entry: async (ctx) => { const metadata = JSON.parse(ctx.info?.agent?.metadata || "{}"); configure session per metadata; await session.start({ room: ctx.room }); } });
Scalability & concurrency
• LiveKit dispatch model launches an agent job per room; run multiple agent server processes if needed.
• Use agent server loadFunc / loadThreshold or multiple replicas to balance load and avoid overload.
• Keep tokens short-lived and validate request inputs to prevent abuse.
Security & operational notes
• Store API_KEY and API_SECRET in env vars; never expose them to the frontend.
• Validate and sanitize user-provided agent configs before embedding in tokens.
• Use HTTPS and short TTLs for tokens.
• Monitor agent server health and logs; autoscale agent servers if you expect many concurrent rooms.
Next steps I can help with
• Provide exact code for the Express token endpoint (JS).
• Provide a starter agent-server example wired to a simple STT/LLM/TTS pipeline.
• Help design the agentConfig schema you should accept from frontend.
Which of the next steps would you like first — token endpoint code or an agent-server starter?
Sources: Agent server options | LiveKit docs | Agent dispatch | LiveKit docs | server-sdk-js | livekit/livekit_composite | DeepWiki | SIP dispatch rule | LiveKit docs | Agents (Node.js) | livekit/livekit_composite | DeepWikiwonderful-kilobyte-85140
11/26/2025, 4:56 PMtall-airline-16756
11/26/2025, 4:57 PM// server.js
import express from 'express';
import { AccessToken, VideoGrant, RoomConfiguration, RoomAgentDispatch } from 'livekit-server-sdk';
const app = express();
app.use(express.json());
const LIVEKIT_URL = process.env.LIVEKIT_URL;
const API_KEY = process.env.LIVEKIT_API_KEY;
const API_SECRET = process.env.LIVEKIT_API_SECRET;
app.post('/get-token', (req, res) => {
const { roomName, identity, agentConfig } = req.body; // agentConfig is a JSON object
const at = new AccessToken(API_KEY, API_SECRET, { identity, ttl: '1h' });
const grant = new VideoGrant({ room: roomName, roomJoin: true, canPublish: true, canSubscribe: true });
at.addGrant(grant);
// Attach agent dispatch with config encoded as JSON string in metadata
at.roomConfig = new RoomConfiguration({
agents: [
new RoomAgentDispatch({
agentName: 'custom-agent', // must match agent server registration
metadata: JSON.stringify(agentConfig || {})
})
]
});
const token = at.toJwt();
res.json({ token, url: LIVEKIT_URL });
});
app.listen(3000, () => console.log('Auth server running on :3000'));
Frontend calls POST /get-token with body { roomName, identity, agentConfig } and then connects to LiveKit using the returned token. The token tells LiveKit to dispatch an agent named "custom-agent" with that metadata when the room is created/joined.
2) Agent server — separate process
• Purpose: long-running worker that listens for dispatch jobs, reads `job.metadata`/`ctx.info.agent.metadata`, and configures the agent per-job.
// agent-server.js
import fs from 'fs';
import { defineAgent, AgentServer } from '@livekit/agents';
// import any pipeline libs you need (STT/LLM/TTS) here
// Helper: build agent behavior from config
function buildAgentFromConfig(config) {
const instructions = config.instructions || 'You are a helpful assistant.';
const voice = config.voice || 'default';
const tools = config.tools || [];
// Return an object the session expects (example shape)
return { instructions, voice, tools };
}
const server = new AgentServer({
agentName: 'custom-agent', // must match the token dispatch agentName
permissions: { canPublish: true, canSubscribe: true, hidden: false }
});
// Register agent behavior; runs each time this agent is dispatched to a room
server.registerAgent(defineAgent({
entry: async (ctx) => {
// ctx.info.agent.metadata contains the JSON string from the token
const metadataStr = ctx.info?.agent?.metadata || '{}';
let config;
try { config = JSON.parse(metadataStr); } catch (e) { config = {}; }
const agentDef = buildAgentFromConfig(config);
// Example: create a session object that wires STT -> LLM -> TTS
// (Pseudo-code: replace with actual libs/integrations)
const session = {
start: async ({ room }) => {
// subscribe to room audio/data, set up STT/LLM/TTS according to agentDef
// e.g., load voice model agentDef.voice, set prompt = agentDef.instructions
},
say: async (text) => {
// synthesize and publish audio to room
}
};
// Start session for this dispatched agent in the room
await session.start({ room: ctx.room });
// Use instructions from config to create initial greeting
await session.say(agentDef.instructions || 'Hello! How can I help you today?');
// Keep the job running while the agent is in the room; when room ends, cleanup happens
}
}));
// Start the agent server as its own process
server.start().catch(err => {
console.error('Agent server failed:', err);
process.exit(1);
});
Key points in this pattern
• Separation: Agent server is a separate service/process from Express. Do not embed long-running agent logic into Express.
• Config transport: Express embeds the user's JSON in token dispatch metadata; the Agent server reads it from the dispatch context (ctx.info.agent.metadata / job.metadata) and builds the agent dynamically.
• Per-room isolate: LiveKit dispatches a job per room; the agent entry function runs per-room and can create stateful sessions tied to that room.
• Agent registration: agentName in the token must match agentName the AgentServer registers.
• Security: validate and sanitize agentConfig in Express before embedding in a token to avoid injection or malformed JSON.
If you want, I can:
• Provide a full runnable example that wires a simple STT (mock), LLM call (mock), and TTS (mock) so you can test end-to-end locally.
• Show a recommended schema for agentConfig and validation middleware for the Express endpoint.
Which would you like next: runnable end-to-end example or a validated agentConfig schema?
Sources: Agent dispatch | LiveKit docs | server-sdk-js | livekit/livekit_composite | DeepWiki | Agent server options | LiveKit docs | Job lifecycle | LiveKit docs | An open source stack for real-time multimodal AIwonderful-kilobyte-85140
11/26/2025, 5:11 PMtall-airline-16756
11/26/2025, 5:12 PM// express-server.js
import express from 'express';
import { MongoClient, ObjectId } from 'mongodb';
import { AccessToken, VideoGrant, RoomConfiguration, RoomAgentDispatch } from 'livekit-server-sdk';
const app = express();
app.use(express.json());
const mongo = new MongoClient(process.env.MONGO_URL);
await mongo.connect();
const db = mongo.db('agents');
app.post('/save-config', async (req, res) => {
const cfg = req.body; // validate/sanitize!
const r = await db.collection('configs').insertOne({ cfg, owner: req.body.owner, createdAt: new Date() });
res.json({ configId: r.insertedId.toString() });
});
app.post('/get-token', async (req, res) => {
const { roomName, identity, configId } = req.body;
// Validate configId and permissions here
// Option A: embed configId only (recommended if configs are large)
const metadata = JSON.stringify({ configId });
const at = new AccessToken(process.env.LK_API_KEY, process.env.LK_API_SECRET, { identity, ttl: '1h' });
at.addGrant(new VideoGrant({ room: roomName, roomJoin: true, canPublish: true, canSubscribe: true }));
at.roomConfig = new RoomConfiguration({
agents: [{ agentName: 'custom-agent', metadata }]
});
res.json({ token: at.toJwt(), url: process.env.LK_URL });
});
app.listen(3000);
2) Agent server: fetch config from metadata or MongoDB, then run per-room agent
// agent-server.js
import { AgentServer, defineAgent } from '@livekit/agents';
import { MongoClient, ObjectId } from 'mongodb';
const mongo = new MongoClient(process.env.MONGO_URL);
await mongo.connect();
const db = mongo.db('agents');
const server = new AgentServer({ agentName: 'custom-agent', permissions: { canPublish: true } });
server.registerAgent(defineAgent({
entry: async (ctx) => {
const metadataStr = ctx.info?.agent?.metadata || '{}';
const meta = JSON.parse(metadataStr);
let config = meta.config; // if Express embedded full config
if (!config && meta.configId) {
const doc = await db.collection('configs').findOne({ _id: new ObjectId(meta.configId) });
config = doc?.cfg || {};
}
// validate config, set defaults
const instructions = config.instructions || 'Be helpful.';
// Initialize your STT/LLM/TTS pipeline using config
const session = createSessionFromConfig(config); // implement your session builder
await session.start({ room: ctx.room });
await session.say(instructions);
// keep running for room lifetime
}
}));
await server.start();
Notes and recommendations
• Embed configId in metadata (not full config) when configs are large or contain sensitive keys; the Agent server can fetch the full config securely.
• Sanitize and validate configs at save time in Express to prevent malformed or malicious configs.
• Keep one agentName (single worker type) to simplify deployment and let the agent server handle per-room instantiation; only use different agentNames if you need completely different agent binaries or drastically different permission sets.
• Use short token TTLs and check permissions/ownership in Express before issuing tokens.
If you want, I can:
• Provide a complete runnable repo structure (Express + Agent server + example session builder).
• Draft a simple JSON schema for agent configs and the Express validation middleware.
Which would help you most next?wonderful-kilobyte-85140
11/26/2025, 5:29 PMtall-airline-16756
11/26/2025, 5:29 PM// twilio-webhook.js (Express)
import express from 'express';
import { MongoClient, ObjectId } from 'mongodb';
import { AccessToken, VideoGrant, RoomConfiguration, RoomAgentDispatch } from 'livekit-server-sdk';
const app = express();
app.use(express.urlencoded({ extended: false })); // Twilio sends form-encoded
const mongo = new MongoClient(process.env.MONGO_URL);
await mongo.connect();
const db = mongo.db('agents');
app.post('/twilio/inbound', async (req, res) => {
const calledNumber = req.body.To; // Twilio's dialed SIP number
const mapping = await db.collection('mappings').findOne({ sipNumber: calledNumber });
if (!mapping) {
// Respond with simple TwiML message then hang up
return res.type('text/xml').send(`<Response><Say>Number not configured. Goodbye.</Say></Response>`);
}
// Create or pick a room name (e.g., use mapping.configId or a generated call-id)
const roomName = `call-${Date.now()}-${mapping.configId}`;
// Build token with agent dispatch metadata referencing configId
const at = new AccessToken(process.env.LK_API_KEY, process.env.LK_API_SECRET, { identity: `twilio-${Date.now()}`, ttl: '1h' });
at.addGrant(new VideoGrant({ room: roomName, roomJoin: true, canPublish: true, canSubscribe: true }));
at.roomConfig = new RoomConfiguration({
agents: [{ agentName: 'custom-agent', metadata: JSON.stringify({ configId: mapping.configId, inbound: true }) }]
});
const token = at.toJwt();
// Option A: If you have a SIP<->LiveKit gateway endpoint that will join LiveKit with this token,
// return TwiML to forward the SIP call to that gateway and include token & room (as SIP URI params or via your gateway API).
// Option B: Use Twilio Media Streams to stream audio to your service which then publishes to LiveKit (more advanced).
// Example simple TwiML to dial a SIP gateway (gateway must know how to accept room & token):
const gatewayUri = `sip:gateway@example.com;room=${encodeURIComponent(roomName)};token=${encodeURIComponent(token)}`;
const twiml = `<Response><Dial><Sip>${gatewayUri}</Sip></Dial></Response>`;
res.type('text/xml').send(twiml);
});
3) Gateway or SIP bridge
• You need a component (could be a lightweight service or 3rd-party SIP gateway) that accepts the SIP call from Twilio, extracts the token and room, then joins LiveKit as a participant (publishing remote audio into the room). This gateway can be your own small service or a SIP-to-WebRTC product.
• Alternatively, use Twilio Media Streams to stream audio to your service which then injects audio into LiveKit (lower-level but flexible).
Agent server behavior
• Agent server receives dispatch with metadata { configId, inbound: true }.
• It fetches the full config from MongoDB, then initializes STT/LLM/TTS pipeline tuned for phone calls (e.g., different prompts, voice, silence detection).
• It publishes synthesized audio back into the room so the caller hears responses.
Operational notes & recommendations
• Validate ownership: ensure only the owner can map a SIP number to their config.
• Token TTL: keep tokens short for security; the gateway should use the token only to join the specific room.
• Logging & call-id: store call sessions in MongoDB for auditing (roomName, mapping, start/end timestamps).
• Gateway reliability: use a stable SIP/WebRTC bridge; Twilio Media Streams is flexible but requires more work.
• If many simultaneous inbound calls expected, autoscale the gateway and agent servers.
If you’d like, I can:
• Provide a small gateway example that accepts SIP from Twilio and joins LiveKit with the token.
• Show a Twilio Media Streams example that forwards audio into LiveKit instead of using a SIP gateway.
Which integration path do you prefer: SIP gateway (easier to wire TwiML) or Twilio Media Streams (more control)?wonderful-kilobyte-85140
11/26/2025, 5:40 PMtall-airline-16756
11/26/2025, 5:41 PMwonderful-kilobyte-85140
12/01/2025, 9:52 AMtall-airline-16756
12/01/2025, 9:53 AM// POST /save-config -> stores config, returns configId
// POST /get-token { roomName, identity, configId } -> returns token whose roomConfig.agents[0].metadata = JSON.stringify({ configId })
2) Agent server: load config and drive prompt/flow
// agent-server.js (separate process)
import { AgentServer, defineAgent } from '@livekit/agents';
import { MongoClient, ObjectId } from 'mongodb';
const mongo = new MongoClient(process.env.MONGO_URL);
await mongo.connect();
const db = mongo.db('agents');
const server = new AgentServer({ agentName: 'custom-agent' });
function createAgentHandlers(config) {
// returns an object mapping promptName -> async handler(ctx, session)
return {
intro: async (ctx, session) => {
await session.say(config.prompts.intro || "Hi! How can I help?");
// optionally wait for user reply, analyze intent, then return next step
const intent = await session.waitForIntent(); // pseudo
if (intent === 'buy') return { next: 'sales' };
if (intent === 'support') return { next: 'support' };
return { next: 'intro' };
},
sales: async (ctx, session) => { /* sales flow */ },
support: async (ctx, session) => { /* support flow */ },
// ... other prompt handlers
};
}
server.registerAgent(defineAgent({
entry: async (ctx) => {
const meta = JSON.parse(ctx.info?.agent?.metadata || '{}');
let config = meta.config;
if (!config && meta.configId) {
const doc = await db.collection('configs').findOne({ _id: new ObjectId(meta.configId) });
config = doc?.config || {};
}
const handlers = createAgentHandlers(config);
// session is a thin wrapper around STT/LLM/TTS and state
const session = createSession(ctx, { userdata: {}, history: [] }); // implement createSession
// choose initial flow/step
const flowId = meta.flowId || config.defaultFlow;
let currentStep = config.flows?.find(f => f.id === flowId)?.steps?.[0] || 'intro';
while (ctx.room.isActive()) {
const handler = handlers[currentStep];
if (!handler) break;
const result = await handler(ctx, session);
// support explicit handoff: { next: 'sales' } or { handoff: 'human' }
if (result?.handoff) {
// implement handoff (e.g., notify operator, persist state)
break;
}
currentStep = result?.next || currentStep;
}
}
}));
await server.start();
Key implementation notes
• Hand off between prompts by returning a next-step or a handoff action from each handler.
• Use session.userdata to store variables across prompt transitions (name, order id, progress).
• Preserve LLM context/history by passing the session chat context into each handler if your LLM calls need the prior messages.
• Keep handlers small and testable — they are your prompt units.
• For low latency in calls: prewarm STT/LLM/TTS, pin region, use LiveKit Phone Numbers or region-proxied SIP trunks.
When to use multi-agent vs single agent with dynamic prompts
• Multi-agent (recommended): each prompt as an agent class + handoffs. Cleaner, composable, easier to reuse prompts across flows.
• Single-agent dynamic prompts: simpler code but more complex prompt management and state handling for many flows.
If you want I can:
• Draft a full starter repo (Express + MongoDB + Agent server) with a small mock STT/LLM/TTS pipeline to test multi-prompt flows.
• Provide a JSON schema for configs and a validation middleware for Express.
Which would you prefer to see next?
Sources: Agents and handoffs | LiveKit docs | Tasks and task groups | LiveKit docs | Announcing Agent Builder: A Pathway to Code | Workflows | LiveKit docs | Live Conversations with AI using ChatGPT and WebRTCwonderful-kilobyte-85140
12/01/2025, 10:05 AMtall-airline-16756
12/01/2025, 10:06 AM// agent-tools.js
import { llm, voice } from '@livekit/agents';
import { z } from 'zod';
// Example tool: lookup order status from your DB/API
const getOrderStatus = llm.tool({
description: 'Return order status for a given orderId.',
parameters: z.object({
orderId: z.string().describe('Order ID to lookup'),
}),
execute: async ({ orderId }, { ctx }) => {
// implement your DB/API call here (secure)
// e.g., const order = await ordersDb.find(orderId)
return { orderId, status: 'shipped', eta: '2025-12-10' };
},
});
// Example tool: create support ticket
const createTicket = llm.tool({
description: 'Create a support ticket with title and body.',
parameters: z.object({
title: z.string(),
body: z.string(),
priority: z.enum(['low','medium','high']).optional(),
}),
execute: async ({ title, body, priority }, { ctx }) => {
// call your ticketing API; return ticket details
const ticket = { id: 'TCK-1234', status: 'open', priority: priority || 'medium' };
return ticket;
},
});
// Agent definition with single prompt and tools
class SupportAgent extends voice.Agent {
constructor() {
super({
instructions: 'You are a customer support voice assistant. Use tools when needed.',
tools: {
getOrderStatus,
createTicket,
},
});
}
}
export { SupportAgent };
Agent entrypoint (per-room job)
// agent-server.js
import { AgentServer, defineAgent, cli } from '@livekit/agents';
import { SupportAgent } from './agent-tools.js';
const server = new AgentServer({
agentName: 'custom-agent',
permissions: { canPublish: true, canSubscribe: true },
});
server.registerAgent(defineAgent({
entry: async (ctx) => {
// create session wiring STT/LLM/TTS as you need (pseudo)
const session = await createSessionFromCtx(ctx); // implement session builder
await session.start({ room: ctx.room, agent: new SupportAgent() });
// optional: greeting
await session.say('Hello — I can check orders or create tickets. How can I help?');
// session runs for room lifetime; tool calls happen automatically via the agent/LLM
},
}));
await server.start();
Notes and best practices
• Use Zod (or similar) to describe tool params so the LLM gets clear parameter schemas.
• Keep tools deterministic and side-effect safe; require auth/permission checks inside execute().
• Prefer returning structured JSON from tools — the LLM ingests results more reliably.
• For sensitive configs/API keys, keep them server-side (do not embed in tokens/metadata).
• Log tool invocations (who/when/params/result) for auditing and debugging.
• If a tool needs frontend data (e.g., user device info), use an RPC tool that sends a request to the connected participant and waits for response.
• Rate-limit or queue heavy tools (long-running API calls) so agent latency remains acceptable.
If you want, I can:
• Provide a runnable starter repo with a mock STT/LLM/TTS pipeline and two tools.
• Show how to expose a tool that triggers an RPC to the frontend (example code).
Which do you want next?
Sources: Agents and handoffs | LiveKit docs | Tool definition and use | LiveKit docs | External data and RAG | LiveKit Docs | Agents v0.x migration guide - Node.js | LiveKit Docswonderful-kilobyte-85140
12/01/2025, 10:08 AMtall-airline-16756
12/01/2025, 10:08 AM// save-tool (simplified)
import express from 'express';
import { MongoClient } from 'mongodb';
import { z } from 'zod';
const toolSchema = z.object({
name: z.string(),
description: z.string(),
type: z.enum(['http','rpc','db','internal']),
paramsSchema: z.any(),
integration: z.object({ kind: z.string(), details: z.any() })
});
app.post('/api/tools', async (req, res) => {
const parsed = toolSchema.parse(req.body); // validate
const r = await db.collection('tools').insertOne({ ...parsed, ownerId: req.user.id, createdAt: new Date() });
res.json({ toolId: r.insertedId.toString() });
});
3) Express: issue token with configId
// get-token
const metadata = JSON.stringify({ configId });
at.roomConfig = new RoomConfiguration({ agents: [{ agentName: 'custom-agent', metadata }] });
4) Agent server: fetch config and dynamically register tools
// agent-server.js (conceptual)
import { AgentServer, defineAgent, llm } from '@livekit/agents';
import { MongoClient, ObjectId } from 'mongodb';
const db = new MongoClient(process.env.MONGO_URL);
await db.connect();
function makeToolExecutor(toolDoc) {
const { integration } = toolDoc;
if (integration.kind === 'http') {
return llm.tool({
description: toolDoc.description,
parameters: /* construct from toolDoc.paramsSchema */,
execute: async (params, { ctx }) => {
// call your backend service or the external URL (include auth from vault)
const resp = await fetch(integration.details.url, { method: integration.details.method, headers: { Authorization: `Bearer ${getSecret(integration.details.authId)}` }, body: JSON.stringify(params) });
return await resp.json();
}
});
}
if (integration.kind === 'rpc') {
return llm.tool({
description: toolDoc.description,
parameters: /* ... */,
execute: async (params, { ctx }) => {
// find the live participant in ctx.room and perform RPC
const participant = Array.from(ctx.room.remoteParticipants.values())[0];
const response = await ctx.room.localParticipant.performRpc({
destinationIdentity: participant.identity,
method: 'toolRpc',
payload: JSON.stringify({ toolId: toolDoc._id.toString(), params }),
responseTimeout: 10000
});
return JSON.parse(response);
}
});
}
// other kinds (db/internal) -> call internal services directly
}
server.registerAgent(defineAgent({
entry: async (ctx) => {
const meta = JSON.parse(ctx.info.agent.metadata || '{}');
const cfgId = meta.configId;
const cfg = await db.collection('configs').findOne({ _id: new ObjectId(cfgId) });
const tools = {};
for (const tId of cfg.toolIds) {
const tdoc = await db.collection('tools').findOne({ _id: new ObjectId(tId) });
tools[tdoc.name] = makeToolExecutor(tdoc);
}
const agent = new (class extends voice.Agent {
constructor(){ super({ instructions: cfg.prompt, tools }); }
})();
const session = createSession(ctx, { /* stt/llm/tts */ });
await session.start({ room: ctx.room, agent });
}
}));
Security & best practices
• Validate tool definitions on save (param schemas, url allowlist).
• Store integration credentials in your secrets vault; agent server retrieves securely (do not store secrets in DB or send to frontend).
• Only allow owners/admins to map tools to phone numbers or agents.
• Sanitize inputs and rate-limit tool execution to protect downstream services.
• Log tool calls for audit and debugging.
RPC tools (for frontend-only data)
• Use a tool of kind 'rpc' that sends an RPC call to the connected participant and waits for reply.
• The browser must implement an RPC handler (LiveKit data RPC) to respond to that method.
• This is useful when you need user device inputs (e.g., microphone permission, geolocation, screen capture).
Why this pattern is simplest & scalable
• Frontend only defines high-level tool configs—no code execution risk.
• Backend centralizes code that actually calls services, so you control security, secrets, and rate limits.
• Agent server dynamically assembles tool set per-job, so one agent binary works for many users/configs.
• Works for both web sessions and inbound phone calls (agent server is the common runtime).
If you want, I can:
• Provide a concrete runnable example repo (Express + MongoDB + agent-server) implementing: one http tool, one rpc tool, config CRUD, token issuance, and a small frontend RPC handler.
• Draft validation schemas for tool definitions and a checklist for securing integrations.
Which should I provide next: runnable starter repo or the validation + security schema?