How can i access the agent via contex.agent in a f...
# ask-ai
w
How can i access the agent via contex.agent in a function_tool that's been added to the class dynamically during initialization?
t
Thanks for reaching out, Alex. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To access
context.agent
in a
function_tool
dynamically added to a class during initialization, you can use the
RunContext
parameter that is automatically provided to your tool functions. The agent can be accessed through
context.session.current_agent
. Here’s an example of how to achieve this:
Copy code
from livekit.agents import function_tool, Agent, RunContext

class MyAgent(Agent):
    def __init__(self):
        # Create a dynamic tool during initialization
        async def my_dynamic_tool(context: RunContext, param: str) -> str:
            # Access the current agent through context
            current_agent = context.session.current_agent
            
            # Use the agent instance (e.g., access agent properties or methods)
            agent_instructions = current_agent.instructions
            
            return f"Tool executed by agent with instructions: {agent_instructions}"
        
        # Add the dynamic tool to the agent
        dynamic_tool = function_tool(
            my_dynamic_tool,
            name="my_dynamic_tool",
            description="A dynamically created tool that accesses the agent"
        )
        
        super().__init__(
            instructions="You are a helpful assistant",
            tools=[dynamic_tool]
        )
Key points to note: • RunContext Parameter: The
RunContext
provides access to the current session, agent, and state. • Agent Access: Use
context.session.current_agent
to access the agent instance. • Dynamic Tool Creation: Use
function_tool
to create tools dynamically, specifying a name, description, and callable function. Let me know if you need further clarification or additional examples! Sources: Tool definition and use | LiveKit Docs | examples/voice_agents/annotated_tool_args.py