Examples
Tool Usage Example
Examples
Tool Usage Example
Learn how to use and create tools in AgenticFleet
Tool Usage Example
Learn how to use built-in tools and create custom tools in AgenticFleet.
Built-in Tools
Using AgenticFleet’s built-in tools:
from agentic_fleet import Agent
from agentic_fleet.tools import (
WebSearch,
FileReader,
CodeExecutor,
APIClient
)
async def use_built_in_tools():
# Create tools
tools = [
WebSearch(),
FileReader(),
CodeExecutor(),
APIClient()
]
# Create agent with tools
agent = Agent(
name="tool_user",
tools=tools
)
# Use web search
search_result = await agent.use_tool(
"web_search",
query="AgenticFleet documentation"
)
print("Search Result:", search_result)
# Read file
file_content = await agent.use_tool(
"file_reader",
path="example.txt"
)
print("File Content:", file_content)
# Execute code
code_result = await agent.use_tool(
"code_executor",
code="print('Hello, World!')"
)
print("Code Result:", code_result)
# Run example
import asyncio
asyncio.run(use_built_in_tools())
Custom Tools
Creating and using custom tools:
from agentic_fleet.tools import BaseTool
from typing import Dict, Any
class WeatherTool(BaseTool):
name = "weather_tool"
description = "Get weather information"
async def _run(
self,
location: str,
units: str = "celsius"
) -> Dict[str, Any]:
# Simulate weather API call
weather = await self.get_weather(
location,
units
)
return weather
async def get_weather(
self,
location: str,
units: str
) -> Dict[str, Any]:
# Implement actual API call
return {
"location": location,
"temperature": 20,
"units": units,
"condition": "sunny"
}
async def use_custom_tool():
# Create tool
weather_tool = WeatherTool()
# Create agent with tool
agent = Agent(
name="weather_assistant",
tools=[weather_tool]
)
# Use tool
weather = await agent.use_tool(
"weather_tool",
location="London",
units="celsius"
)
print("Weather:", weather)
asyncio.run(use_custom_tool())
Tool Chains
Creating and using tool chains:
from agentic_fleet.tools import ToolChain
async def use_tool_chain():
# Create tools
web_search = WebSearch()
file_reader = FileReader()
code_executor = CodeExecutor()
# Create chain
chain = ToolChain([
web_search,
file_reader,
code_executor
])
# Execute chain
result = await chain.execute(
initial_input="Research and implement"
)
print("Chain Result:", result)
asyncio.run(use_tool_chain())
Advanced Tool Features
Tool with Configuration
from agentic_fleet.tools import ToolConfig
class DatabaseTool(BaseTool):
name = "database_tool"
description = "Database operations"
def __init__(self, config: ToolConfig):
self.config = config
self.connection = None
async def setup(self):
# Connect to database
self.connection = await self.connect(
self.config.connection_string
)
async def _run(
self,
query: str
) -> Dict[str, Any]:
# Execute query
result = await self.connection.execute(
query
)
return {"result": result}
async def cleanup(self):
# Close connection
await self.connection.close()
# Use configured tool
config = ToolConfig(
connection_string="postgresql://..."
)
tool = DatabaseTool(config)
Tool with Validation
from pydantic import BaseModel, Field
class WeatherInput(BaseModel):
location: str = Field(
...,
description="City name"
)
units: str = Field(
default="celsius",
description="Temperature units"
)
class WeatherTool(BaseTool):
name = "weather_tool"
input_model = WeatherInput
async def _run(
self,
location: str,
units: str = "celsius"
) -> Dict[str, Any]:
# Implementation
pass
Tool with Caching
from agentic_fleet.tools import cached_tool
from agentic_fleet.cache import RedisCache
# Create cache
cache = RedisCache(
url="redis://localhost:6379",
ttl=3600
)
@cached_tool(cache=cache)
class CachedWeatherTool(BaseTool):
name = "cached_weather_tool"
async def _run(
self,
location: str
) -> Dict[str, Any]:
# Implementation
pass
Tool with Rate Limiting
from agentic_fleet.tools import rate_limited
@rate_limited(
calls=100,
period=60
)
class RateLimitedTool(BaseTool):
name = "rate_limited_tool"
async def _run(
self,
input_data: str
) -> Dict[str, Any]:
# Implementation
pass
Error Handling
from agentic_fleet.exceptions import ToolError
class RobustTool(BaseTool):
name = "robust_tool"
async def _run(
self,
input_data: str
) -> Dict[str, Any]:
try:
result = await self.process(
input_data
)
return {"result": result}
except Exception as e:
raise ToolError(
f"Tool error: {str(e)}"
)
Tool Monitoring
from agentic_fleet.monitoring import ToolMonitor
# Create monitor
monitor = ToolMonitor()
# Use tool with monitoring
async def monitored_tool_usage():
tool = WeatherTool()
async with monitor.track(tool):
result = await tool.run(
location="London"
)
# Get metrics
metrics = monitor.get_metrics(
tool.name
)
print("Tool Metrics:", metrics)
asyncio.run(monitored_tool_usage())
Best Practices
-
Clear Documentation
class WellDocumentedTool(BaseTool): """Weather information tool. Args: location: City name units: Temperature units Returns: Dict with weather information """ name = "weather_tool"
-
Resource Management
async with tool: result = await tool.run()
-
Error Handling
try: result = await tool.run() except ToolError as e: logger.error(f"Tool error: {e}")
-
Input Validation
def validate_input(self, **kwargs): if "location" not in kwargs: raise ValueError( "Location required" )