how to exit the agent based on task done?
# ask-ai
a
how to exit the agent based on task done?
t
Thanks for reaching out, Aditya. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To exit an agent based on task completion in LiveKit, you can use one of the following approaches: 1. on_exit Lifecycle Hook: Override the
on_exit
method in your agent to run cleanup or exit logic when the agent is about to exit.
Copy code
class MyAgent(Agent):
    async def on_exit(self) -> None:
        # Cleanup or exit logic here
        await super().on_exit()
1. Drain Method: Use
drain()
to gracefully shut down an agent by completing any ongoing tasks before exit.
Copy code
async def exit_agent():
    if agent.activity is not None:
        await agent.activity.drain()
1. aclose Method: Use
aclose()
to asynchronously close and release resources immediately.
Copy code
async def exit_agent():
    if agent.activity is not None:
        await agent.activity.aclose()
1. InlineTask Completion: For
InlineTask
-based tasks, complete by setting the result or exception on the task to cause it to exit.
Copy code
class MyInlineTask(InlineTask[MyResultType]):
    def complete(self, result: MyResultType | ToolError) -> None:
        super().complete(result)
The choice depends on your specific use case and how gracefully you want the agent to shut down. These methods help ensure tasks are managed properly before the agent exits. For additional details, you can review the LiveKit Agents documentation on lifecycle and task management.
a
give me example on on_exit
t
Hey there! Let me walk you through a cool little method called
on_exit
in LiveKit agents. Think of it like a friendly farewell moment for your agent.
Copy code
async def on_exit(self) -> None:
    await self.session.generate_reply(
        instructions="Tell the user a friendly goodbye before you exit."
    )
So, this method is basically your agent's way of saying "see ya later!" before it wraps up its work or hands things off to another agent. It's super handy for those final touchpoints – maybe dropping a warm goodbye, making sure some important data gets saved, or just tidying things up. In this example, we're using the method to have the agent send a sweet farewell message. Just a nice, personal touch to make the interaction feel more human and considerate.
a
but how does it know to terminate
t
Hey there! Let me break down how an agent in LiveKit wraps up its work in a super smooth way. Think of it like a well-organized teammate who always makes sure to tidy up before heading out. 1. Lifecycle Hook:
on_exit
is like the agent's personal "goodbye checklist" - making sure everything is in order before leaving. 2. Session Management: The
AgentSession
is basically the team manager, keeping track of when it's time to close things down (like calling
aclose()
). 3. Drain Method:
drain()
is that responsible friend who makes sure all tasks are finished before stepping out - running
on_exit
and wrapping everything up. 4. Activity Cleanup: After making sure everything's done, the agent lets go of its resources, just like clearing your desk at the end of the workday. 5. Close Event: A
CloseEvent
is basically the agent's way of saying "All done! I'm officially signing off." Pretty cool, right? This whole process makes sure the agent shuts down super gracefully, leaving no loose ends behind. 😊 Sources: Voice pipeline nodes | LiveKit Docs | livekit-agents/livekit/agents/ipc/job_proc_lazy_main.py | livekit-agents/livekit/agents/voice/agent.py
a
give me example of the on_exit
t
Hey there! Let me walk you through a neat way to add a personal touch when your LiveKit agent is wrapping up a conversation. 👋
Copy code
from livekit.agents import Agent

class MyAgent(Agent):
    async def on_exit(self) -> None:
        """Called before the agent gives control to another agent or exits the session."""
        # Send a goodbye message before exiting
        await self.session.generate_reply(
            instructions="Thank you for interacting with me. Goodbye!"
        )
See how simple it is? This code lets your agent say a warm goodbye before stepping back. It's like giving a friendly wave as you're heading out – just a nice, considerate way to end the interaction. Pretty cool, right? 😊
a
how to initiate this on_exit based on users's request?
t
The current information in the knowledge base doesn't give us a straightforward way to directly trigger the on_exit lifecycle hook from a user request. But don't worry - I totally get what you're looking for! The on_exit method actually runs automatically when an agent is about to exit or hand control to another agent in the same session. Think of it like a behind-the-scenes cleanup process. Here's a quick example that shows how you might close a session, which does kick off some exit processes:
Copy code
@function_tool
async def close_session(self):
    await self.session.generate_reply(instructions="say goodbye to the user")
    self._closing_task = asyncio.create_task(self.session.aclose())
If you're hoping to exit based on a specific user command, we can definitely work together to create some custom logic. Basically, you'd want to detect the user's command and then programmatically close the session using methods like aclose() or drain(). This approach would naturally invoke on_exit as part of the shutdown process. Want me to help you brainstorm how we could set that up? I'm all ears and happy to walk you through it! Sources: Voice pipeline nodes | LiveKit Docs | tests/test_agent_session.py