what's the intended way to close a session from ag...
# ask-ai
b
what's the intended way to close a session from agent's side (because the time is up or it was requested by the user). I still want to on_close hook to fire up
t
Thanks for reaching out, mateuszkasprowicz. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how an agent should end a session (time up or user-requested) while ensuring the on_close / on_session_end hook runs. Use a graceful shutdown on the session context so shutdown hooks run and pending work (transcripts, callbacks) can complete. • Python: call either ◦
await session.aclose()
— begins teardown and waits for completion, or ◦
session.shutdown(drain=True)
— gracefully drains pending operations. Register post-shutdown work in
on_session_end
or with
ctx.add_shutdown_callback()
. • Node.js: call
ctx.shutdown('reason')
to end the session and run registered shutdown hooks. Important: graceful shutdown is required for the hooks to execute — forcible process termination will not run them. Would you like example snippets for your codebase (Python or Node.js)? Sources: Job lifecycle | LiveKit docs | Observability data hooks | LiveKit docs
b
so what's the difference between aclose() and shutdown() in practice. give me examples
t
You're asking for the practical difference between
aclose()
and
shutdown()
and examples. Short answer: both perform a graceful end of a session, but they differ in intent and behavior: •
aclose()
— immediate async teardown you await. Use when you want to begin teardown now and wait until the session has fully closed and all shutdown hooks finished. •
shutdown()
— requests a graceful shutdown (optionally draining work) but is more of a controlled/ordered shutdown signal; it may return immediately and let the session drain before full close (depending on args/impl). Use when you want to ask the session to stop (optionally finish pending work) without necessarily blocking until every finalization step completes. Python examples 1) Use
await session.aclose()
when you need to synchronously finish teardown and then continue:
Copy code
# immediate teardown, wait until complete so on_session_end runs before next steps
await session.aclose()
# safe to access persisted transcripts or continue shutdown-dependent logic here
2) Use
session.shutdown(drain=True)
when you want the session to finish pending work but not necessarily block here:
Copy code
# ask session to gracefully stop and drain pending operations
session.shutdown(drain=True)
# your code can continue; shutdown callbacks will run as session drains
Node.js examples 1) Immediate shutdown-and-wait pattern (if your API awaits shutdown):
Copy code
// ensure shutdown completes before proceeding
await ctx.shutdown('time-up');
// ctx.shutdown runs registered shutdown hooks and disconnects the agent
2) Fire-and-allow-drain pattern:
Copy code
// signal shutdown and let the session drain while this thread continues
ctx.shutdown('user-requested');
// don't await — session will run shutdown hooks and finalize in background
When to choose which • Use
aclose()
/ awaiting
shutdown()
when subsequent code depends on completed cleanup (transcripts saved, reports generated). • Use non-blocking
shutdown()
(or
shutdown(drain=True)
without awaiting) when you want the session to finish naturally but don't need to block the caller. Note: shutdown hooks (like
on_session_end
/ registered shutdown callbacks) run only on graceful shutdown. If you want sample full handlers or snippets wired to
on_session_end
, tell me which language and I’ll provide a compact example.
b
I'm still not sure what's the difference
t
Thanks — let’s make this concrete. Think of shutdown() as "please stop, finish what you're doing, then close" and aclose() as "begin closing now and wait until everything is finished." Key practical differences • Intent ◦ shutdown(): a signal you send to the session to begin a graceful stop (optionally drain pending work). It’s a request to stop, not necessarily a synchronous wait. ◦ aclose(): an async teardown you await — it initiates close and suspends until the session is fully closed and all shutdown hooks have run. • Blocking behavior ◦ shutdown(): may return immediately (fire-and-forget) or return quickly while the session continues to drain in background. ◦ aclose(): returns only after teardown is complete. • Use cases ◦ Use shutdown() when you want the session to stop but your caller can continue without waiting (e.g., signal time-up and let background work finish). ◦ Use aclose() when you need to wait for final state (transcripts saved, reports generated) before proceeding. Concrete examples Python 1) Need final data now — wait for completion:
Copy code
await session.aclose()
# safe: on_session_end has completed, transcripts persisted
2) Signal graceful stop and continue immediately:
Copy code
session.shutdown(drain=True)
# returns quickly; session will run on_session_end while your code continues
Node.js 1) Wait for shutdown to finish:
Copy code
await ctx.shutdown('time-up');
// shutdown hooks finished; safe to read persisted outputs
2) Signal and continue:
Copy code
ctx.shutdown('user-requested');
// non-blocking: hooks run while this call returns immediately
Which to pick • If subsequent code depends on the session being fully closed or on outputs produced by shutdown hooks → use aclose() / await shutdown(). • If you only need to request the session to stop and don’t need to block → call shutdown() without awaiting. If you tell me which language and whether you need to wait for transcripts/reports before continuing, I’ll give a short copy-paste example wired to your hooks.
b
async def remove_participant(_session_: AgentSession) -> None: job_ctx = get_job_context() participant_identity = session.userdata.participant_identity if participant_identity: await job_ctx.api.room.remove_participant( RoomParticipantIdentity(room=job_ctx.room.name, identity=participant_identity) ) _else_: logger.warning("Participant identity not found, skipping removal") session.shutdown() so is this a correct order to remove a participant and finish the session immediately? (keep in mind I have a close on disconnect == True)
t
You're almost correct — remove participant first, then request shutdown. A couple small notes and a tightened example. Why this order works • Removing the participant before shutdown ensures the room state is updated while your agent is still connected and able to call the Room API. • Calling
_session_.shutdown()
after removal requests a graceful session end so your on_close/on_session_end hook runs (assuming graceful shutdown, not a forced process kill). Recommended improvements • Await the remove call to ensure it succeeded before calling shutdown. • If you need to wait until the shutdown and hooks finish (e.g., to read persisted transcripts), use
await _session_.aclose()
instead of the non-blocking
shutdown()
. Tightened example (async, Python):
Copy code
async def remove_participant(_session_: AgentSession) -> None:
    job_ctx = get_job_context()
    participant_identity = _session_.userdata.participant_identity

    if participant_identity:
        await job_ctx.api.room.remove_participant(
            RoomParticipantIdentity(room=job_ctx.room.name, identity=participant_identity)
        )
    else:
        logger.warning("Participant identity not found, skipping removal")

    # Option A: signal graceful shutdown and continue immediately
    _session_.shutdown()

    # Option B: wait for full teardown and for on_session_end to complete
    # await _session_.aclose()
