In livekit-agents 1.2.2, what's the correct way to...
# ask-ai
j
In livekit-agents 1.2.2, what's the correct way to gracefully + shutdown an agent when the main participant disconnects? Should + we use
ctx.shutdown()
,
session.shutdown()
, or something else?
t
Thanks for reaching out, Albert. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To gracefully shut down an agent in livekit-agents 1.2.2 when the main participant disconnects, you have several options depending on your requirements: 1. Automatic Shutdown (Recommended): The
AgentSession
automatically handles participant disconnection by default. The session will close automatically when the linked participant disconnects with reasons like
CLIENT_INITIATED
,
ROOM_DELETED
, or
USER_REJECTED
. This behavior is controlled by the
close_on_disconnect
option:
Copy code
session = AgentSession(
    stt=deepgram.STT(),
    llm=openai.LLM(),
    tts=cartesia.TTS(),
    vad=silero.VAD.load(),
)

# Default behavior - session closes automatically on participant disconnect
await session.start(agent=MyAgent(), room=ctx.room)
You can disable this automatic behavior by setting
RoomInputOptions.close_on_disconnect
to
False
. 2. Manual Session Closure: If you need manual control over session closure, use `session.aclose()`:
Copy code
# Close the agent session gracefully
await session.aclose()
3. Job Context Shutdown: Use
ctx.shutdown()
when you want to disconnect the agent from the room entirely:
Copy code
# Disconnect from the room
ctx.shutdown(reason="Session ended")
4. Complete Room Termination: If you want to end the session for everyone, you can delete the room when the session is closed:
Copy code
ctx.delete_room()
Recommended Approach: For most use cases, rely on the automatic session closure behavior, which closes the agent session gracefully when the linked participant disconnects. If you need custom cleanup logic, you can add shutdown callbacks using
ctx.add_shutdown_callback()
to handle any necessary cleanup during shutdown. Sources: livekit-agents/livekit/agents/ipc/job_proc_lazy_main.py | Job lifecycle | LiveKit Docs