agents.react.dynamic_react_agentΒΆ
Dynamic React Agent with Tool Loading Capabilities.
This module provides DynamicReactAgent, an enhanced ReactAgent that can dynamically discover, load, and activate tools based on task requirements using the Dynamic Activation Pattern.
Based on: - @project_docs/active/patterns/dynamic_activation_pattern.md - @notebooks/tool_loader.ipynb pattern for tool loading - @packages/haive-agents/examples/supervisor/advanced/dynamic_activation_example.py
ClassesΒΆ
ReactAgent with dynamic tool loading capabilities. |
|
Specialized state for dynamic tool management. |
Module ContentsΒΆ
- class agents.react.dynamic_react_agent.DynamicReactAgent(/, **data)ΒΆ
Bases:
haive.agents.react.agent.ReactAgent
ReactAgent with dynamic tool loading capabilities.
This agent extends ReactAgent with the ability to dynamically discover, load, and activate tools based on task requirements. It uses the Dynamic Activation Pattern with MetaStateSchema for component tracking.
- Key Features:
Dynamic tool discovery using ComponentDiscoveryAgent
Automatic tool loading from documentation
Tool activation and deactivation management
Usage tracking and statistics
Recompilation support for new tools
MetaStateSchema integration for tracking
- Parameters:
name β Agent name
engine β AugLLMConfig for the agent
state_schema β DynamicToolState (set automatically)
data (Any)
- Private Attributes:
_discovery_agent: ComponentDiscoveryAgent for finding tools _meta_self: MetaStateSchema wrapper for self-tracking _tool_loader: Tool loader for actual tool instantiation
Examples
Basic dynamic tool loading:
from haive.agents.react.dynamic_react_agent import DynamicReactAgent from haive.core.engine.aug_llm import AugLLMConfig # Create agent with discovery agent = DynamicReactAgent.create_with_discovery( name="dynamic_react", document_path="@haive-tools", engine=AugLLMConfig() ) # Task that needs specific tools result = await agent.arun("Calculate compound interest and create a chart") # Agent automatically discovers and loads needed tools active_tools = agent.get_active_tool_names() print(f"Tools used: {', '.join(active_tools)}")
Manual tool discovery:
# Discover tools for specific task tools = await agent.discover_and_load_tools("data visualization") print(f"Loaded {len(tools)} tools for visualization") # Use agent with newly loaded tools result = await agent.arun("Create a bar chart from this data")
Tool management:
# Get tool usage statistics stats = agent.get_tool_usage_stats() print(f"Most used tool: {max(stats, key=stats.get)}") # Categorize tools agent.categorize_tool("calculator", "math") agent.categorize_tool("chart_maker", "visualization")
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- async activate_tool_by_name(tool_name)ΒΆ
Activate a tool by name.
- Parameters:
tool_name (str) β Name of tool to activate
- Returns:
True if activation succeeded
- Return type:
Examples
Activate specific tool:
success = await agent.activate_tool_by_name("calculator") if success: print("Calculator activated successfully")
- categorize_tool(tool_name, category)ΒΆ
Categorize a tool by type.
- Parameters:
- Return type:
None
Examples
Categorize tools:
agent.categorize_tool("calculator", "math") agent.categorize_tool("web_search", "web")
- classmethod create_with_discovery(name, document_path, engine, use_mcp=False, **kwargs)ΒΆ
Factory method to create agent with discovery capabilities.
- Parameters:
- Returns:
DynamicReactAgent with discovery capabilities
- Return type:
Examples
Create with Haive tools:
agent = DynamicReactAgent.create_with_discovery( name="haive_react", document_path="@haive-tools", engine=AugLLMConfig() )
Create with custom tools and MCP:
agent = DynamicReactAgent.create_with_discovery( name="custom_react", document_path="/path/to/custom/tools", engine=AugLLMConfig(temperature=0.3), use_mcp=True )
- classmethod create_with_rag_tooling(name, engine, rag_documents, tool_documents=None, use_mcp=False, **kwargs)ΒΆ
Factory method to create agent with RAG-based tool discovery.
This creates a DynamicReactAgent that can request tools from a RAG agent based on document content. The agent will have both reasoning capabilities and the ability to discover and use tools dynamically.
- Parameters:
name (str) β Agent name
engine (haive.core.engine.aug_llm.AugLLMConfig) β AugLLMConfig for the agent
rag_documents (list[str]) β List of documents for RAG knowledge base
tool_documents (list[str] | None) β Optional separate documents for tool discovery
use_mcp (bool) β Whether to use MCP (Model Context Protocol) for tools
**kwargs β Additional arguments for agent
- Returns:
DynamicReactAgent with RAG-based tool discovery
- Return type:
Examples
Create with RAG knowledge and tool discovery:
documents = [ "Python programming guide with examples", "Data analysis techniques and tools", "Machine learning algorithms overview" ] agent = DynamicReactAgent.create_with_rag_tooling( name="rag_react", engine=AugLLMConfig(), rag_documents=documents )
Create with separate tool discovery documents:
knowledge_docs = ["Domain knowledge documents..."] tool_docs = ["Tool documentation and examples..."] agent = DynamicReactAgent.create_with_rag_tooling( name="specialized_react", engine=AugLLMConfig(), rag_documents=knowledge_docs, tool_documents=tool_docs, use_mcp=True )
- classmethod create_with_tools(name, tools, engine, **kwargs)ΒΆ
Factory method to create agent with pre-registered tools.
- Parameters:
- Returns:
DynamicReactAgent with pre-registered tools
- Return type:
Examples
Create with specific tools:
from langchain_core.tools import tool @tool def calculator(expression: str) -> float: '''Calculate mathematical expression.''' return eval(expression) tools = [ { "id": "calc", "name": "Calculator", "description": "Mathematical calculations", "component": calculator, "category": "math" } ] agent = DynamicReactAgent.create_with_tools( name="tool_react", tools=tools, engine=AugLLMConfig() )
- deactivate_tool_by_name(tool_name)ΒΆ
Deactivate a tool by name.
- Parameters:
tool_name (str) β Name of tool to deactivate
- Returns:
True if deactivation succeeded
- Return type:
Examples
Deactivate specific tool:
success = agent.deactivate_tool_by_name("calculator") if success: print("Calculator deactivated successfully")
- async discover_and_load_tools(task)ΒΆ
Discover and load tools for a specific task.
- Parameters:
task (str) β Task description to find tools for
- Returns:
List of loaded BaseTool instances
- Return type:
list[langchain_core.tools.BaseTool]
Examples
Discover tools for calculation:
tools = await agent.discover_and_load_tools("mathematical calculations") print(f"Loaded {len(tools)} math tools")
Discover tools for data processing:
tools = await agent.discover_and_load_tools("data analysis and visualization") for tool in tools: print(f"Loaded tool: {tool.name}")
- async discover_and_load_tools_legacy(task)ΒΆ
Legacy version of discover_and_load_tools for backward compatibility.
- get_active_tool_names()ΒΆ
Get names of all active tools.
Examples
List active tools:
tool_names = agent.get_active_tool_names() print(f"Active tools: {', '.join(tool_names)}")
- get_registry_stats()ΒΆ
Get statistics about the tool registry.
Examples
Show registry status:
stats = agent.get_registry_stats() print(f"Total tools: {stats['total_components']}") print(f"Active tools: {stats['active_components']}") print(f"Most used: {stats['most_used_component']}")
- get_tool_usage_stats()ΒΆ
Get tool usage statistics.
Examples
Get usage statistics:
stats = agent.get_tool_usage_stats() most_used = max(stats.items(), key=lambda x: x[1]) print(f"Most used tool: {most_used[0]} ({most_used[1]} times)")
- get_tools_by_category(category)ΒΆ
Get tools in a specific category.
- Parameters:
category (str) β Category to get tools for
- Returns:
List of tool names in the category
- Return type:
Examples
Get math tools:
math_tools = agent.get_tools_by_category("math") print(f"Math tools: {', '.join(math_tools)}")
- setup_agent()ΒΆ
Setup the dynamic React agent.
This method is called during agent initialization to set up the agentβs internal state and discovery capabilities.
- Return type:
None
- class agents.react.dynamic_react_agent.DynamicToolState(/, **data)ΒΆ
Bases:
haive.core.schema.prebuilt.dynamic_activation_state.DynamicActivationState
Specialized state for dynamic tool management.
Extends DynamicActivationState with tool-specific functionality for ReactAgent tool loading and management.
- Parameters:
tool_categories β Categorization of tools by type
tool_usage_stats β Usage statistics for each tool
last_tool_discovery β Timestamp of last tool discovery
discovery_queries β History of discovery queries
data (Any)
Examples
Basic tool state usage:
state = DynamicToolState() # Track tool categories state.tool_categories = { "math": ["calculator", "statistics"], "web": ["search", "scraper"], "file": ["reader", "writer"] } # Track tool usage state.tool_usage_stats = { "calculator": 5, "search": 3, "reader": 2 }
Get active tools:
active_tools = state.get_active_tools() for tool in active_tools: print(f"Active tool: {tool.name}")
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- categorize_tool(tool_name, category)ΒΆ
Categorize a tool by type.
- Parameters:
- Return type:
None
Examples
Categorize tools:
state.categorize_tool("calculator", "math") state.categorize_tool("web_search", "web") state.categorize_tool("file_reader", "file")
- get_active_tools()ΒΆ
Get all active tools as LangChain tools.
- Returns:
List of active BaseTool instances
- Return type:
list[langchain_core.tools.BaseTool]
Examples
Get active tools for agent:
tools = state.get_active_tools() agent_tools = [tool for tool in tools if isinstance(tool, BaseTool)]
- get_tool_usage_stats()ΒΆ
Get tool usage statistics.
Examples
Get usage statistics:
stats = state.get_tool_usage_stats() most_used = max(stats.items(), key=lambda x: x[1]) print(f"Most used tool: {most_used[0]} ({most_used[1]} times)")
- get_tools_by_category(category)ΒΆ
Get tools in a specific category.
- Parameters:
category (str) β Category to get tools for
- Returns:
List of tool names in the category
- Return type:
Examples
Get math tools:
math_tools = state.get_tools_by_category("math") print(f"Math tools: {', '.join(math_tools)}")
- track_tool_usage(tool_name)ΒΆ
Track usage of a specific tool.
- Parameters:
tool_name (str) β Name of the tool that was used
- Return type:
None
Examples
Track tool usage:
state.track_tool_usage("calculator") state.track_tool_usage("search") # Check usage stats print(f"Calculator used {state.tool_usage_stats['calculator']} times")