steep-balloon-41261
10/25/2025, 4:34 PMtall-airline-16756
10/25/2025, 4:34 PMtall-airline-16756
10/25/2025, 4:34 PMtall-airline-16756
10/25/2025, 4:36 PMloadFunc and loadThreshold parameters within the WorkerOptions class. These options let you set up a custom load function that controls how many concurrent jobs a worker can handle, helping you manage workload smoothly.
Here’s a friendly example to guide you:
import { Worker, WorkerOptions } from '@livekit/agents';
const workerOptions: WorkerOptions = {
agent: './agent.ts',
loadFunc: async (worker) => {
const activeJobs = worker.activeJobs.length;
const maxJobs = 9;
return activeJobs / maxJobs; // Returns load between 0 and 1
},
loadThreshold: 0.9, // Worker stops accepting new jobs when load reaches this value
};
const worker = new Worker(workerOptions);
await worker.run();
Here are some key parameters to keep in mind:
• loadFunc: This function returns the current load as a float between 0 and 1.0. You can calculate it based on how many active jobs the worker currently has.
• loadThreshold: This sets the maximum load at which the worker will still accept new jobs. For example, setting it to 0.9 means the worker will handle up to 9 jobs concurrently.
Just a couple of important notes to keep in mind:
• In LiveKit Cloud deployments, custom loadFunc and loadThreshold aren’t supported — the system uses default values based on CPU load with a threshold of 0.7.
• When you want to gracefully shut down a worker, you can use the drain() method. This stops new jobs from being accepted while allowing current jobs to finish.
With this setup, your worker will gracefully stop accepting new jobs once it reaches your specified concurrency limit, helping you maintain a balanced and efficient agent infrastructure. If you have any questions or need further help, feel free to ask—I’m here to support you!
Sources: README.md | Worker options | LiveKit Docs | livekit-agents/livekit/agents/worker.py | Worker lifecycle | LiveKit Docstall-airline-16756
10/25/2025, 6:50 PMJobContext and RoomEvent.Disconnected. Here's a friendly walkthrough on how to set this up:
import { JobContext } from '@livekit/agents-sdk';
export async function entrypoint(ctx: JobContext) {
// First, connect the agent to the room
await ctx.connect();
// Then, listen for when the room disconnects
ctx.room.on('disconnected', () => {
console.log('Room disconnected — shutting down agent');
// You can also run any cleanup tasks here if needed
ctx.shutdown(); // This starts a graceful shutdown
});
// Place your agent logic here (like processing audio or responding to events)
// When the room disconnects, the handler above will take care of shutting down
}
Here are some additional helpful options you might find useful:
• If you want to shut down when a specific participant leaves, just listen for participant_disconnected like this:
ctx.room.on('participant_disconnected', (participant) => {
console.log(`Participant ${participant.identity} left — shutting down`);
ctx.shutdown();
});
• To make sure any cleanup tasks run during shutdown, you can register them with `ctx.add_shutdown_callback()`:
ctx.add_shutdown_callback(() => {
console.log('Running cleanup before shutdown');
// This is a great spot to close files or release resources quickly
});
And a quick tip on configuration:
• If you'd like to shorten the default 60-second shutdown timeout, just adjust shutdownProcessTimeout in WorkerOptions like this:
const worker = new Worker({
agent: './agent.ts',
shutdownProcessTimeout: 10_000, // 10 seconds
});
With this setup, your worker will gracefully shut down right after the call ends or when a particular participant disconnects. If you have any questions or need further help, feel free to ask—I'm here to support you!
Sources: agents/src/worker.ts | Job lifecycle | LiveKit Docs | Operational Guidance & Best Practices | livekit/livekit_composite | DeepWik...tall-airline-16756
10/25/2025, 8:22 PMtall-airline-16756
10/25/2025, 8:49 PMctx.shutdown is executed, it gently signals the specific job process to start its graceful shutdown sequence. This includes disconnecting the agent (software participant) from the room using room.disconnect(). Just to clarify:
• This doesn’t directly reduce the count of active jobs or workers: The LiveKit server takes care of reducing active jobs as a natural result of the job ending.
• This doesn’t shut down the room: Disconnecting the agent lets other participants keep enjoying the session. The room will only close when the last non-agent participant leaves, or if you choose to explicitly use the server API’s deleteRoom method to end the room for everyone.
If you want to make sure the room is fully shut down after the agent disconnects, simply call the deleteRoom method through the server API. I hope this helps clarify things for you!
Sources: agents/src/ipc/job_proc_lazy_main.ts | livekit-agents/livekit/agents/worker.py | Job lifecycle | LiveKit Docs | pkg/service/agentservice.gotall-airline-16756
10/25/2025, 8:52 PMdeleteRoom method. This will close the room for everyone, including agents, stopping all related processes and ensuring no unnecessary workers stay active.
3. Implement Participant Disconnection Listeners
You might find it helpful to listen for when participants disconnect, and then shut down the agent session once the last human leaves. Here’s a simple example:
ctx.room.on('participant_disconnected', (participant) => {
if (ctx.room.remoteParticipants.length === 0) {
console.log('Last participant left — shutting down agent');
ctx.shutdown();
}
});
4. Configure RoomInputOptions
When you start an agent session, you can set it up to automatically delete the room when the session ends. This helps keep things tidy without extra effort:
await session.start(
agent: MyAgent(),
room: ctx.room,
room_input_options: RoomInputOptions(
delete_room_on_close: true
)
);
5. Proper Cleanup
Finally, always remember to clean up properly by calling session.aclose() to end agent sessions and free up resources. Here’s a quick example:
try {
await session.start(...);
} finally {
await session.aclose();
}
By using these approaches, you’ll ensure agent sessions close smoothly, resources are freed, and the active worker count stays just right when agents aren’t needed anymore. If you have any questions or want to walk through these steps together, I’m here for you!
Sources: Worker lifecycle | LiveKit Docs | Job lifecycle | LiveKit Docs | examples/voice_agents/realtime_joke_teller.pytall-airline-16756
10/25/2025, 9:19 PMworker.activeJobs.length after the last human disconnects can be a bit puzzling. This usually happens because of the graceful shutdown process and how LiveKit manages the job lifecycle. Let me walk you through the main points:
• Graceful Shutdown Timeout: By default, the system waits up to 60 seconds to allow a job to shut down gracefully before it’s forcefully terminated. You can adjust this timeout using the shutdownProcessTimeout parameter in WorkerOptions if you’d like to speed things up.
• Active Jobs Calculation: The count of active jobs only goes down once the job process has fully completed its shutdown, is removed from the process pool, and the runningJob property is cleared.
• Session Closure: After the last human participant disconnects, the agent session might need a bit of extra time to finish tasks like generating final responses, running shutdown hooks, and cleaning up.
• Room and Agent Coordination: The system also waits for agent participants to leave the room properly, which has a timeout of about 3 seconds.
Here are some friendly recommendations to help minimize these delays:
• Try reducing the shutdownProcessTimeout in WorkerOptions to shorten that graceful shutdown period.
• Make sure your shutdown hooks and cleanup tasks are optimized to complete quickly.
• Consider configuring session close behavior through RoomInputOptions to make the process smoother.
This delay is actually intentional—it helps ensure jobs terminate reliably and everything cleans up properly. But the great news is, you can tune these timeout settings to find the right balance between responsiveness and reliability that fits your needs. If you have any more questions or want help adjusting these settings, I’m here for you!
Sources: agents/src/worker.ts | examples/voice_agents/session_close_callback.py | Job lifecycle | LiveKit Docs | Worker lifecycle | LiveKit Docs | CHANGELOG.md