how to manually invoke a tool call in a agent on_e...
# ask-ai
w
how to manually invoke a tool call in a agent on_enter
t
Thanks for reaching out, Test. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hi there! If you'd like to manually invoke a tool call in an agent's
on_enter
method, here are a few ways you can do it: • Indirect Invocation (LLM-Triggered): You can use
self.session.generate_reply()
inside
on_enter
. This gently prompts the LLM to assess the context and decide whether to call a tool based on your agent's instructions. Just a heads-up, though—it doesn't guarantee the tool will be called every time. • Direct Invocation (Explicit Call): If you want to be sure the tool runs, you can call the tool method directly in
on_enter
. For example: `async def on_enter(self): await self.tool_name(context=RunContext(userdata=self.session.userdata, chat_ctx=self.chat_ctx))`This way, the tool definitely executes, but you'll want to make sure the context is properly set up. • Silent Execution: If you'd prefer to suppress any automatic replies after the tool runs, you can use the
function_tools_executed
event along with
cancel_tool_reply()
to keep things quiet. If you'd like, I’m here to help with more details or examples tailored to your specific situation. Just let me know! Sources: Tool definition and use | LiveKit docs | complex-agents/testing/agent.py | main.py | examples/voice_agents/restaurant_agent.py
w
agent does not have access to tool call
t
I understand how frustrating it can be when your agent doesn’t have access to a tool call. Let’s walk through some steps together to help resolve this: • Verify Tool Registration: Please make sure the tool is properly registered with your agent. For Python agents, you can use the
@function_tool()
decorator, and for JavaScript agents, double-check that the tool is included in the agent's
tools
configuration. • Check Tool Name: It’s important that the tool name matches exactly between the LLM’s call and the tool definition—sometimes a small typo can cause issues. • Validate Arguments: Let’s confirm that the tool’s argument schema aligns with what the LLM is trying to pass along. • Examine Context: Make sure the tool is available in the current context and that any necessary external services or authentication tokens are correctly set up. • Review Logs: Taking a look at the agent logs can be really helpful—watch out for messages like
unknown AI function
or validation errors that can point us toward the problem. If you’re still running into trouble after trying these steps, please feel free to share the specific tool and agent setup details with me. I’m here to help you through this! Sources: agents/src/inference/llm.ts | livekit-agents/livekit/agents/voice/generation.py | Tool definition and use | LiveKit docs | External data and RAG | LiveKit Docs
w
object has no attribute
t
It looks like you're encountering the "object has no attribute" error, which usually happens when trying to access something that isn't available on the object. Don’t worry, I’m here to help you work through this! Here are some friendly steps you can follow: • Verify Public API Usage: Double-check that the attribute you want to use is actually part of the exported API. The official LiveKit documentation is a great place to confirm which interfaces are supported. • Handle Conditional Imports: If you’re working with modules that might not always be available (like
mcp
), try using
typing.TYPE_CHECKING
to prevent issues during runtime: • Validate Environment Setup: It’s a good idea to check that your LiveKit package versions are compatible. Running
pip freeze | grep livekit
can help you see what’s installed. • Debug Object Structure: You can use
dir(obj)
or
hasattr(obj, 'attr_name')
to peek inside the object and make sure the attribute you want is really there before accessing it. • Review Implementation: Lastly, take a moment to ensure your agent implementation aligns with the documented patterns and examples. This often helps catch subtle issues. If you’d like, feel free to share more details about the specific object and attribute causing trouble—I’m more than happy to assist you further! Sources: livekit-plugins/livekit-plugins-hedra/livekit/plugins/hedra/avatar.py | SIP troubleshooting guide | LiveKit docs | Events and error handling | LiveKit docs | Still Have Questions
w
i am calling AgentName.tool_name()
t
I understand that directly calling
AgentName.tool_name()
isn’t supported in LiveKit agents, and that can be a bit confusing. Tools are actually designed to be triggered by the LLM based on the conversation context, tool descriptions, and parameter schemas. To help ensure your tools work smoothly: • Make sure to define your tools using decorators like
@function_tool
(Python) or
llm.tool()
(Node.js). • Provide clear descriptions and parameter schemas so the LLM knows exactly when and how to use each tool. • Try testing the tool behavior by simulating user input and checking that the right tool is called with the expected arguments. If you’d like, I’m here to help you with setting up or testing your tools—just let me know! Sources: Tool definition and use | LiveKit docs | models/templates/CohereForAI-c4ai-command-r-plus-tool_use.jinja | examples/src/restaurant_agent.ts | livekit-agents/livekit/agents/inference/llm.py | Testing and evaluation | LiveKit Docs
w
await self.tool_name(context=RunContext(userdata=self.session.userdata, chat_ctx=self.chat_ctx)) this gives error tool is added using super().__init__( tools=tools_list, )
t
Thanks for reaching out! The error happens because tools added via
super().__init__(tools=tools_list)
are registered in the agent's
ToolContext
, but they aren't automatically set up as methods on the agent instance. So, calling
self.tool_name()
won’t work right away. Here’s how you can fix this: • Access Tools via ToolContext: You can use
self.tools.function_tools['tool_name']
to call the tool. For example:
Copy code
tool_func = self.tools.function_tools['tool_name']
result = await tool_func(
    context=RunContext(
        userdata=self.session.userdata,
        chat_ctx=self.chat_ctx
    ),
    param="value"
)
• Define Tools Inside the Class: If you’d prefer to call tools directly like
self.tool_name()
, you can define them inside your agent class using the
@function_tool()
decorator:
Copy code
@function_tool()
async def tool_name(self, context: RunContext, param: str):
    return "result"
