How do i call a function in agent.py when the user...
# ask-ai
c
How do i call a function in agent.py when the user has left the room?
t
Thanks for reaching out, Bryce. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! If you want to call a function in
agent.py
when a user leaves the room, you can tap into the
participant_disconnected
event on the room object. This event fires whenever someone leaves, and you can set up a handler function to react to it. Here’s an example:
Copy code
async def entrypoint(ctx: JobContext):
    session = AgentSession()

    def on_participant_left(participant: rtc.Participant):
        print(f"Participant {participant.identity} has left the room")
        # This is where you can call your custom function
        my_custom_function()

    ctx.room.on("participant_disconnected", on_participant_left)

    await session.start(agent=MyAgent(), room=ctx.room)
On the other hand, if your goal is to close the agent session when someone leaves, you can listen for the
session.on("close")
event. By default, the session closes automatically when the linked participant disconnects, which triggers the
close
event. Here’s how that looks:
Copy code
@session.on("close")
async def on_session_close(ev: CloseEvent):
    print(f"Session closed, reason: {ev.reason}")
    await my_cleanup_function()
Feel free to ask if you want me to explain anything further or help out with your code! Sources: How to capture real-time agent transcriptions during conversations | agent/game_host.py | examples/voice_agents/inactive_user.py