Skip to main content
In Agency Swarm, tools enable agents to perform specific actions and interact with external systems. The framework supports two approaches for creating custom tools depending on the version you’re using. Framework supports 2 methods of creating tools:
  1. Using agency-swarm’s BaseTool class.
  2. Using openai’s @function_tool decorator with async functions.
Explore the sections below to find a method that suits your approach the best.
  • BaseTool
  • FunctionTool
In Agency Swarm’s approach, tools are Python classes that inherit from BaseTool. They are defined using Pydantic, a data validation library. Each BaseTool must implement the run method, which is the main method that will be called when the tool is invoked by an agent.

Step-by-step Guide

To create a custom tool, typically you need to follow these steps:
1

Add Import Statements

On top of your tool file, import the necessary modules and classes.
from agency_swarm.tools import BaseTool
from pydantic import Field, model_validator
# ... other imports
2

Define the Tool Class and Docstring

Create a new class that inherits from BaseTool. Write a clear docstring describing the tool’s purpose. This docstring is crucial as it helps agents understand how to use the tool.
class Calculator(BaseTool):
    """
    A simple calculator tool that evaluates mathematical expressions.
    """
3

Define Input Fields

Use Pydantic fields to define the inputs your tool will accept.
expression: str = Field(..., description="The mathematical expression to evaluate.")
You can use Pydantic’s validators to verify the inputs. This can be extremely effective to avoid hallucinations or other errors in production.
@model_validator(mode="after")
def validate_expression(self):
    if self.expression.endswith("/0"):
        raise ValueError("Division by zero is not permitted")
4

Implement the run Method

Add the functionality that will be executed when the tool is called.
async def run(self):
    # Implement the tool's functionality
    result = eval(self.expression)
    return str(result)
The run method should return a string, which is the tool’s output that the agent will see and use in its response.
5

Test the Tool Independently

Test the tool independently to ensure it behaves as expected. We recommend adding a if __name__ == "__main__": block at the end of the tool file:
import asyncio

if __name__ == "__main__":
    calc = Calculator(expression="2 + 2 * 3")
    print(asyncio.run(calc.run()))  # Output should be '8'
6

Add the Tool to an Agent

After your tool works as expected, simply add it to an agent’s list of tools.
from agency_swarm import Agent
from .tools.calculator import Calculator

agent = Agent(
    name="MathAgent",
    tools=[Calculator],
    # Other agent parameters
)
Alternatively, you can simply place the tool file in the tools_folder directory and it will be automatically added to the agent.
from agency_swarm import Agent
agent = Agent(
    name="MathAgent",
    tools_folder="./tools",
    # Other agent parameters
)
Each file in the tools_folder should contain a class that is named exactly the same as the file name. For example, Calculator.py should contain a Calculator class.

Full Code Example

Below is the full code example for a calculator tool above.
# calculator.py
from agency_swarm.tools import BaseTool
from pydantic import Field, model_validator

class Calculator(BaseTool):
    """
    A simple calculator tool that evaluates mathematical expressions.
    """
    expression: str = Field(..., description="The mathematical expression to evaluate.")

    @model_validator(mode="after")
    def validate_expression(self):
        if self.expression.endswith("/0"):
            raise ValueError("Division by zero is not permitted")

    async def run(self):
        result = eval(self.expression)
        return str(result)

if __name__ == "__main__":
    import asyncio

    calc = Calculator(expression="2 + 2 * 3")
    print(asyncio.run(calc.run()))  # Output should be '8'

Next Steps

I