how to use tool call on_enter from agent in liveki...
# ask-ai
s
how to use tool call on_enter from agent in livekit
t
Thanks for reaching out, Abdullah. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Could you please share a bit more about the 'on_enter' tool you mentioned? For example, is it a specific feature, an API, or part of a workflow in LiveKit? Any extra details you can provide will really help me support you better. I'm here to help!
s
this is my base.py
Copy code
import logging
from livekit.agents.voice import Agent, RunContext

from shared.models import UserData

logger = logging.getLogger(__name__)

RunContext_T = RunContext[UserData]

greeting = False


class BaseAgent(Agent):

    async def on_enter(self) -> None:

        logger.info(f"session object: {self.session}")
        logger.info(f"session type: {type(self.session)}")

        logger.info("==== SESSION INITIALIZED ====")
        logger.info(f"LLM: -> {self.session.llm}")
        logger.info(f"STT: -> {self.session.stt}")
        logger.info(f"TTS: -> {self.session.tts}")

        agent_name = self.__class__.__name__
        logger.info(f"entering task {agent_name}")

        userdata: UserData = self.session.userdata
        chat_ctx = self.chat_ctx.copy() 


        # Bring over some turns from the previous agent for continuity
        if isinstance(userdata.prev_agent, Agent):
            truncated = userdata.prev_agent.chat_ctx.copy(
                exclude_instructions=True, exclude_function_call=False
            )
            existing_ids = {item.id for item in chat_ctx.items}
            items_copy = [it for it in truncated.items if it.id not in existing_ids]
            chat_ctx.items.extend(items_copy)

        # Inject current user state into system context
        chat_ctx.add_message(
            role="system",
            content=f"You are {agent_name}. Current user data:\n{userdata.summarize()}",
        )
        logger.info(f"Sajjad You are {agent_name}. Current user data:\n{userdata.summarize()}")

        await self.update_chat_ctx(self.chat_ctx)

        self.session.generate_reply(tool_choice="auto")

    # async def _transfer_to(self, name: str, context: RunContext_T):
    #     userdata = context.userdata
    #     current = context.session.current_agent
    #     next_agent = userdata.agents[name]
    #     userdata.prev_agent = current
    #     return next_agent

    def _transfer_to(self, name: str):
        """Resolve the next agent using the current session (no RunContext)."""
        userdata: UserData = self.session.userdata
        current = self.session.current_agent
        next_agent = userdata.agents[name]
        userdata.prev_agent = current
        return next_agent
and my agent.py
Copy code
# agents/info_collector.py
import asyncio
import logging,json
from livekit.agents.llm import function_tool
from livekit.plugins import elevenlabs, openai
from prompts.greeting_agent import greeting_agent_prompt

from agents.base import BaseAgent, RunContext_T
from shared.tools import update_name, update_phone

from livekit.agents import RunContext, get_job_context

logger = logging.getLogger("modular-callflow")
logger.setLevel(logging.INFO)
import logging
from livekit.agents.voice import Agent, RunContext

from shared.models import UserData

logger = logging.getLogger(__name__)

# RunContext_T = RunContext[UserData]

greeting = False


