I'm building an agent builder frontend. So i'll ne...
# ask-ai
w
I'm building an agent builder frontend. So i'll need to create an agent with a custom config & deploy it to a room for a frontend user to connect to. Frontend could have many users trying to create and talk to a custom agent. How does the backend for this look like (assuming I want to use js)
t
Thanks for reaching out, Someshwar. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how a JavaScript backend should look so frontend users can create custom agents (with configs) and deploy them into LiveKit rooms for real-time interaction. Below is a concise, practical backend design you can implement with Node.js. Core idea • Backend issues short-lived LiveKit tokens that include a RoomAgentDispatch (agent name + metadata/config). • A long-running agent server (using @livekit/agents) listens for dispatches and starts an agent instance in the room, reading the metadata to configure behavior (instructions, voice, model, etc.). • Frontend calls your backend to request a token and LiveKit URL, then connects to the room — LiveKit will dispatch the configured agent automatically. Architecture (high level) • Frontend (many users) → Your JS Backend (Express / Next API) → LiveKit (token + room) → Agent Server(s) running @livekit/agents join room and run configured agent logic Minimal components to implement 1) Token-generation endpoint (Node.js + livekit-server-sdk) • Accepts: roomName, userId, agentConfig (instructions, voice, model, metadata) • Creates an AccessToken with a VideoGrant for the room and embeds a RoomAgentDispatch entry with
agentName
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 | DeepWiki
w
Tell me more about how the Agent server codebase would look like, would it be part of the express codebase? how would it take in a json and create a custom agent. Show me code also so that it's clear
t
You're asking whether the Agent server should live inside your Express app, how it consumes JSON to create custom agents, and for clear JS code showing that flow. Short answer: keep them separate — Express issues tokens & embeds JSON metadata; the Agent server runs as a separate Node process, reads the metadata on dispatch, and builds the agent at runtime. Below is a concise, runnable pattern (Node.js) showing: • Express token endpoint that embeds JSON agent config in the dispatch • Separate Agent server that parses metadata and instantiates a per-room agent using that JSON 1) Express backend — token endpoint • Purpose: authenticate frontend users and embed agent dispatch (agentName + JSON metadata) in the token.
Copy code
// 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.
Copy code
// 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 AI
w
I see that the agent-name should match. Different users will be creating multiple agents right. The agent-name should be different for each right? I want the agent config to be stored in mongodb, does that change things. I want the simplest structure
t
You're right to focus on unique identification and simplicity. Short answers first, then a minimal pattern you can implement. Short answers • Agent name in the token must match the agent server registration. • You do NOT need a unique agentName per user. Use a single registered agentName (e.g., "custom-agent") for all dispatches and pass each user's config in the dispatch metadata. • Storing per-agent configs in MongoDB works well: Express reads the config by ID, embeds it (or an ID) into the token metadata, and the Agent server loads the JSON (either from metadata or by fetching from MongoDB using the ID). • Simplest structure: one Express service (auth + token + config CRUD), one Agent server process registered as a single agentName that dynamically loads config per-dispatch. Recommended minimal flow 1. User saves agent config in MongoDB → returns configId. 2. Frontend requests token to join room with configId. 3. Express loads configId (or validates it) and creates token embedding { configId } in metadata (or the full config JSON if small). 4. LiveKit dispatches agent job to your Agent server (agentName = "custom-agent") with metadata. 5. Agent server, on entry, reads metadata; if metadata contains configId it fetches full config from MongoDB, then initializes the per-room agent using that config. Minimal code snippets 1) Express: store config, return token with configId in metadata
Copy code
// 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
Copy code
// 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?
w
what if a frontend user wants to assign one of the agents to a twilio SIP number for inbound calling. Different people might want different agents on different SIP numbers
t
Good question — you can map any user's agent to a Twilio SIP number. Keep the same simple architecture: store mappings in MongoDB, use Express to handle Twilio webhooks, generate a LiveKit token that dispatches the configured agent, and bridge the incoming call into a LiveKit room. Minimal flow and sample code below. High-level flow 1. User saves agent config in MongoDB and creates a mapping record { sipNumber, configId, owner }. 2. Twilio receives an inbound call to a SIP number and sends a webhook to your Express endpoint. 3. Your Express webhook looks up the mapping for that SIP number, validates it, creates/chooses a LiveKit room, generates a token with a RoomAgentDispatch metadata containing the configId (or inline config), and returns TwiML that connects the call into the LiveKit room (SIP or WebRTC bridge). 4. Your Agent server (registered as the single agentName) is dispatched into the room, fetches config from metadata/MongoDB, and handles the call (STT → LLM → TTS). Design choices • Keep one agentName (e.g., "custom-agent") and pass per-call config via metadata — simplest and scalable. • Store mapping { sipNumber => configId } in MongoDB so different users can map different SIP numbers. • Embed only configId in token metadata (recommended). Agent server fetches full config securely from MongoDB. • Choose bridging method: Twilio can SIP-to-WebRTC or SIP-to-SIP; you’ll typically use TwiML <Dial><Sip> or Twilio Media Streams + a SIP/WebRTC bridge to connect audio into LiveKit. Return TwiML that connects the call to your LiveKit gateway (or a SIP gateway that publishes to the LiveKit room). Concise example (Express + Twilio webhook + LiveKit token) 1) Mongo mapping doc { sipNumber: "+15551234567", configId: "65..." , owner: "user123" } 2) Twilio webhook handler (simplified)
Copy code
// 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)?
w
Take a step back and think about my problem statement. I want an agent builder frontend to be used by many people to create custom agents. The users could try to talk to the agents on the web, or assign the agent to a number (owned by frontend) for inbound calling. What are my options in building a service like this? My priority is call latency
t
You're building a multi-tenant agent-builder platform for web + inbound phone with call-latency as the top priority. Below are the practical architecture options, trade-offs, and a clear recommended path that minimizes latency while staying simple to operate. Top-level constraints to remember • Minimize hops between caller ⇄ media edge ⇄ agent compute. • Keep agent startup/cold-start time low (prewarm / warm workers). • Keep architecture simple: one Express auth/control plane + separate Agent workers. • Prefer region-pinned infrastructure so SIP and agent compute sit in same region. Options and trade-offs (concise) 1) LiveKit Cloud Agents + LiveKit Phone Numbers — Best for lowest latency (recommended) • What: Use LiveKit Cloud to host agents (agent workers) and buy phone numbers via LiveKit Phone Numbers API. • Why low latency: phone numbers map to LiveKit regional edges; callers hit the nearest edge and the agent compute can be pinned to that same region. • Pros: lowest end-to-end latency, autoscaling, simpler infra, built-in dispatch and observability. • Cons: vendor cost and less low-level control vs self-host. • When to use: you want “just work” low-latency phone + web with minimal infra ops. 2) LiveKit Cloud Agents + Third-party SIP (e.g., Twilio/Telnyx) — medium latency • What: Use LiveKit for agent hosting, third-party SIP for numbers. • Latency impact: extra hop via SIP provider regional proxy → LiveKit edge. Choose provider regional proxy endpoints to reduce hops. • Pros: flexible number management, established telco features. • Cons: slightly higher latency than using LiveKit Phone Numbers; more moving parts. 3) Self-hosted LiveKit + Regional SIP gateways — flexible but ops-heavy • What: Run LiveKit cluster (or edge instances) and your own SIP gateway (or use provider trunk) pinned to regions. • Latency impact: can be low if you carefully provision regional edges and gateways, but requires significant ops. • Pros: full control, potentially lower cost at scale. • Cons: complex to run, maintain, and scale globally. Agent hosting patterns (multi-tenant) • Single registered agentName (recommended): register one agent worker process (e.g., "custom-agent") and dispatch per-room configs via token metadata or configId. Simpler, less infra. • Per-tenant agentName: create distinct agent deployments per tenant when you need strict isolation, different binaries, or tenant-level resource guarantees. More complex and costly. • Recommendation: start with single agent worker that reads per-job metadata/config from MongoDB. Move to per-tenant deployments only if you need dedicated resources or isolated runtime. How to minimize call latency (practical checklist) • Region pin the agent to the same LiveKit edge where calls land. • Use LiveKit Phone Numbers (or region-proxied SIP trunks) to avoid extra provider hops. • Prewarm agent processes and keep a pool of idle workers to avoid cold starts. • Use short audio frame sizes and low codec latency (G.711 for PSTN; Opus settings for WebRTC). • Run your STT/LLM/TTS inference in-region (or use low-latency LLM endpoints). • Measure and iterate: track RTP round-trip, TTFB for audio generation, and model response time. Simple, low-latency architecture (concrete recommended stack) • Frontend: React UI for agent builder + WebRTC client to test agents. • Control plane: Express API + MongoDB ◦ CRUD agent configs → store config documents and return configId. ◦ Token endpoint: produce AccessToken with RoomAgentDispatch metadata containing configId or inline config. ◦ Phone mapping API: map platform-owned number -> configId. • Agent workers: single AgentServer (Node or Python) registered as "custom-agent" ◦ On dispatch: read metadata; if metadata has configId → fetch from MongoDB → initialize per-room session (STT→LLM→TTS). ◦ Keep worker warm: prewarm models, maintain idle processes. • SIP bridging: ◦ Preferred: LiveKit Phone Numbers (region pinned) that route inbound calls into LiveKit rooms. ◦ Alternative: Twilio/Telnyx SIP trunk to your SIP gateway or Media Streams → bridge into LiveKit room. Flow for inbound call (minimal latency) 1. Caller dials platform number (LiveKit Phone Number) → hits LiveKit edge in region R. 2. LiveKit dispatches an agent job for the target room (agentName = "custom-agent", metadata includes configId). 3. Agent worker pinned in region R gets job, fetches config (or uses metadata), joins the room, and connects STT/LLM/TTS pipelines. 4. Agent publishes audio back to the room → caller hears replies with minimal hops. Operational simplicity tips • Embed only configId in token metadata; let the agent worker fetch the full config from MongoDB (keeps token small and prevents leaking secrets). • Validate owner permissions in Express before issuing tokens or mapping numbers. • Keep a call/session table in MongoDB: { callId, room, configId, start/end, latency metrics } for postmortem and tuning. • Start with one region and LiveKit Cloud; expand regions when you need geographic coverage. Next practical steps I can provide • Minimal repo layout and example code for: Express + MongoDB token/config endpoints, Agent worker that reads configId and runs a mock STT/LLM/TTS pipeline, and a Twilio vs LiveKit Phone Numbers example for inbound handling. • A prioritized checklist to reduce call latency (prewarm, region pin, codec settings). Which next step would you like: runnable starter repo (Express + Agent worker) or an actionable latency checklist with exact config suggestions (regions, codec settings, prewarm params)? Sources: Deploying to production | LiveKit Docs | Generating tokens | LiveKit docs | Server-side | livekit/livekit_composite | DeepWiki | SIP cloud and region pinning | LiveKit docs | Phone Numbers APIs | LiveKit docs
w
how can I create a multi prompt agent backend, like retell
t
You're asking how to build a multi-prompt agent backend (like Retell). Below is a concise, practical design and a minimal Node.js/LiveKit-style code pattern showing how to implement multiple prompts, dynamic switching, and preserved context. Core idea • Model each prompt/persona as a small agent (distinct instructions). • Use agent handoffs to switch between prompts (function-tool style or an explicit router). • Keep shared state (session variables, progress) in session userdata. • Preserve conversation history by passing chat context when handing off. Architecture (simple) • Express + MongoDB: store agent "prompt" templates and full flow definitions. • Single Agent Server (separate process) registered as a dispatcher (e.g., "custom-agent"). • Token metadata includes configId or flowId; agent server fetches config and runs per-room sessions. • Agents are lightweight classes or handlers that implement a prompt + optional tools. Data model (suggested) • configs collection: { _id, ownerId, name, prompts: { intro, sales, support, survey }, flows: [ {id, steps:[ 'intro','survey','handoff:human' ] } ], createdAt } • mappings: phoneNumber -> configId • sessions: call/room records with current step, userdata, history refs Minimal flow 1. Frontend creates/saves config (prompts + flows) → returns configId. 2. User or inbound call triggers room creation with token containing configId. 3. Agent server reads config, starts session at the flow's first prompt. 4. When conditions are met, agent returns a handoff action which routes to another prompt/agent. 5. Session userdata persists state; conversation history is preserved by passing chat_ctx into the next prompt. Minimal Node.js/JS pattern (conceptual — adapt to your libraries) 1) Express: save config and issue token with configId
Copy code
// 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
Copy code
// 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 WebRTC
w
lets go back to the single prompt agent. How can I give it access to tools
t
Good — single-prompt agent + tools is a simple, powerful pattern. Below is a concise explanation and a concrete Node.js example showing: • how to define tools • how to register them with a single-prompt agent • how the LLM can invoke them during a session • notes on security and common integrations How it works (short) • Tools are server-side functions exposed to the agent’s LLM as callable operations (typed schema + description). • When the LLM decides to call a tool, the framework invokes your function, returns the structured result to the model, and the model continues the conversation using that result. • You register tools when constructing the agent (no separate agent per tool needed). Node.js example (minimal, using @livekit/agents) • Define tools with schema and execute logic • Create a single agent with tools included • Agent session runs in a dispatched job and the LLM can call tools
Copy code
// 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)
Copy code
// 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 Docs
w
if you remember I wanted an agent builder frontend to be used by many people to create custom agents. The users could try to talk to the agents on the web, or assign the agent to a number (owned by frontend) for inbound calling. How can i pass tools to the agent from the frontend
t
Good question — you want frontend users to define tools (APIs, DB actions, RPCs) and have those tools available to their agent when it runs (web or phone). Short answer: don’t ship executable code from the browser. store tool definitions and wiring in your backend, reference them from the token metadata (or embed a safe config), and have the agent server load/instantiate those tools per-dispatch. Below is a minimal, secure pattern with concrete code sketches. Core principles • Never run arbitrary frontend code on the agent server. • Frontend supplies a tool definition schema (name, description, parameters, type, integrationId). • Backend stores tool configs in MongoDB and validates them. • Token metadata contains a trusted reference (configId or toolIds) — not raw code. • Agent server fetches the tool configs and registers concrete tool implementations (wrappers that call your internal APIs, RPCs, or 3rd-party services). • For data from the actual caller’s device, expose an RPC-style tool that requests the frontend participant and waits for a response. Flow overview 1. Frontend: user defines tools via UI → POST /save-tool → backend validates & stores config → returns toolId. 2. Frontend: creates/updates agent config selecting toolIds → POST /save-agent-config → returns configId. 3. When user requests a token / an inbound call arrives, Express issues a token with metadata { configId }. 4. Agent server: on dispatch, reads metadata, fetches config + tool definitions from DB, constructs tool implementations and passes them to the agent instance. 5. At runtime, the LLM calls a tool → agent framework invokes your server-side execute() for that tool → tool can: ◦ call internal APIs (DB, CRM) ◦ call 3rd-party services (Stripe, Zendesk) ◦ perform RPC to frontend participant and await response Minimal data model (Mongo) • tools: { _id, ownerId, name, description, type, paramsSchema, integration: { kind:'internal'|'http'|'rpc'|'thirdparty', details: {...} }, createdAt } • configs: { _id, ownerId, prompts, toolIds: [...], flowDef } • mappings: phoneNumber -> configId Example components 1) Frontend saves a tool (example request) POST /api/tools body: { name, description, type: "http"|"rpc"|"db", paramsSchema, integration: { kind:'http', url:'https://api.example.com/lookup', method:'POST', authId:'int_abc' } } 2) Express: validate & store tool
Copy code
// 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
Copy code
// 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
Copy code
// 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?