Here’s a simple example of creating a tool and using it with an agent:
from swarms import Agentdef calculate_roi(investment: float, return_amount: float) -> str: """ Calculate Return on Investment (ROI) Args: investment (float): Initial investment amount return_amount (float): Return amount received Returns: str: ROI percentage and analysis """ roi = ((return_amount - investment) / investment) * 100 return f"ROI: {roi:.2f}%. Investment: ${investment:,.2f}, Return: ${return_amount:,.2f}"# Create agent with the toolagent = Agent( agent_name="Financial-Analyst", system_prompt="You are a financial analyst. Use the calculate_roi tool to analyze investments.", model_name="gpt-5.4", max_loops=1, tools=[calculate_roi], # Add tools here)# Agent will automatically use the tool when neededresponse = agent.run( "What's the ROI if I invest $10,000 and get back $15,000?")print(response)
Agents can use multiple tools in a single workflow:
from swarms import Agentimport httpximport jsondef search_stocks(query: str) -> str: """ Search for stock information Args: query (str): Stock symbol or company name Returns: str: Stock information """ # Implementation here return f"Stock information for {query}"def analyze_financials(stock_symbol: str) -> str: """ Analyze financial statements for a stock Args: stock_symbol (str): Stock ticker symbol Returns: str: Financial analysis """ # Implementation here return f"Financial analysis for {stock_symbol}"def calculate_metrics(revenue: float, expenses: float) -> str: """ Calculate financial metrics Args: revenue (float): Total revenue expenses (float): Total expenses Returns: str: Calculated metrics including profit margin """ profit = revenue - expenses margin = (profit / revenue) * 100 if revenue > 0 else 0 return f"Profit: ${profit:,.2f}, Margin: {margin:.2f}%"# Agent with multiple toolsmulti_tool_agent = Agent( agent_name="Investment-Analyst", system_prompt="You are an investment analyst. Use the available tools to research and analyze stocks.", model_name="gpt-5.4", max_loops=3, tools=[search_stocks, analyze_financials, calculate_metrics],)result = multi_tool_agent.run( "Analyze Apple (AAPL) stock and provide investment recommendation")print(result)
Simple Python functions with type hints and docstrings:
def get_weather(city: str, units: str = "celsius") -> str: """ Get current weather for a city Args: city (str): City name units (str): Temperature units (celsius or fahrenheit) Returns: str: Weather information """ # API call here return f"Weather in {city}: 22°C, Sunny"agent = Agent( model_name="gpt-5.4", tools=[get_weather],)
def analyze_sentiment(text: str) -> str: """ Analyze sentiment of text This tool uses natural language processing to determine whether the sentiment of the input text is positive, negative, or neutral. Args: text (str): The text to analyze. Should be at least 10 characters. Returns: str: Sentiment analysis result with score and classification Example: >>> analyze_sentiment("I love this product!") "Sentiment: Positive (Score: 0.92)" """ # Implementation pass
from loguru import loggerdef logged_tool(param: str) -> str: """ Tool with logging """ logger.info(f"Tool called with param: {param}") try: result = execute(param) logger.success(f"Tool completed successfully") return result except Exception as e: logger.error(f"Tool failed: {e}") raise
swarms.tools.tool_registry provides ToolStorage, a named registry of tool callables. Tools are keyed by their function name — add_tool reads func.__name__, so there is no separate label to pass.
from swarms import Agentfrom swarms.tools.tool_registry import ToolStorage# Create tool storageregistry = ToolStorage( name="Research Tools", description="Search and analysis tools for the agent",)# Register tools (keyed by function name: "exa_search", "calculate_metrics")registry.add_many_tools([exa_search, calculate_metrics])# Pull a specific tool back out by namesearch = registry.get_tool("exa_search")# Hand the registered tools to an agentagent = Agent( model_name="gpt-5.4", tools=[registry.get_tool(name) for name in ("exa_search", "calculate_metrics")],)
The tool_registry decorator registers a function into a ToolStorage at definition time:
from swarms.tools.tool_registry import ToolStorage, tool_registrystorage = ToolStorage(name="Math Tools", description="Arithmetic helpers")@tool_registry(storage)def calculate_roi(investment: float, return_amount: float) -> str: """Calculate return on investment as a percentage.""" roi = ((return_amount - investment) / investment) * 100 return f"ROI: {roi:.2f}%"
ToolStorage.list_tools() returns a JSON string of registry metadata, not a list of callables — build the agent’s tools list with get_tool(name) as shown above.
🤖 Agent: Financial-Analyst━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━🔧 Using tool: calculate_roi Arguments: {"investment": 10000, "return_amount": 15000}📊 Tool Result: ROI: 50.00%. Investment: $10,000.00, Return: $15,000.00💡 Analysis: Based on the ROI calculation, this investment returned 50%, which is an excellent return. The investment of $10,000 generated a profit of $5,000, indicating strong performance.