how long will agent remain in the room when partic...
# ask-ai
m
how long will agent remain in the room when participant leave ?
t
Thanks for reaching out, Anigilaje. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
When a participant leaves a LiveKit room, the agent and egress participants remain in the room for a short period of time. However, the room will automatically close when the last non-agent participant has left, and any remaining agents will be disconnected. If you want to ensure the agent leaves immediately, you can delete the room when the participant exits. Sources: Anatomy of an Agent | LiveKit Docs
m
can i set a time limi for when agent should remain in the room. like can the agent remain in the room because participant can join 5 mins later.
t
Yes, you can set a time limit for how long the agent should remain in the room after a participant leaves. This can be done using the
departureTimeout
property in the
CreateOptions
interface. This property allows you to specify the number of seconds to keep the room open after the last participant leaves, which is useful for giving participants a grace period to re-join. Sources: CreateOptions | LiveKit JS Server SDK - v2.9.7 | Inside a session | LiveKit Docs
m
Add the departure time out to this code here, set to 5 mins :
Copy code
async def entrypoint(ctx: JobContext):
    ctx.log_context_fields = {
        "room": ctx.room.name,
        "user_id": "waec_student",
    }
    await ctx.connect()
    <http://logger.info|logger.info>("Connected to room")

    session = AgentSession(
        vad=ctx.proc.userdata["vad"],
        llm=openai.LLM(model="gpt-4o"), 
        stt=deepgram.STT(model="nova-2", language="en-US"),
        tts=deepgram.TTS() 
    )
    <http://logger.info|logger.info>("Agent session components initialized")
    

    @ctx.room.on("participant_disconnected")
    def on_participant_disconnected(participant: rtc.Participant):
        <http://logging.info|logging.info>(
            f"Participant {participant.identity} disconnected, reason: {rtc.DisconnectReason.Name(participant.disconnect_reason)}"
        )
        
        # Send RPC message to frontend about participant disconnection
        async def send_participant_disconnect_notice():
            try:
                await ctx.room.local_participant.publish_data(
                    json.dumps({
                        "method": "participant_disconnected",
                        "data": {
                            "participant": participant.identity,
                            "reason": rtc.DisconnectReason.Name(participant.disconnect_reason),
                            "message": "Participant disconnected"
                        }
                    }).encode(),
                    topic="lk-rpc-request"
                )
                <http://logger.info|logger.info>("Sent participant_disconnected RPC to frontend")
            except Exception as e:
                logger.error(f"Failed to send participant_disconnected RPC: {str(e)}", exc_info=True)
        
        asyncio.create_task(send_participant_disconnect_notice())

 

    @session.on("metrics_collected")
    def _on_metrics_collected(ev: MetricsCollectedEvent):
        metrics.log_metrics(ev.metrics)
        usage_collector.collect(ev.metrics)
    


    usage_collector = metrics.UsageCollector()

    @session.on("metrics_collected")
    def _on_metrics_collected(ev: MetricsCollectedEvent):
        metrics.log_metrics(ev.metrics)
        usage_collector.collect(ev.metrics)
            
            
    async def log_usage():
        summary = usage_collector.get_summary()
        <http://logger.info|logger.info>(f"Usage summary: {summary}")
        
   

    async def delete_room():
        async with api.LiveKitAPI(
            os.getenv("LIVEKIT_URL"),
            os.getenv("LIVEKIT_API_KEY"),
            os.getenv("LIVEKIT_API_SECRET")
        ) as api_client:
            await api_client.room.delete_room(api.DeleteRoomRequest(
                room=ctx.room.name,
            ))
            <http://logger.info|logger.info>("Room deleted successfully")

    # Add shutdown callbacks in correct order
    ctx.add_shutdown_callback(log_usage)  # First log usage (which now sends the RPC)
    ctx.add_shutdown_callback(delete_room)  # Then delete the room
        

    await ctx.wait_for_participant()
    <http://logger.info|logger.info>("Participant detected")

    agent = WAECExamAgent()
    agent.session = session

   

    try:
        await session.start(
            room=ctx.room,
            agent=agent,
            room_input_options=RoomInputOptions(
                text_enabled=True,
                audio_enabled=True
            ),
            room_output_options=RoomOutputOptions(
                transcription_enabled=True,
                audio_enabled=True
            ),
        )
        <http://logger.info|logger.info>("Agent session started successfully")
    except Exception as e:
        logger.error(f"Failed to start agent session: {str(e)}", exc_info=True)
        raise


if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, prewarm_fnc=prewarm))
t
To set the departure timeout to 5 minutes in your code, you can include the
departureTimeout
property in the room creation options. Here's how you can modify your code:
Copy code
async def entrypoint(ctx: JobContext):
    ctx.log_context_fields = {
        "room": ctx.room.name,
        "user_id": "waec_student",
    }
    await ctx.connect()
    <http://logger.info|logger.info>("Connected to room")

    session = AgentSession(
        vad=ctx.proc.userdata["vad"],
        llm=openai.LLM(model="gpt-4o"), 
        stt=deepgram.STT(model="nova-2", language="en-US"),
        tts=deepgram.TTS() 
    )
    <http://logger.info|logger.info>("Agent session components initialized")

    # Set departure timeout to 5 minutes (300 seconds)
    room_options = RoomOptions(
        departure_timeout=300  # 5 minutes in seconds
    )

    try:
        await session.start(
            room=ctx.room,
            agent=agent,
            room_input_options=RoomInputOptions(
                text_enabled=True,
                audio_enabled=True
            ),
            room_output_options=RoomOutputOptions(
                transcription_enabled=True,
                audio_enabled=True
            ),
            room_options=room_options  # Pass the room options here
        )
        <http://logger.info|logger.info>("Agent session started successfully")
    except Exception as e:
        logger.error(f"Failed to start agent session: {str(e)}", exc_info=True)
        raise
This ensures that the room remains open for 5 minutes after the last participant leaves, allowing them to rejoin within that time frame.
It seems that the
RoomOptions
class or object is not defined in your current code. You may need to import it from the appropriate LiveKit SDK or library. Please check the documentation or the SDK you are using to confirm the correct import statement for
RoomOptions
. If you are still facing issues, let me know, and I can assist further.