class greeting_agent(BaseAgent):
    """
     This is called for greeting the caller
    """

    def __init__(self, greeting= None, bot_name=None, name=None, time= None,greeting_prompt = None):
        self.greeting= greeting
        self.bot_name = bot_name
        self.name = name
        self.time = time
        self.greeting_prompt = greeting_prompt

        logger.info(f"Greeting agent initialized: {bot_name}, {name}, {greeting_prompt}")
        # super().__init__(instructions=must_ask_agent_prompt,
        # )
        updated_greeting_agent_prompt = greeting_agent_prompt.format(greeting=greeting, name= name, bot_name=bot_name, time=time, greeting_prompt= greeting_prompt)
        logger.info(f"greeting: {updated_greeting_agent_prompt}")



        super().__init__(instructions=updated_greeting_agent_prompt)

    async def on_enter(self) -> None:

        logger.info(f"session object: {self.session}")
        logger.info(f"session type: {type(self.session)}")

        logger.info("==== SESSION INITIALIZED ====")
        logger.info(f"LLM: -> {self.session.llm}")
        logger.info(f"STT: -> {self.session.stt}")
        logger.info(f"TTS: -> {self.session.tts}")



        agent_name = self.__class__.__name__
        logger.info(f"entering task {agent_name}")

        userdata: UserData = self.session.userdata
        chat_ctx = self.chat_ctx.copy() 


        # Bring over some turns from the previous agent for continuity
        if isinstance(userdata.prev_agent, Agent):
            truncated = userdata.prev_agent.chat_ctx.copy(
                exclude_instructions=True, exclude_function_call=False
            )
            existing_ids = {item.id for item in chat_ctx.items}
            items_copy = [it for it in truncated.items if it.id not in existing_ids]
            chat_ctx.items.extend(items_copy)

        # Inject current user state into system context
        chat_ctx.add_message(
            role="system",
            content=f"You are {agent_name}. Current user data:\n{userdata.summarize()}",
        )
        logger.info(f"Sajjad You are {agent_name}. Current user data:\n{userdata.summarize()}")

        await self.update_chat_ctx(self.chat_ctx)
        # await self.session.generate_reply(tool_choice="required", allow_interruptions=False)

        logger.info("[GreetingAgent] Generating greeting message...")
        # ✅ Wait for greeting message to be fully generated & spoken
        await self.session.generate_reply(allow_interruptions=False)

        logger.info("[GreetingAgent] Greeting completed, auto-transferring to main_agent...")
        # ✅ Immediately transfer to main_agent
        # return await self._transfer_to("main_agent")
        await asyncio.sleep(0.1)

        logger.info("[GreetingAgent] Greeting completed, auto-transferring to main_agent...")
        next_agent = self._transfer_to("main_agent")
        return next_agent
    


    # @function_tool()
    # async def main_agent(self, context: RunContext_T):
    #     """
    #         No matter what the user query is call this function to answer
    #     """
    #     logger.info(f"Transferring to main_agent from greeter agent")
    #     return await self._transfer_to("main_agent", context)
in my agent i want to transfer to main_agent in on_enter
t
In LiveKit, the
on_enter
method is mainly there to help with initialization and setup when an agent becomes active. It’s not really meant to directly start agent transfers. Instead, agent transfers usually happen through function tools or workflows. Here’s a friendly guide on how you can handle agent transfers: 1. Try using a function tool to define the transfer logic. For example:
Copy code
class BaseAgent(Agent):
    async def _transfer_to_agent(self, name: str, context: RunContext_T) -> Agent:
        userdata = context.userdata
        userdata.prev_agent = context.session.current_agent
        return userdata.agents[name]

class GreetingAgent(BaseAgent):
    @function_tool
    async def transfer_to_main_agent(self, context: RunContext_T) -> Agent:
        await self.session.say("Transferring you to the main agent.")
        return await self._transfer_to_agent("main_agent", context)
1. Or, you can use
session.update_agent()
inside a function tool to directly change the active agent:
Copy code
class ShortAgent(Agent):
    @function_tool
    async def change_agent(self):
        self.session.update_agent(LongAgent())
These methods help make sure the transfer logic works smoothly while keeping the context and chat history intact. If you have any questions or want me to walk you through it more, just let me know—I’m here to help! Sources: Pipeline nodes and hooks | LiveKit Docs
s
my goal is to generate a greeting from greeting agent and immedatly transfer to main agent without waiting for user response?
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!
s
2025-10-08 142713,075 - multi_agent - ERROR - [prewarm] Failed to instantiate EnglishModel: no job context found, are you running this code inside a job entrypoint? Traceback (most recent call last): File "/home/abdullah/Desktop/voice-ai-multiagent-backend/prewarm.py", line 47, in prewarm_fnc proc.userdata["turn_detection"] = EnglishModel() File "/home/abdullah/Desktop/voice-ai-multiagent-backend/livekit/plugins/turn_detector/english.py", line 17, in init super().__init__(model_type="en", unlikely_threshold=unlikely_threshold) File "/home/abdullah/Desktop/voice-ai-multiagent-backend/livekit/plugins/turn_detector/base.py", line 144, in init self._executor = inference_executor or get_job_context().inference_executor File "/home/abdullah/Desktop/voice-ai-multiagent-backend/livekit/agents/job.py", line 44, in get_job_context raise RuntimeError( RuntimeError: no job context found, are you running this code inside a job entrypoint? can i not run turn_dector in prewarm?