Choose Option A if you want to fire-and-forget and let hooks run in background. Choose Option B if subsequent logic depends on shutdown completion.
b
is there some waiting period after removing a user from a room and the actual closure? I see some delay I have these in my RoomOptions _close_on_disconnect_=True, _delete_room_on_close_=True,
t
You're seeing a delay because several async steps happen after you remove a participant and request session/room shutdown. Here’s what to expect and how to make behavior deterministic. What causes the delay • remove_participant is an API call that signals LiveKit to disconnect that participant; the server then performs disconnect cleanup asynchronously. • With close_on_disconnect = True the room will close only after all participants are fully disconnected; that disconnect completion can take a short moment to propagate. • With delete_room_on_close = True the room deletion occurs after the room closes, so you’ll see an additional short delay while the close finishes and deletion runs. • Shutdown hooks (on_close / on_session_end) run only when the session shuts down gracefully — they won’t run instantly if you signal shutdown but the session still needs to drain or wait for disconnects. How to make it deterministic • Await the removal call: ensure the API call completes before proceeding. ◦ await job_ctx.api.room.remove_participant(...) • If you need to be certain all shutdown hooks and final persistence are finished before continuing, await aclose() instead of calling shutdown() fire-and-forget: ◦ await session.aclose() • If you only need to request stop and can allow background finalization, call session.shutdown() (non-blocking) and let hooks run asynchronously. Practical pattern (Python) • Remove participant and wait: ◦ await remove_participant(...) • Then: ◦ If you must wait for on_session_end/transcripts: await session.aclose() ◦ If not: session.shutdown() Notes • Short delays (seconds) are normal due to async disconnect propagation and room-close/delete sequencing. • If you need to detect when the room is actually deleted, poll the room state or wait for whatever post-close signal your system uses (and use aclose() if you control the agent lifecycle and need to block until completion). Would you like a tiny copy-paste example that waits for full teardown (remove -> await aclose) for your exact handler?