wooden-beard-26644
07/25/2025, 8:37 PMtall-airline-16756
07/25/2025, 8:37 PMtall-airline-16756
07/25/2025, 8:38 PMcontext.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:
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