big-controller-60015
07/31/2025, 2:10 PMtall-airline-16756
07/31/2025, 2:10 PMtall-airline-16756
07/31/2025, 2:11 PMaclose() method to close the session: await session.aclose()
• Graceful Closure with Drain: Call drain() before closing to ensure all pending operations complete: await session.drain()
await session.aclose()
• Closing from Within an Agent: Implement session closure as a function tool within your agent: class MyAgent(Agent):
@function_tool
async def end_session(self):
"""When the user wants to stop talking to you, use this function to close the session."""
await self.session.drain()
await self.session.aclose()
• Closing with Custom Logic: Generate a farewell message before closing: class MyAgent(Agent):
@llm.function_tool
async def close_session(self):
"""Called when user want to leave the conversation"""
<http://logger.info|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())
• Cleanup in Finally Blocks: Ensure proper cleanup when using sessions in try/finally blocks: session = None
try:
session = AgentSession(...)
await session.start(agent=MyAgent(), room=ctx.room)
# ... session logic
finally:
if session:
await session.aclose()
• Multiple Session Management: Close multiple sessions properly: async def _close_session(self, sess: AgentSession) -> None:
await sess.drain()
await sess.aclose()
# Close all sessions
await asyncio.gather(*[self._close_session(session) for session in self._sessions.values()])
Additionally, sessions will automatically close when the linked participant disconnects for reasons like CLIENT_INITIATED, ROOM_DELETED, or USER_REJECTED, unless you disable this behavior by setting RoomInputOptions.close_on_disconnect to False.
Let me know if you need further clarification on any of these methods!
Sources: examples/other/transcription/multi-user-transcriber.py | basics/exit_message.py