Building AI agents that can adapt to their environment is one of the most challenging yet rewarding aspects of modern LLM development. While static tool definitions are easy to implement, they often lead to bloated context windows and rigid systems that fail to scale. PydanticAI, a type-safe framework for building agents, offers powerful abstractions that allow developers to move beyond static registration and toward dynamic tool selection.
In this post, we will explore how to implement runtime capability discovery, ensuring your agent only sees and uses the tools relevant to the current task or environment state.
Why Dynamic Tool Selection Matters
Traditional agent frameworks often require you to define a fixed list of tools at initialization. As your system grows, this list becomes unwieldy. More tools mean more tokens consumed in the system prompt, which can degrade the LLM's performance and increase latency. Furthermore, static tools can be dangerous if they reference resources that are no longer available.
Dynamic tool selection solves this by allowing the agent to inspect the current context—such as user role, API availability, or previous conversation history—and decide which tools to expose at runtime. PydanticAI excels here because its tool system is deeply integrated with its graph-based execution model.
Implementing Runtime Discovery in PydanticAI
PydanticAI allows tools to be functions or classes with a specific structure. To achieve dynamic selection, we can leverage the fact that tools are resolved during the graph building phase. By using a custom dependency injection container or a factory pattern, we can filter tools before the LLM sees them.
Consider a scenario where an agent has access to both read_file and write_file tools, but the user is currently in "read-only" mode. We want the agent to only see read_file.
from pydantic_ai import Agent, RunContext
from pydantic import BaseModel
from typing import Literal
# Define a simple configuration model
class AgentConfig(BaseModel):
user_role: Literal['admin', 'viewer'] = 'viewer'
# Define the Agent
agent = Agent(
'anthropic:claude-3-opus',
deps_type=AgentConfig
)
# Dynamic Tool Registration Pattern
# Instead of using the @agent.tool decorator statically,
# we can conditionally add tools via the graph or by
# managing the tool set dynamically.
# For simplicity, let's look at a pattern using RunContext
# where tools can check context before execution, or
# better, we filter the tool list before the agent runs.
# Note: In PydanticAI, tools are often defined via decorators.
# To make them dynamic, we can use a 'ToolProvider' pattern.
def create_tools_for_context(config: AgentConfig) -> list[Callable]:
tools = []
if config.user_role == 'admin':
# Define tools inline or reference global ones
@agent.tool
def delete_file(path: str) -> str:
"""Delete a file."""
return f"Deleted {path}"
tools.append(delete_file)
@agent.tool
def read_file(path: str) -> str:
"""Read a file."""
return f"Content of {path}"
tools.append(read_file)
return tools
# In a real application, you would manage the agent's tool registry
# or use a middleware/dependency to inject the correct set of tools
# before the LLM call is made.
Advanced Pattern: Using Dependency Injection for Tool Context
A more robust approach in PydanticAI is to use the RunContext object. This object provides access to the current run's dependencies. You can create a "meta-tool" that allows the LLM to discover other tools on the fly, or use a pre-processing step to narrow down the tool list.
However, the most elegant solution for "Capability Discovery" is to treat tool availability as a state variable in your dependency graph. By having a function that returns the active tools based on the RunContext dependencies, you ensure that the LLM's schema is generated dynamically for each turn.
from pydantic_ai import Agent, RunContext
from typing import Annotated
agent = Agent('anthropic:claude-3-opus')
class Context:
def __init__(self, available_capabilities: list[str]):
self.available_capabilities = available_capabilities
@agent.tool
def use_tool(
ctx: Annotated[RunContext[Context], 'Context'],
tool_name: str,
**kwargs
) -> str:
"""
Dynamically invoke a tool by name.
The LLM sees this single 'use_tool' function,
but can specify which underlying capability to use.
"""
if tool_name not in ctx.deps.available_capabilities:
return f"Error: Tool '{tool_name}' is not available in the current context."
# Dispatch to the actual implementation
# This is a simplified dispatch mechanism
if tool_name == 'search':
return f"Searching for {kwargs.get('query')}"
elif tool_name == 'calculate':
return f"Calculating {kwargs.get('expression')}"
return "Unknown tool"
# When running the agent, inject the context
# async with agent.run('Search for AI news') as run:
# pass # Context would be injected via the run's dependencies
Best Practices and Security Considerations
- Validation: Always validate the tool name and parameters against a whitelist before execution to prevent prompt injection attacks from exploiting dynamic dispatch.
- Logging: Log which tools were exposed to the LLM and which were actually selected for each run. This helps in debugging complex agent behaviors.
- Latency: Be mindful that dynamic tool discovery adds overhead. Cache tool schemas where possible if the context changes infrequently.
Conclusion
Dynamic tool selection in PydanticAI transforms static agents into adaptive systems that can respond to real-time conditions. By leveraging dependency injection and context-aware tool registration, you can build agents that are not only more efficient but also safer and more scalable. As you experiment with these patterns, focus on how the LLM's understanding of available capabilities changes when the toolset is curated for the specific task at hand.