How can I end a session after 200 seconds of conve...
# ask-ai
h
How can I end a session after 200 seconds of conversation?
t
Thanks for reaching out, Lukasz. 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 end a session after 200 seconds of conversation in LiveKit, here are a couple of friendly ways to do it: • Close the Agent Session: You can set up a timer to automatically close the agent session after 200 seconds. Here’s a simple example:
Copy code
import asyncio
from livekit.agents import JobContext, AgentSession

async def entrypoint(ctx: JobContext):
    session = AgentSession()
    
    # Start your agent session
    await session.start(agent=your_agent, room=ctx.room)
    
    # Create a task that will close the session after 200 seconds
    async def close_after_timeout():
        await asyncio.sleep(200)  # Wait 200 seconds
        await session.aclose()  # Close the agent session
    
    # Run the timeout task concurrently
    asyncio.create_task(close_after_timeout())
• End the Session for Everyone: Or, if you prefer, you can delete the entire room after 200 seconds like this:
Copy code
from livekit import api
import os

async def entrypoint(ctx: JobContext):
    # Start your session setup
    
    async def delete_room_after_timeout():
        await asyncio.sleep(200)
        
        api_client = api.LiveKitAPI(
            os.getenv("LIVEKIT_URL"),
            os.getenv("LIVEKIT_API_KEY"),
            os.getenv("LIVEKIT_API_SECRET"),
        )
        await api_client.room.delete_room(api.DeleteRoomRequest(
            room=ctx.job.room.name,
        ))
    
    asyncio.create_task(delete_room_after_timeout())
Feel free to pick whichever method works best for you! And if you have any questions or need a hand with anything else, just let me know—I’m here to help! Sources: Inside a session | LiveKit Docs | Agents Core Architecture | livekit/livekit_composite | DeepWiki | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real... | basics/exit_message.py | Job lifecycle | LiveKit Docs
h
And how to handle the case where the user might disconnect earlier; they should say goodbye before disconnecting
t
To help make sure users say goodbye before disconnecting, here are some friendly strategies you can try out: • Explicit Goodbye Function: You can create a handy function that users call to wrap up the session with a warm goodbye message:
Copy code
@llm.function_tool
async def close_session(self):
    """Called when user wants to leave the conversation"""
    logger.info("Closing session from function tool")
    await self.session.generate_reply(instructions="say goodbye to the user")
    self._closing_task = asyncio.create_task(self.session.aclose())
• Lifecycle Hooks: Using the
on_exit
method is a neat way to send a friendly goodbye before the session ends:
Copy code
async def on_exit(self):
    await self.session.generate_reply(
        instructions="Tell the user a friendly goodbye before you exit.",
    )
• Session Close Events: You can listen for session close events to tidy things up and make sure a goodbye message gets sent out:
Copy code
@session.on("close")
def on_close(ev: CloseEvent):
    print(f"Agent Session closed, reason: {ev.reason}")
    await self.session.say("Goodbye!")
• Control Interruptions: When generating goodbye messages, setting
allow_interruptions=False
helps ensure the farewell plays out fully without being cut off:
Copy code
@function_tool
async def story_finished(self, context: RunContext[StoryData]):
    self.session.interrupt()
    await self.session.generate_reply(
        instructions=f"say goodbye to {context.userdata.name}", 
        allow_interruptions=False
    )
With these approaches, users will always get a proper, friendly farewell—whether they disconnect on their own or the session times out. If you want to chat more about this or need a hand, just let me know! Sources: examples/voice_agents/realtime_joke_teller.py | Voice pipeline nodes | LiveKit Docs | Connecting to LiveKit | LiveKit Docs | web/providers/GameProvider.tsx