In what ways can I dispatch agent to the interview...
# ask-ai
b
In what ways can I dispatch agent to the interview room using Node.js?
t
Thanks for reaching out, Dmytro. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm happy to guide you through how to dispatch an agent to the interview room using Node.js! You have two friendly options to choose from: 1. Explicit Dispatch Using AgentDispatchClient: This approach uses the
AgentDispatchClient
from the LiveKit SDK to programmatically send an agent to a room. Here’s a simple example to help you get started:
Copy code
import { AgentDispatchClient } from 'livekit-server-sdk';

const agentDispatchClient = new AgentDispatchClient(
  process.env.LIVEKIT_URL,
  process.env.LIVEKIT_API_KEY,
  process.env.LIVEKIT_API_SECRET
);

// Dispatch agent to room
const dispatch = await agentDispatchClient.createDispatch(
  'interview-room',     // room name
  'interview-agent',    // agent name (must match agent's WorkerOptions.agentName)
  {
    metadata: JSON.stringify({
      agentRole: 'interviewer',
      interviewId: '12345',
    }),
  }
);

console.log('Agent dispatched:', dispatch);
This method is great because it lets you decide exactly when to trigger the agent to join. 2. Dispatch on Participant Connection (via Token): If you prefer, you can embed the agent dispatch setup directly into the participant’s access token. That way, the agent is dispatched automatically when the participant joins. Here’s how you can do it:
Copy code
import { AccessToken } from 'livekit-server-sdk';
import { RoomConfiguration, RoomAgentDispatch } from '@livekit/protocol';

const at = new AccessToken();
at.identity = 'candidate-123';
at.addGrant({ roomJoin: true, room: 'interview-room' });

// Configure agent dispatch in room config
at.roomConfig = new RoomConfiguration({
  agents: [
    new RoomAgentDispatch({
      agentName: 'interview-agent',
      metadata: JSON.stringify({
        role: 'technical interviewer',
        experienceLevel: 'senior',
      }),
    }),
  ],
});

const token = await at.toJwt();
console.log('Participant token:', token);
This way, the agent joins seamlessly as soon as the participant connects with this token. Just a quick tip: make sure your agent is registered with the correct
agentName
in its
WorkerOptions
so explicit dispatch works smoothly. If you'd like to see a full working example, feel free to check out the LiveKit Node SDK agent dispatch example. I hope this helps you move forward confidently! Sources: Job lifecycle | LiveKit Docs | Agent dispatch | LiveKit Docs | packages/livekit-server-sdk/src/AgentDispatchClient.ts
b
Let's proceed with option 2. What will be in case I don't specify RoomConfiguration?
t
Thanks for reaching out! Could you please share a bit more about the setup you have in mind? Are you wondering about what happens by default with agent dispatch when
RoomConfiguration
isn’t included, or are you curious about how the system manages agent dispatch without any particular configuration? I’m here to help clarify this for you!
b
Okay, so how much time does it take for livekit to dispatch Voice Agent to the room?
t
I'm happy to share that LiveKit usually sends a Voice Agent to a room in under 150 ms! This quick response comes from carefully optimized dispatch methods that handle lots of requests smoothly. That said, a few things like how close your network is, which AI service providers you’re using (like STT/LLM/TTS), and how your endpoints are set up can affect the timing. If you notice any delays, a good step is to make sure you have enough agent workers and that they’re located near your AI services to help keep things speedy. If you’d like, I’m here to help you fine-tune the dispatch performance—just let me know! Sources: Web and mobile frontends | LiveKit Docs | Agent dispatch | LiveKit Docs | livekit-api/livekit/api/agent_dispatch_service.py | SIP Integration & Telephony | livekit/livekit_composite | DeepWiki | Operational Guidance & Best Practices | livekit/livekit_composite | DeepWik...
b
Yes, current dispatch time takes around 5-6 seconds until agent joins and start talking
t
I understand that waiting 5-6 seconds for the agent to join and start talking can feel a bit long, and I’m here to help you improve that experience. Let’s look at some ways we can optimize this together: 1. Scale Agent Workers: It’s important to make sure you have enough agent servers running to handle all the requests coming in at the same time. Keeping an eye on the dispatch queue and automatically scaling your worker instances can really help prevent any timeouts. 2. Reduce Network Latency: Placing your agent servers closer to the AI services they rely on (like LLM, STT, TTS) can make a big difference. This way, the data doesn’t have to travel as far, cutting down on delays. 3. Choose Low-Latency AI Providers: Not all AI providers perform the same everywhere. It’s a good idea to evaluate which ones offer the fastest response times in your region and pick the best fit. 4. Use Metrics API for Monitoring: Keeping track of key metrics like Time To First Token (TTFT) and Time To First Byte (TTFB) can help you spot exactly where delays might be happening, whether it’s with LLM or TTS responses. 5. Tune Endpointing Settings: Adjusting your STT endpointing settings can help the system detect when speech ends more quickly, so the agent can respond faster. By working through these steps, you should see a noticeable improvement in how quickly the agent joins and starts the conversation. If you’d like, I’m more than happy to walk you through any of these points in more detail—just let me know! Sources: Troubleshooting & Common Issues | livekit/livekit_composite | DeepWiki | Community & Support | livekit/livekit_composite | DeepWiki | How can I reduce latency in voice agents using STT, TTS and LLM? | Agent dispatch | LiveKit Docs | Operational Guidance & Best Practices | livekit/livekit_composite | DeepWik...
b
I noticed that prewarm stage is executed for each dispatched agent, is it expected?
t
I’d like to help clarify how the prewarm stage works. It’s designed to run once for each process, not for every dispatched agent. This is an intentional setup that applies across all LiveKit configurations. The purpose of the prewarm stage is to load important resources, like model files or other static data, into the process before any jobs start. This helps improve efficiency, reduce latency, and keep processes isolated for better fault tolerance. If you’re seeing prewarming happen with every agent dispatch, it might mean new processes are being created each time instead of reusing the pre-warmed ones. To get the best performance, make sure your deployment keeps a pool of pre-warmed processes ready. By default, LiveKit can prewarm up to 4 idle processes in production, allowing them to handle multiple jobs smoothly. If you’d like, I’m here to help you set this up or answer any questions you have! Sources: Worker options | LiveKit Docs | agents/src/generator.ts | ivr-nagivator/README.mdoc | main.py | examples/voice_agents/langgraph_agent.py
b
So what should I check to verify that prewarm processes exists and how to configure prewarm processes for 10-20 sessions per minute
t
To help you verify and configure prewarm processes for handling 10–20 sessions per minute, here’s a friendly step-by-step guide: 1. Verify Prewarm Processes • Start by defining a
prewarm_fnc
in your
WorkerOptions
to initialize necessary resources, like loading models. • Keep an eye on your logs for signs of prewarm activity or notice if initialization times get shorter when jobs begin. • Check out the
/worker
health endpoint (available via
WorkerOptions
) to see active job counts and how many idle processes are ready to go. 2. Configure Prewarm Processes You can set the
num_idle_processes
parameter in
WorkerOptions
to keep a pool of prewarmed processes available:
Copy code
def prewarm(proc: JobProcess):
    proc.userdata["vad"] = silero.VAD.load()  # Example: preloading VAD model

