famous-area-25335
08/31/2025, 6:55 AMtall-airline-16756
08/31/2025, 6:55 AMtall-airline-16756
08/31/2025, 6:55 AMRoomEvent.Disconnected event from the LiveKit client SDK. This event fires whenever someone leaves the room, so your app can jump in and handle things smoothly.
Here’s a quick example in JavaScript/TypeScript:
room.on(RoomEvent.Disconnected, () => {
console.log("User disconnected from the room");
// You can do cleanup or update the UI here
});
And for native platforms:
• Swift: Just use the room(_:didUpdateConnectionState:from:) delegate method and watch for the state .disconnected.
• Android (Kotlin/Java): Keep an eye on the RoomEvent.Disconnected event.
If you want me to walk you through more examples or details for a particular platform, just let me know—I’m here to help!
Sources: avatars/hedra/education_avatar/education-frontend/components/app.tsx | components/app.tsx | Multiplatform/Controllers/RoomContext.swift | livekit-android-test/src/test/java/io/livekit/android/room/RoomMockE2ETest.... | livekit-agents/livekit/agents/voice/room_io/room_io.pyfamous-area-25335
08/31/2025, 6:56 AMtall-airline-16756
08/31/2025, 6:56 AMparticipant_left webhook event whenever someone leaves a room. Here’s a simple way to get it going:
1. Enable Webhooks: Set the webhook_url in your LiveKit server configuration (livekit.yaml) to point to your server’s endpoint. Don’t forget to add a webhook_secret to keep things secure.
2. Listen for the participant_left Event: Your server should be ready to handle POST requests at that webhook URL. The event payload will give you useful info like participant_identity, room_name, and disconnect_reason.
3. Verify Webhook Signature: Use the webhook_secret to check the X-LiveKit-Signature header, so you know the request is legit.
Here’s a quick example in Python to help you get started:
import hmac
from flask import Flask, request, jsonify
app = Flask(__name__)
WEBHOOK_SECRET = "your-webhook-secret"
@app.route('/livekit-webhooks', methods=['POST'])
def handle_webhook():
signature = request.headers.get('X-LiveKit-Signature')
body = request.get_data()
# Verify signature
expected = hmac.new(WEBHOOK_SECRET.encode(), body, 'sha256').hexdigest()
if not hmac.compare_digest(expected, signature):
return 'Invalid signature', 401
data = request.json
if data['event'] == 'participant_left':
print(f"Participant {data['participant_identity']} left room {data['room_name']}")
# You can do cleanup, logging, or analytics here
return jsonify(success=True)
If you’d like, I’m happy to help with more details or examples tailored to your server setup—just let me know!
Sources: livekit-plugins/livekit-plugins-google/livekit/plugins/google/beta/realtime... | Multiplatform/Controllers/RoomContext.swift | livekit-android-test/src/test/java/io/livekit/android/room/RoomMockE2ETest....famous-area-25335
08/31/2025, 6:58 AMtall-airline-16756
08/31/2025, 6:59 AMAgentSession fires a close event when the session ends, including if a user disconnects. You can catch this event to stop TTS playback and tidy things up. For example:
@session.on("close")
def on_close(ev: CloseEvent):
print(f"Agent Session closed, reason: {ev.reason}")
# Here’s where you can do cleanup or other tasks
1. Stop TTS Playback and Close the Session: If you want to manually stop TTS playback and close the session, just call session.aclose(). This makes sure everything gets cleaned up properly. Like this:
await session.aclose()
1. Automatic Closure: By default, RoomInputOptions.close_on_disconnect is set to True. This means it automatically stops TTS playback and closes the session when the user disconnects. But if you want to handle it yourself, you can set it to False and add your own logic.
If anything’s unclear or you’d like more examples, just let me know—I’m happy to help!
Sources: agents/src/voice/room_io/room_io.ts | livekit-agents/livekit/agents/voice/agent_activity.py | basics/exit_message.py | How to capture real-time agent transcriptions during conversationsfamous-area-25335
08/31/2025, 7:02 AMtall-airline-16756
08/31/2025, 7:02 AMAgentSession, tweak the VoiceOptions to stop multiple voices from playing at once. For example:
session = AgentSession(\n allow_interruptions=False,\n discard_audio_if_uninterruptible=True,\n min_interruption_duration=0.5,\n)
1. Use Turn Detection: Set up turn_detection so the system knows when the user has stopped talking and it's the agent's turn to respond. You can choose between vad (voice activity detection) or stt (speech-to-text) depending on what fits your needs.
2. Clean Up Smoothly: Don't forget to add shutdown callbacks to tidy things up and close sessions properly:
ctx.add_shutdown_callback(cleanup)
If you want me to walk you through any of these steps or need more examples, just let me know—I’m here to help!
Sources: Job lifecycle | LiveKit Docs | examples/other/transcription/multi-user-transcriber.py | Quotas and limits | LiveKit Docs | Anatomy of an Agent | LiveKit Docs | Inside a session | LiveKit Docsfamous-area-25335
08/31/2025, 7:03 AMtall-airline-16756
08/31/2025, 7:04 AMaclose() method that takes care of canceling tasks and closing sessions neatly. Here’s a quick example:
async def aclose(self):
await utils.aio.cancel_and_wait(*self._tasks) # Cancel active tasks
await asyncio.gather(*[self._close_session(session) for session in self._sessions.values()]) # Close sessions
self.ctx.room.off("participant_connected", self.on_participant_connected)
self.ctx.room.off("participant_disconnected", self.on_participant_disconnected)
1. Ensure Cleanup with `try`/`finally`: Wrapping your session logic in a `try`/`finally` block is a great way to make sure cleanup always happens, no matter what:
try:
session = AgentSession()
await session.start(agent=MyAgent(), room=ctx.room)
await shutdown_future_or_room_empty()
finally:
if session:
await session.aclose()
1. Resource-Specific Cleanup: For individual resources, defining a cleanup method that can be safely called multiple times is super helpful:
async def cleanup(self):
if self.livekit_api:
await self.livekit_api.aclose()
self.livekit_api = None
1. Combine Session Close Events with Job Shutdown: You can use the close event for quick cleanup and ctx.add_shutdown_callback() to handle any final tasks gracefully:
@session.on("close")
def on_close_session(ev: CloseEvent):
print(f"Session closed: {ev.reason}")
ctx.add_shutdown_callback(save_user_state_to_db)
If you want me to walk you through any part of this or need more examples, just let me know—I’m here to help!
Sources: livekit-agents/livekit/agents/voice/agent_session.py | agent.py | Inside a session | LiveKit Docsfamous-area-25335
08/31/2025, 7:05 AMtall-airline-16756
08/31/2025, 7:05 AMctx.shutdown(reason="User disconnected") inside your entrypoint function. This lets the worker know it should stop taking new jobs and start shutting down.
2. Graceful Draining: The worker will then automatically stop accepting new jobs and wait for any active ones to finish up. If you want, you can tweak how long it waits by setting the drain_timeout in WorkerOptions like this:
opts = WorkerOptions(\n entrypoint_fnc=entrypoint,\n drain_timeout=60 # seconds\n)
1. Run Cleanup: You can also add cleanup tasks that run after shutdown by using `ctx.add_shutdown_callback()`:
async def my_cleanup():\n # Perform cleanup actions\n pass\n\nctx.add_shutdown_callback(my_cleanup)
So, once ctx.shutdown() is called, the worker won’t accept any new jobs and will run your cleanup tasks. If you want me to walk you through this with more examples or have any questions, just let me know—I’m here to help!
Sources: Job lifecycle | LiveKit Docs | examples/voice_agents/realtime_joke_teller.py | Deploying to custom environments | LiveKit Docs | Worker options | LiveKit Docs | agents/src/job.tsfamous-area-25335
08/31/2025, 7:10 AMtall-airline-16756
08/31/2025, 7:11 AMctx.shutdown(reason="User disconnected"). This gently tells the worker to stop accepting new jobs and start shutting down.
2. Use Shutdown Callbacks: You can register a cleanup function with ctx.add_shutdown_callback(). This way, your cleanup runs right after the user disconnects but before the job process ends. For example:
async def my_cleanup():
# Perform cleanup actions
pass
ctx.add_shutdown_callback(my_cleanup)
1. Set Drain Timeout: Make sure to set the drain_timeout in WorkerOptions so there’s enough time for your final function to finish smoothly. Like this:
opts = WorkerOptions(
entrypoint_fnc=entrypoint,
drain_timeout=60 # seconds
)
1. Leverage Load-Based Rejection: If you want, you can add a custom load_fnc to politely reject new jobs when the worker is busy finishing up. Here’s a quick example:
def compute_load(worker):
return min(len(worker.active_jobs) / 10, 1.0)
opts = WorkerOptions(
load_fnc=compute_load,
load_threshold=0.9,
)
These handy steps help make sure your worker finishes its final tasks without taking on anything new. If you want me to walk you through any part or share more examples, just let me know—I’m here to help!
Sources: Deployment and scaling | LiveKit Docs | livekit-agents/livekit/agents/worker.py | Job lifecycle | LiveKit Docs | Worker options | LiveKit Docs | Deploying to custom environments | LiveKit Docsfamous-area-25335
08/31/2025, 7:37 AMtall-airline-16756
08/31/2025, 7:38 AMdef compute_load(worker):\n return min(len(worker.active_jobs) / 10, 1.0)
1. `load_threshold`: This sets the maximum load the worker will accept before it stops taking new jobs. The default is 0.7 (or 70%). If the load goes over this, the worker politely says no to new jobs and lets the server send them elsewhere.
When the load is too high, the worker keeps working on the jobs it already has but won’t take on more, which helps handle busy times smoothly. If you’re using autoscaling, it’s a good idea to set it to add more workers before hitting the threshold—like scaling up at 0.5 if your load_threshold is 0.7.
If you want me to walk you through this more or need some examples, just let me know—I’m happy to help!
Sources: Worker options | LiveKit Docs | Deploying to custom environments | LiveKit Docs | README.mdfierce-answer-55580
08/31/2025, 8:18 AMtall-airline-16756
08/31/2025, 8:18 AMlen(worker.active_jobs)) and divides that by 10, so the load is a number between 0 and 1. Plus, it uses min to make sure the load never goes above 1.0, even if there are more than 10 jobs running.
2. `opts = WorkerOptions(...)`: Here’s where we set up the worker with some options:
◦ `load_fnc=compute_load`: This tells the worker to use our custom load function to keep track of how busy it is.
◦ `load_threshold=0.9`: This means the worker will stop taking new jobs once it hits 90% of its capacity (so, a load of 0.9 or higher).
So, with this setup, the worker can comfortably handle up to 9 active jobs before it starts saying “hold on, I’m full!” If anything’s unclear or you want to dive deeper, just let me know—I’m here to help!fierce-answer-55580
08/31/2025, 8:19 AMtall-airline-16756
08/31/2025, 8:19 AMfrom livekit import WorkerOptions
# Define a custom load function
def compute_load(worker):
# Calculate load as the ratio of active jobs to a maximum capacity of 10
return min(len(worker.active_jobs) / 10, 1.0)
# Configure WorkerOptions with the custom load function and threshold
opts = WorkerOptions(
load_fnc=compute_load, # Use the custom load function
load_threshold=0.9 # Reject new jobs if load reaches 90%
)
# Example worker entrypoint
def entrypoint(ctx):
print("Worker started")
# Simulate job processing
async def process_job():
print("Processing job...")
await asyncio.sleep(5) # Simulate job duration
print("Job completed")
ctx.add_shutdown_callback(lambda: print("Worker shutting down"))
# Main loop to simulate job handling
while True:
if len(ctx.worker.active_jobs) >= 10:
print("Worker at capacity, rejecting new jobs")
break
await process_job()
# Start the worker with the configured options
if __name__ == "__main__":
from livekit import Worker
Worker(entrypoint, opts).run()
This snippet shows you how to set up and use load-based rejection in a LiveKit worker. Basically, the worker will politely say “no thanks” to new jobs once it hits 90% of its capacity (that’s 9 out of 10 active jobs). If you want me to walk you through it more or need extra examples, just let me know—I’m here to help!fierce-answer-55580
08/31/2025, 8:21 AMtall-airline-16756
08/31/2025, 8:21 AMfrom livekit import WorkerOptions, agents\n\n# Define a custom load function\ndef compute_load(worker):\n # Calculate load as the ratio of active jobs to a maximum capacity of 10\n return min(len(worker.active_jobs) / 10, 1.0)\n\n# Configure WorkerOptions with the custom load function and threshold\nopts = WorkerOptions(\n load_fnc=compute_load, # Use the custom load function\n load_threshold=0.9 # Reject new jobs if load reaches 90%\n)\n\n# Define your entrypoint function\ndef start_session(ctx):\n print(\"Session started\")\n # Add your session logic here\n pass\n\n# Define a prewarm function (optional)\ndef prewarm():\n print(\"Worker prewarming...\")\n # Add any pre-initialization logic here\n pass\n\n# Run the worker\nif __name__ == \"__main__\":\n agents.cli.run_app(\n agents.WorkerOptions(\n entrypoint_fnc=start_session,\n prewarm_fnc=prewarm,\n agent_name=\"Evi\",\n ws_url=API_URL,\n api_key=API_KEY,\n api_secret=API_SECRET,\n load_fnc=compute_load,\n load_threshold=0.9\n )\n )
So, this example ties your compute_load function right into the worker setup. Basically, the worker will politely say “no thanks” to new jobs once it hits 90% capacity (which is 9 active jobs in this case). If anything’s unclear or you want to tweak it further, just let me know—I’m happy to help!fierce-answer-55580
08/31/2025, 8:27 AMtall-airline-16756
08/31/2025, 8:28 AMjob_executor_type in WorkerOptions, but sticking with process-based execution is the default and usually the best way to go.
If you want me to walk you through anything else or have more questions about setting up your workers, just let me know—I’m here to help!
Sources: livekit-agents/livekit/agents/worker.py | Worker lifecycle | LiveKit Docs | Deploying to custom environments | LiveKit Docs