does livekit end an agent call/session when the la...
# ask-ai
i
does livekit end an agent call/session when the last remote participant leaves? how does that process work exactly?
t
Thanks for reaching out, Ed. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks for reaching out! I’d love to help you understand how LiveKit manages sessions and rooms when participants leave. Here’s a friendly breakdown: • Default Behavior: When the last non-agent participant leaves a room, LiveKit automatically closes it. Any AI agents or programmatic participants still connected will be disconnected, and the room is removed from the server to keep things tidy. • Agent Sessions: AI agent jobs will keep running until all standard and SIP participants have left, unless you choose to shut them down manually. Typically, an
AgentSession
closes when its linked participant disconnects, but if you want to change that, you can use the
RoomInputOptions.close_on_disconnect
setting to disable this behavior. • Manual Termination: If you want to end a session right away for everyone, you can call the
deleteRoom
API. This will immediately close the room and disconnect all participants. This setup helps keep everything running smoothly by managing resources and cleaning up inactive sessions automatically. If you have any questions or want me to walk you through any part of this, just let me know—I’m here to help! Sources: Worker lifecycle | LiveKit Docs | Rooms, participants, and tracks | LiveKit Docs | examples/voice_agents/session_close_callback.py | Connecting to LiveKit | LiveKit Docs | Transferring calls | LiveKit Docs
i
ok heres a scenario im dealing with - we start the agent session with agent_session.start() and then after that (in order) we add the shutdown callback, and then we create an outbound call with create_sip_participant, and then after that we run a few functions that start room egresses, for call recording. im seeing a race condition happen where after running create_sip_participant with
wait_until_answered=True
, if the request fails and we get, for example, a 480 sip status, we see that livekit still fires a participant connected and then subsequently a participant disconnected event. because of the participant disconnected event, the room starts to shutdown (because the last remote participant left), and our room egresses which as i mentioned before come after creating a sip participant, try to fire after the server has been disconnected, leading to errors. im trying to figure out how to handle this.
t
I understand how tricky race conditions can be, so let’s walk through some helpful steps and best practices together to tackle the issue you’re facing: 1. Handle SIP Participant Failures: It’s a good idea to wrap
create_sip_participant(wait_until_answered=True)
in a try-except block. This way, you can catch errors like a 480 SIP status and take a closer look at the error details (like
sip_status_code
) to better understand what’s going on. 2. Monitor SIP State: Keep an eye on the SIP participant’s attributes, such as
sip.callStatus
, to track how the call is progressing. You can also watch for disconnection events through callbacks or changes in these attributes. 3. Prevent Premature Room Shutdown: To avoid issues, try not to delete the room immediately after a participant disconnects. Instead, use a session manager to coordinate cleanup, making sure no agent sessions or async tasks are still running before you call
delete_room
. 4. Order of Operations: Starting the agent session before calling
create_sip_participant
helps ensure you don’t miss any initial interactions. Also, make sure room egresses begin only after the SIP participant has connected successfully. 5. Await Cleanup: Before deleting the room, double-check that all agent sessions are properly closed (for example, with
await session.aclose()
) and that any background tasks have stopped. Following these steps should make managing the room lifecycle smoother and help prevent errors from shutting things down too soon. If anything isn’t clear or you’d like more help, please don’t hesitate to reach out—I’m here for you! Sources: examples/voice_agents/realtime_joke_teller.py | agent.py | test/lktest/livekit.go | CHANGELOG.md | Docs::Agents
i
thanks. the problem is that a 480 natively, on livekit's side, fires a participant connected and a participant disconnected event, thats not something im doing myself. so the participant disconnected event natively causes livekit to start shutting down the room
t
To help you prevent LiveKit from shutting down the room when a SIP participant encounters a 480 status and triggers participant connected and disconnected events, here are some friendly strategies you can try: 1. Keep a Persistent Standard Participant: It’s a good idea to have at least one Standard or Ingress participant, like a bot or agent, stay in the room. This way, the room won’t close automatically when SIP participants disconnect. 2. Keep an Eye on Participant Events: You can use the
participant_disconnected
event to see if any Standard or Ingress participants are still around. If none are left, you might want to reconnect someone or take steps to keep the room alive. 3. Use Timeouts Wisely: Setting up
departure_timeout
or
empty_timeout
on the server side can delay the room closing. This gives you some breathing room to bring a Standard participant back if needed. 4. Helpful Best Practices: Consider running an AI agent as a Standard participant to keep the room active. It’s best not to rely only on SIP participants since they can be temporary and affected by telephony protocols. Following these tips should make managing your room’s lifecycle smoother and help avoid unexpected shutdowns due to SIP participant issues. If you have any questions or want to explore this further, I’m here to help! Sources: Docs::Telephony | Connecting to LiveKit | LiveKit Docs | livekit-ffi/protocol/participant.proto | Making outbound calls | LiveKit Docs | livekit-protocol/livekit/protocol/sip.py
i
when livekit ends the call after the last remote participant disconnects, what does it do exactly? does it run: 1.
await ctx.wait_for_playout()
to let the agent finish its speech. 2. then
await session.drain()
to make sure all pending and then deletes the room?
t
I understand that managing the call termination process can feel a bit tricky, so I’m here to help guide you through it! LiveKit doesn’t automatically run
ctx.wait_for_playout()
,
session.drain()
, or delete the room when the last remote participant disconnects. These steps need to be handled explicitly in your application logic. Here’s a friendly walkthrough of the recommended sequence for gracefully ending a call: 1. Await Playout: Use
await ctx.wait_for_playout()
to make sure the agent finishes speaking before moving forward. 2. Shutdown Session: Call
session.shutdown()
, which will internally call
session.drain()
to wrap up all ongoing tasks smoothly. 3. Delete Room: Use the
delete_room
API to close the room and remove it from the server. Just a quick note: while
session.drain()
isn’t triggered automatically on its own, it’s included as part of the cleanup when you call
session.shutdown()
with draining enabled. Also, deleting the room is a manual step unless you’ve set up
delete_room_on_close
. If any part of this feels unclear or if you’d like a hand implementing these steps, please don’t hesitate to reach out—I’m here to support you! Sources: livekit-agents/livekit/agents/voice/agent_session.py | Agent speech and audio | LiveKit Docs | Agents telephony integration | LiveKit Docs | Inside a session | LiveKit Docs
i
when the last remote participant leaves, livekit natively ends the call right? what exactly does it do in that shutdown process
t
When the last remote participant leaves, LiveKit gently begins a shutdown process with these thoughtful steps: 1. Departure Timeout: LiveKit waits for a brief moment (called the departure timeout) to give any participants a chance to reconnect. 2. Room Closure: If no one rejoins before this timeout ends, the room is closed. This carefully triggers cleanup actions like removing all participants, stopping tracks, and notifying services. 3. Manual Closure Option: If you prefer, you can also manually close the room right away using the
deleteRoom
API, which disconnects everyone and removes the room from the server. This approach helps keep things running smoothly during brief disconnections while making sure resources are managed well when a room is no longer in use. If you’d like, I’m here to walk you through any part of this in more detail! Sources: Job lifecycle | LiveKit Docs | Inside a session | LiveKit Docs | server/agent.py | Rooms, participants, and tracks | LiveKit Docs | pkg/rtc/room.go