I transferred between agent but I after transfered...
# ask-ai
m
I transferred between agent but I after transfered I want to come back to the agent that called it
t
Thanks for reaching out, Muhammad. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I’m happy to help you with returning to the original agent after a transfer! You can achieve this smoothly by using agent handoffs while preserving the context. The idea is to save the current agent before the transfer and then bring it back when you want to return. If you’re working with Python, a great way is to store the current agent in
userdata.prev_agent
before transferring. Later on, you can retrieve it and hand off back to that original agent. Here’s a simple example to guide you:
Copy code
async def return_to_previous_agent(self, context):
    userdata = context.userdata
    if userdata.prev_agent:
        return userdata.prev_agent  # Hand off back to the original agent
    else:
        return self  # No previous agent to return to
For those using Node.js, a similar method works by saving the current agent in
userdata.prevAgent
and then creating a tool to return to it. Here’s how you might do it:
Copy code
const returnToPreviousAgent = llm.tool({
    description: 'Return to the previous agent',
    execute: async (_, { ctx }) => {
        const userdata = ctx.userData;
        if (userdata.prevAgent) {
            return llm.handoff({ agent: userdata.prevAgent });
        }
        return 'No previous agent to return to.';
    }
});
If you’d like, I’m here to help you step-by-step with implementing this or if you have any other questions. Just let me know! Sources: complex-agents/role-playing/README.md | examples/src/restaurant_agent.ts | Tool definition and use | LiveKit docs
m
What are task in livekit?
t
I'm glad you're interested in learning about Tasks in LiveKit! These are experimental components within the LiveKit Agents framework, designed as focused, reusable units that help you achieve specific goals and return typed results. Unlike regular agents, tasks temporarily take control of a session, carry out their purpose, and then hand control back along with the result to the calling agent or task. Tasks can be really handy for things like: • Getting recording consent right at the start of a call • Gathering structured information, such as email or credit card details • Guiding users through a series of questions To create tasks, you extend the
AgentTask
class in Python, and they support tools much like agents do. Tasks kick off with the
on_enter
method and wrap up by calling the
complete
method with a result. There are also some prebuilt tasks like
GetEmailTask
that make it easier to collect and validate email addresses. Just a quick heads-up: tasks are still experimental, currently available only in Python, and the API might evolve in future updates. If you have any questions or need help getting started, feel free to ask—I’m here to support you! Sources: Workflows | LiveKit Docs
m
Show me the code
t
I'd love to walk you through an example of how to define and use a custom task in LiveKit using Python. Here it is:
Copy code
from livekit.agents.beta.workflows import AgentTask
from dataclasses import dataclass
from typing import Optional

@dataclass
class UserInfo:
    """Custom result type for structured data collection"""
    name: str
    email: str
    phone: Optional[str] = None

class CollectUserInfoTask(AgentTask[UserInfo]):
    """
    Custom task that collects user information and returns structured data.
    Extends AgentTask with a generic type parameter for the result.
    """
    
    def __init__(self):
        super().__init__()
        self._collected_info = {"name": None, "email": None, "phone": None}
    
    async def on_enter(self):
        """
        Called when the task starts. This method initiates interaction with the user.
        The task has full access to the session and can use tools, TTS, etc.
        """
        await self.say("Hi! I need to collect some information from you.")
        await self.say("What's your full name?")
    
    async def collect_name(self, name: str):
        """Tool function that can be called by the LLM to collect name"""
        self._collected_info["name"] = name
        await self.say(f"Thanks {name}! What's your email address?")
    
    async def collect_email(self, email: str):
        """Tool function to collect and validate email"""
        if "@" not in email:
            await self.say("That doesn't look like a valid email. Please try again.")
            return
        
        self._collected_info["email"] = email
        await self.say("Great! Do you have a phone number you'd like to share? Say 'skip' if not.")
    
    async def collect_phone(self, phone: str):
        """Tool function to collect optional phone number"""
        if phone.lower() != "skip":
            self._collected_info["phone"] = phone
        
        # Complete the task with structured results
        result = UserInfo(
            name=self._collected_info["name"],
            email=self._collected_info["email"],
            phone=self._collected_info["phone"]
        )
        await self.complete(result)

# Using the task within an agent
async def agent_with_task_example(ctx):
    """Example showing how to run tasks within an agent"""
    
    # Create and run the task - it automatically takes control
    user_info_task = CollectUserInfoTask()
    
    # Await the task to get its result
    user_info = await user_info_task
    
    # Use the structured result
    print(f"Collected info: {user_info.name}, {user_info.email}, {user_info.phone}")
    
    # Continue with other agent logic...
This example shows you how to create a task that gently collects user information and returns it neatly as structured data. If you have any questions or want me to walk you through any part of this, please don’t hesitate to ask. I’m here to help! Sources: examples/primitives/participant_entrypoint.py | meditation_assistant/README.mdoc | Workflows | LiveKit Docs