i try to make the room closed after the participan...
# ask-ai
p
i try to make the room closed after the participant join but i get this error i try this but i get this error ception was never retrieved future: <Task finished name='Task-292' coro=<entrypoint.<locals>.on_participant_disconnected_wrapper.<locals>.on_participant_disconnected_async() done, defined at /home/client/astroTest/voice-pipeline-agent-python/main.py:130> exception=AttributeError("'Room' object has no attribute 'GetParticipants'")> Traceback (most recent call last): File "/home/client/astroTest/voice-pipeline-agent-python/main.py", line 132, in on_participant_disconnected_async participants = ctx.room.GetParticipants() ^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'Room' object has no attribute 'GetParticipants'. Did you mean: 'num_participants'? {"pid": 47988, "job_id": "AJ_nHBHzuYAWF8z"} 2025-08-03 032245,153 - DEBUG livekit.agents - session closed {"reason": "participant_disconnected", "error": null, "pid": 47988, "job_id": "AJ_nHBHzuYAWF8z"} 2025-08-03 032306,120 - INFO livekit.agents - process exiting {"reason": "", "pid": 47988, "job_id": "AJ_nHBHzuYAWF8z"} 2025-08-03 032306,120 - DEBUG livekit.agents - shutting down job task {"reason": "", "user_initiated": false, "pid": 47988, "job_id": "AJ_nHBHzuYAWF8z"} 2025-08-03 032306,124 - WARNING livekit - livekit:rtc engine453livekit:rtc_engine - received session close: "signal client closed: \"stream closed\"" UnknownReason Resume {"pid": 47988, "job_id": "AJ_nHBHzuYAWF8z"} the code is like this # Handler wrapper because .on() can't register async callbacks directly def on_participant_disconnected_wrapper(participant): async def on_participant_disconnected_async(participant): logger.info(f"Participant {participant.identity} disconnected.") participants = ctx.room.GetParticipants() non_agent_participants = [p for p in participants if p.role != "agent"] if len(non_agent_participants) == 0: logger.info(f"Only agent remains in room {ctx.room.name}, closing room.") await ctx.room.CloseIfEmpty() asyncio.create_task(on_participant_disconnected_async(participant)) ctx.room.on("participant_disconnected", on_participant_disconnected_wrapper)
t
Thanks for reaching out, Yassine. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
The error occurs because the 'Room' object in your code does not have a method called
GetParticipants
. Instead, you should use the LiveKit API's
list_participants
method to retrieve participants in a room. Here's how you can handle this: 1. Retrieve Participants: Use the
list_participants
method to fetch all participants in the room:
Copy code
from livekit import api

async def fetch_room_participants(room_name: str):
    async def _fetch(lkapi):
        list_request = api.ListParticipantsRequest(room=room_name)
        participants_response = await lkapi.room.list_participants(list_request)
        return [
            {
                "identity": participant.identity,
                "name": participant.name,
                "state": participant.state,
                "joined_at": participant.joined_at,
                "metadata": participant.metadata,
                "sid": participant.sid
            }
            for participant in participants_response.participants
        ]
    return await with_livekit_api(_fetch)
2. Close the Room: If only agents remain, use the
delete_room
method to close the room:
Copy code
from livekit import api

async def delete_livekit_room(room_name: str):
    async def _delete(lkapi):
        delete_request = api.DeleteRoomRequest(room=room_name)
        await lkapi.room.delete_room(delete_request)
        return True
    return await with_livekit_api(_delete)
Example: Check participants and close the room if only agents are present:
Copy code
participants = await fetch_room_participants("my_room")
if all(p["state"] == "AGENT" for p in participants):
    await delete_livekit_room("my_room")
This approach ensures you can manage room closure effectively based on participant presence. Let me know if you need further assistance! Sources: mcp/server.py | Inside a session | LiveKit Docs
p
how to stop the session directly ffor example if the user disconnect we will stop the session
t
Hey there! If you want to stop a session right away when a user disconnects, you can use the
session.on("close")
event handler in the LiveKit Python SDK. This handy feature lets you catch when the session is closing and take immediate action, like deleting the room. Here’s a simple example to get you started:
Copy code
import asyncio
import logging
from livekit.agents import AgentSession, JobContext, WorkerOptions, cli
from livekit.plugins import deepgram, openai, silero

logger = logging.getLogger("my-worker")
logger.setLevel(<http://logging.INFO|logging.INFO>)

class MyAgent(Agent):
    def __init__(self):
        super().__init__(instructions="You are a helpful assistant.")

async def entrypoint(ctx: JobContext):
    session = AgentSession(
        stt=deepgram.STT(),
        llm=openai.LLM(),
        tts=silero.TTS(),
        vad=silero.VAD.load(),
    )

    # Start the session with the agent
    await session.start(agent=MyAgent(), room=ctx.room)

    @session.on("close")
    def on_close(ev):
        <http://logger.info|logger.info>(f"Session closed. Reason: {ev.reason}")
        # Delete the room to stop the session immediately
        ctx.delete_room()

cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
Just a couple of important things to keep in mind:Event Handling: The
session.on("close")
event fires when the session is shutting down. You can peek at the reason for closure and act accordingly. • Room Deletion: Calling
ctx.delete_room()
will stop the session right away when the user disconnects. This setup helps make sure your session wraps up as soon as someone leaves. If you want me to walk you through any part of this or have other questions, just let me know—I’m here to help!