how to count the participants on the shutdown call...
# ask-ai
l
how to count the participants on the shutdown callback
t
Thanks for reaching out, Rajadurai. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — I’m responding to your question about counting participants during the shutdown callback. You can’t rely on the in-memory
ctx.room
to get an accurate participant list during shutdown. Instead, create a
LiveKitAPI
client in the shutdown callback and call the Room Service
list_participants
method, then count the returned participants. Suggested steps 1. Create a
LiveKitAPI
instance with your server URL, API key, and API secret. 2. Call
room.list_participants(...)
for the room you want to inspect. 3. Count the length of
response.participants
. 4. Log or act on the participant count, and close the API client. Example (Python, async)
Copy code
async def on_shutdown():
    lkapi = api.LiveKitAPI(
        os.getenv("LIVEKIT_URL"),
        os.getenv("LIVEKIT_API_KEY"),
        os.getenv("LIVEKIT_API_SECRET"),
    )
    try:
        response = await lkapi.room.list_participants(
            api.ListParticipantsRequest(room=ctx.room.name)
        )
        participant_count = len(response.participants)
        <http://logger.info|logger.info>(f"Room {ctx.room.name} has {participant_count} participants during shutdown")
    except Exception as e:
        logger.error(f"Failed to list participants during shutdown: {e}")
    finally:
        await lkapi.aclose()

# Register the shutdown callback
ctx.add_shutdown_callback(on_shutdown)
If you’d like, I can: • Show a synchronous variant (if you’re not using async). • Add filtering (e.g., only count participants with a specific role or metadata). • Help place this into your existing shutdown flow if you share how you currently register callbacks. Sources: Python Agents: Handling exceptions in your entrypoint | LiveKit | SIP Lifecycle Management Agent | LiveKit Documentation | Job lifecycle | LiveKit Documentation