When last participant leaves the room, I want to d...
# ask-ai
j
When last participant leaves the room, I want to disconnect the agent too.. clean up everything and reset to setup fresh session when the user joins again
t
Thanks for reaching out, meetakshay99. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
LiveKit automatically handles the scenario where the last participant leaves the room. When this happens, the room will automatically close, and any remaining agents will be disconnected. This ensures that everything is cleaned up and reset for a fresh session when a new participant joins again. You don't need to implement any additional logic for this behavior. Sources: Anatomy of an Agent | LiveKit Docs | Worker lifecycle | LiveKit Docs
j
What should my cleanup code look like in that case and where should the cleanup code be called from?
t
To handle cleanup when a LiveKit room closes, you can use shutdown hooks or specific cleanup methods depending on your implementation. Here are some examples: • Using Shutdown Hooks: You can add a shutdown callback in your agent's code to perform cleanup tasks. For example: `async def entrypoint(ctx: JobContext): async def my_shutdown_hook(): # save user state or perform cleanup ... ctx.add_shutdown_callback(my_shutdown_hook)`This hook will be called when the session ends, and you can use it to clean up resources or save states. • Adjusting Timeout: Shutdown hooks are expected to complete within a short time (default 60 seconds). You can adjust this timeout using the
shutdown_process_timeout
parameter in
WorkerOptions
. • Manual Disconnection: You can manually disconnect from a room using:
ctx.shutdown(reason="Session ended")
SDK-Specific Cleanup: If you are using the Android SDK, you can use the
close()
method for objects or the
cleanUp()
method for E2EEManager to release resources. Let me know if you need further clarification or assistance with implementing this! Sources: Inside a session | LiveKit Docs | close | cleanUp