if __name__ == "__main__":
    cli.run_app(
        WorkerOptions(
            entrypoint_fnc=entrypoint,
            prewarm_fnc=prewarm,
            num_idle_processes=10  # Adjust based on load
        )
    )
For handling 10–20 sessions per minute (about 1 session every 3–6 seconds), a good starting point is
num_idle_processes=5–10
. You can then tweak this number based on how things perform. 3. Monitor and Optimize • Make sure your LiveKit Cloud plan supports enough concurrent sessions and agent session minutes for your needs. • Keep an eye on CPU usage, session concurrency, and how quickly agents start up to fine-tune your
num_idle_processes
setting. • Consider using the
load_fnc
and
load_threshold
parameters to automatically adjust idle processes depending on system load. If you have any questions or need a hand with implementation or monitoring, please don’t hesitate to reach out—I’m here to help! Sources: examples/other/transcription/multi-user-transcriber.py | Quotas and limits | LiveKit docs | LiveKit Pricing | Worker options | LiveKit Docs
b
I use Node.js SDK Okay, so currently I configured agent setup as this:
Copy code
cli.runApp(new WorkerOptions({ agent: fileURLToPath(import.meta.url), production: true, numIdleProcesses: 10 }));
When I run agent locally, I see logs from prewarm for N processes but when I dispatch agent by creating AccessToken anyway it creates one more process and waiting for prewarm
t
I understand how important it is to have your setup running smoothly! In your current configuration, LiveKit creates a new process and runs the
prewarm
function whenever it dispatches an agent. This happens because the
prewarm
function is meant to initialize resources within each isolated job process. Even if you have
numIdleProcesses
set, it only controls how many idle worker processes stay warm at the worker level, not at the job level. When you dispatch an agent using an
AccessToken
, LiveKit assigns the job to a process—this could be a new one or one from the idle pool. The
prewarm
function then runs inside that specific job’s process to get everything ready, like loading models or AI engines needed for the task. To help things run more efficiently, try to keep your
prewarm
function as streamlined as possible, loading only the essential resources for the job. If you find delays are still happening, you might want to increase
numIdleProcesses
so more prewarmed processes are ready to go, which can really reduce the need to create new ones on the fly. Please feel free to reach out if you’d like any more tips or help optimizing your setup—I’m here to support you! Sources: Worker options | LiveKit Docs | Node.js Agents Architecture | livekit/livekit_composite | DeepWiki | examples/src/gemini_realtime_agent.ts
b
But my numIdleProcesses = 5 and I only assign 1 agent
t
I completely understand how this can be a bit puzzling! Even with
numIdleProcesses
set to 5 and just 1 agent assigned, LiveKit might create a new process if the warmed process queue happens to be temporarily empty. This can occur because of a few reasons: • Initialization delays: Sometimes, processes aren’t fully initialized and added to the warmed queue just yet. • Readiness event: The idle pool might not have reached its target count if the readiness event (
idle_ready
) hasn’t triggered. • Immediate demand: If there aren’t any warmed processes available right when a job comes in, the system will spin up a new process to handle it. A good way to handle this is to make sure your prewarm function runs efficiently and that the system has enough time to get the idle pool ready before dispatching jobs. It also helps to keep an eye on the warmed process queue to confirm it’s maintaining the expected number of idle processes. Please feel free to reach out if you’d like any help debugging or optimizing this — I’m here to support you! Sources: livekit-agents/livekit/agents/ipc/proc_pool.py