Tools are external functions and capabilities that extend what agents can do beyond text generation. While language models excel at reasoning and language tasks, tools enable agents to:
Access external data (APIs, databases, web search)
Perform computations (calculations, data analysis)
Take actions (send emails, create files, run code)
Interact with systems (databases, cloud services, IoT devices)
Think of tools as the “hands” of your agent - they transform language understanding into real-world actions.
The simplest way to create a tool is with a Python function:
from swarms import Agentdef search_web(query: str) -> str: """ Search the web for information. Args: query (str): The search query to execute Returns: str: Search results """ # Your search implementation return f"Search results for: {query}"def calculate(expression: str) -> float: """ Evaluate a mathematical expression. Args: expression (str): Mathematical expression to evaluate (e.g., "2 + 2") Returns: float: The calculated result """ return eval(expression) # Be careful with eval in production!# Create agent with toolsagent = Agent( model_name="gpt-4o-mini", tools=[search_web, calculate],)response = agent.run("Search for the current price of Bitcoin and calculate 5 * 100")
Requirements for Tool Functions:
Type hints: All parameters and return values must have type annotations
Docstrings: Clear documentation explaining what the tool does
Parameter descriptions: Document each parameter in the docstring
Without these, the LLM cannot reliably use your tools!
# ✅ Good: Clear, well-documented tooldef fetch_stock_price(symbol: str, date: str = None) -> dict: """ Fetch the stock price for a given symbol. Args: symbol (str): Stock ticker symbol (e.g., "AAPL", "GOOGL") date (str, optional): Date in YYYY-MM-DD format. Defaults to today. Returns: dict: Dictionary containing price, volume, and market cap """ # Implementation return {"price": 150.0, "volume": 1000000, "market_cap": "2.5T"}# ❌ Bad: No type hints or documentationdef get_price(symbol): return 150.0
Simple Python functions passed directly to the agent:
def get_weather(location: str, units: str = "celsius") -> str: """ Get current weather for a location. Args: location (str): City name or coordinates units (str): Temperature units ("celsius" or "fahrenheit") Returns: str: Weather description """ return f"Weather in {location}: 22°{units[0].upper()}, Sunny"agent = Agent( model_name="gpt-4o-mini", tools=[get_weather],)response = agent.run("What's the weather in San Francisco?")
import requestsdef search_web(query: str, num_results: int = 5) -> str: """ Search the web and return results. Args: query (str): Search query string num_results (int): Number of results to return Returns: str: Formatted search results """ # Integration with search API (e.g., Google, DuckDuckGo, Exa) # This is a simplified example return f"Top {num_results} results for '{query}'"
import osdef read_file(filepath: str) -> str: """ Read contents of a file. Args: filepath (str): Path to the file to read Returns: str: File contents """ with open(filepath, 'r') as f: return f.read()def write_file(filepath: str, content: str) -> str: """ Write content to a file. Args: filepath (str): Path where file should be written content (str): Content to write to file Returns: str: Success message """ with open(filepath, 'w') as f: f.write(content) return f"Successfully wrote to {filepath}"def list_files(directory: str) -> list: """ List files in a directory. Args: directory (str): Path to directory Returns: list: List of filenames """ return os.listdir(directory)
from swarms import Agentdef search_web(query: str) -> str: """Search the web for information.""" return f"Search results for: {query}"def calculate(expression: str) -> float: """Perform mathematical calculations.""" return eval(expression)def save_to_file(filename: str, content: str) -> str: """Save content to a file.""" with open(filename, 'w') as f: f.write(content) return f"Saved to {filename}"# Agent with multiple toolsagent = Agent( model_name="gpt-4o-mini", tools=[search_web, calculate, save_to_file], max_loops=5, # Allow multiple tool uses)# Agent can chain tools togetherresponse = agent.run( "Search for the current Bitcoin price, calculate what 10 Bitcoins would cost, " "and save the result to bitcoin_value.txt")
# Check if function has documentationhas_docs = tool_manager.check_func_if_have_docs(my_function)# Check if function has type hintshas_hints = tool_manager.check_func_if_have_type_hints(my_function)# Validate function call stringis_valid = tool_manager.check_str_for_functions_valid(function_call_str)
Provide clear descriptions that help the LLM understand when and how to use the tool:
def search_web(query: str, num_results: int = 10) -> str: """ Search the web using DuckDuckGo and return formatted results. Use this tool when you need current information from the internet, real-time data, or information not in your training data. Args: query (str): The search query. Be specific for better results. num_results (int): Number of results to return (default: 10, max: 50) Returns: str: Formatted search results with titles, URLs, and snippets """
Error Handling
Tools should handle errors gracefully and return informative messages:
Never expose sensitive credentials in tool descriptions
Performance Optimization
Cache frequently used results
Use async operations when possible
Set appropriate timeouts
Limit output size for large responses
def search_web(query: str) -> str: # Cache results for repeated queries cache_key = f"search_{query}" if cache_key in cache: return cache[cache_key] result = perform_search(query) cache[cache_key] = result return result
from swarms.tools import BaseToolclass CustomToolManager(BaseTool): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def load_tools_from_directory(self, directory: str): """Load all Python functions from a directory as tools.""" import importlib.util import inspect tools = [] for file in os.listdir(directory): if file.endswith('.py'): # Load module and extract functions spec = importlib.util.spec_from_file_location( file[:-3], os.path.join(directory, file) ) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) # Get all functions from module for name, obj in inspect.getmembers(module): if inspect.isfunction(obj): tools.append(obj) self.tools = tools return tools