If anything is unclear or if you'd like me to walk you through your setup, just let me know—I’m happy to help! Sources: Tool definition and use | LiveKit docs
w
async def confirm_meeting(context: RunContext_T) -> str:
t
I'd be happy to guide you through defining and using an async tool like
confirm_meeting(context: RunContext_T) -> str
. Here’s a step-by-step approach to help you along: 1. Define the Tool: Start by using the
@function_tool()
decorator to let the LLM know this function can be called. For example:
Copy code
@function_tool()
async def confirm_meeting(self, context: RunContext_T) -> str:
    """Called when the user confirms the meeting details."""
    userdata = context.userdata
    if not userdata.customer_name or not userdata.meeting_time:
        return "Please provide your name and meeting time first."
    return "Your meeting has been confirmed."
1. Access Context: You can use
context.userdata
to get or update user-specific info, like meeting details. 2. Register the Tool: Make sure to include your tool in the agent’s
tools
list when initializing, or define it directly inside the agent class. 3. Handle Interruptions: If you want to prevent interruptions from user input during the tool’s execution, just call
context.disallow_interruptions()
at the start of your function. If you’d like, I’m here to help with any part of the implementation or testing. Just let me know! Sources: Tool definition and use | LiveKit docs | livekit-agents/livekit/agents/llm/mcp.py
w
TypeError: RunContext.__init__() got an unexpected keyword argument 'userdata
t
It looks like the error happens because
RunContext.__init__()
doesn’t take
userdata
directly as a parameter. Instead, you can access
userdata
through the
session
object that’s passed to
RunContext
. Here’s a friendly way to fix this: • Make sure you pass
userdata
when you initialize your `AgentSession`:
Copy code
userdata = MyUserData(ctx=ctx)
session = AgentSession[MyUserData](
    userdata=userdata,
    llm=openai.LLM(),
    stt=deepgram.STT(),
    tts=elevenlabs.TTS(),
    vad=silero.VAD.load()
)
• Then, when you’re working with tools, access
userdata
via
context.userdata
, where
context
is your
RunContext
instance initialized with the
AgentSession
. If anything feels unclear or you’d like a hand with any step, please don’t hesitate to ask—I’m here to help! Sources: livekit-agents/livekit/agents/voice/agent_session.py | Workflows | LiveKit docs | flows/multi_stage_flow.py
w
tool_func = self.tools.function_tools['tool_name'] result = await tool_func( context=RunContext( userdata=self.session.userdata, chat_ctx=self.chat_ctx ), param="value" ) you gave this
t
Thank you for sharing the example! I noticed it references
self.tools.function_tools
, which isn’t clearly documented as a public API in LiveKit. Could you please let me know if you’re trying to access tools from outside the agent, during event handling, or maybe in another specific situation? Understanding this will really help me guide you to the best solution. Sources: Tool definition and use | LiveKit docs | Agents v0.x migration guide - Python | LiveKit docs | livekit-plugins/livekit-plugins-mistralai/livekit/plugins/mistralai/llm.py
w
i want to do tool all in agents on_enter method
t
Hey there! When it comes to calling a tool in an agent's
on_enter
method, the best way is to use
self.session.generate_reply()
. This lets the LLM decide if it should invoke the tool based on the agent's instructions. Here's a simple example to illustrate:
Copy code
async def on_enter(self):
    self.session.generate_reply(
        instructions="Ask the user about the weather to trigger the weather tool."
    )
If you’d prefer to call a tool directly within
on_enter
, that’s possible too—just call it like any regular method if it’s defined inside your agent class. For example:
Copy code
@function_tool
async def get_weather(self, location: str):
    return f"The weather in {location} is sunny."

async def on_enter(self):
    await self.get_weather("New York")
That said, directly invoking tools in
on_enter
isn’t officially documented and might not perfectly fit with LiveKit’s intended lifecycle. For the smoothest experience, I recommend guiding the LLM through your agent’s instructions so it calls the tool during the session. If you’d like, I’m here to help you set this up or answer any questions you have! Sources: examples/src/basic_tool_call_agent.ts | docs/index.yaml
w
without generate_reply
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!