Different Ways to Create Tools

Explore all methods for creating tools in PraisonAI

Choose between functions, classes, remote sources, or packages when extending agent capabilities.

python
from praisonaiagents import Agent, tool

@tool
def add(a: int, b: int) -> int:
    """Add two integers."""
    return a + b

agent = Agent(name="Toolkit", tools=[add])
agent.start("What is 2 plus 3?")

The user picks a tool style, registers it, and confirms the agent selects the right tool.

Diagram

Tool Methods

📋 Style

🔧 Register

✅ Agent Uses It

How It Works

Diagram
ToolAgentUserToolAgentUserTask needing a capabilitySelect and call the registered toolResultAnswer using the result

How to Create Tools as Functions

  1. Define Simple Function
    python
    def calculator_tool(expression: str) -> float:
        """Evaluate a mathematical expression.
    
        Args:
            expression: Math expression to evaluate
    
        Returns:
            Result of the calculation
        """
        return eval(expression)
  2. Use with Agent
    python
    from praisonaiagents import Agent
    
    agent = Agent(
        name="calculator",
        tools=[calculator_tool]
    )

How to Create Tools as Lambda Functions

  1. Define Lambda Tool
    python
    # Simple lambda tool
    uppercase_tool = lambda text: text.upper()
    uppercase_tool.__doc__ = "Convert text to uppercase"
    uppercase_tool.__annotations__ = {"text": str, "return": str}
  2. Use with Agent
    python
    agent = Agent(
        name="formatter",
        tools=[uppercase_tool]
    )

How to Create Tools from External Libraries

  1. Wrap Library Function
    python
    import requests
    
    def http_get_tool(url: str) -> dict:
        """Make HTTP GET request.
    
        Args:
            url: URL to fetch
    
        Returns:
            Response data as dictionary
        """
        response = requests.get(url)
        return {
            "status": response.status_code,
            "content": response.text[:1000]
        }
  2. Use Wrapped Tool
    python
    agent = Agent(
        name="http_agent",
        tools=[http_get_tool]
    )

How to Create Tools in tools.py File

  1. Create tools.py
    python
    # tools.py
    
    def file_reader(path: str) -> str:
        """Read file contents.
    
        Args:
            path: Path to file
    
        Returns:
            File contents
        """
        with open(path, 'r') as f:
            return f.read()
    
    def file_writer(path: str, content: str) -> bool:
        """Write content to file.
    
        Args:
            path: Path to file
            content: Content to write
    
        Returns:
            Success status
        """
        with open(path, 'w') as f:
            f.write(content)
        return True
  2. Reference in Template
    yaml
    # agents.yaml
    roles:
      file_agent:
        tools:
          - file_reader
          - file_writer

How to Create Tools in a Package

  1. Create Package Structure
    my_tools/
    ├── __init__.py
    ├── search.py
    └── database.py
  2. Define Tools in Module
    python
    # my_tools/search.py
    
    def web_search(query: str) -> list:
        """Search the web.
    
        Args:
            query: Search query
    
        Returns:
            List of results
        """
        return [{"title": "Result", "url": "https://example.com"}]
  3. Export in __init__.py
    python
    # my_tools/__init__.py
    from .search import web_search
    from .database import db_query
    
    __all__ = ["web_search", "db_query"]
  4. Use as tools_source
    yaml
    # TEMPLATE.yaml
    requires:
      tools_sources:
        - my_tools

How to Create Tools with Decorators

  1. Use Tool Decorator
    python
    from praisonaiagents import tool
    
    @tool
    def decorated_tool(query: str) -> str:
        """A decorated tool function.
    
        Args:
            query: Input query
    
        Returns:
            Processed result
        """
        return f"Processed: {query}"
  2. Use with Agent
    python
    agent = Agent(
        name="decorated_agent",
        tools=[decorated_tool]
    )

How to Add Tools via CLI

  1. Add Package Tools
    bash
    praisonai tools add pandas
  2. Add Local File
    bash
    praisonai tools add ./my_tools.py
  3. Add from GitHub
    bash
    praisonai tools add github:user/repo/tools
  4. Verify Added Tools
    bash
    praisonai tools list

How to Create Tools with Choice Parameters

  1. Use Literal for Fixed Options
    python
    from typing import Literal
    from praisonaiagents import Agent, tool
    
    @tool
    def format_text(text: str, style: Literal["bold", "italic", "underline"]) -> str:
        """Format text with specified style."""
        if style == "bold":
            return f"**{text}**"
        elif style == "italic":
            return f"*{text}*"
        else:
            return f"__{text}__"
    
    agent = Agent(
        instructions="You format text",
        tools=[format_text]
    )
    
    agent.start("Make this text bold")

See the Tool Parameter Types page for complete guide on using Optional, Union, Literal, Enum, List, and Dict types.

Tool Creation Methods Comparison

MethodBest ForComplexity
FunctionSimple toolsLow
LambdaOne-linersLow
ClassStateful toolsMedium
PackageReusable toolsMedium
DecoratorEnhanced toolsLow
External wrapLibrary integrationMedium
CLI addQuick setupLow

Best Practices

Start with a plain function and @tool

The function-plus-decorator path has the lowest complexity and covers most tools — reach for classes only when you need shared state.

Use classes for stateful tools

When a tool holds a connection or cache, a class keeps that state tidy; pass the bound methods to the agent’s tools list.

Wrap external libraries thinly

Adapt a library call into a typed, docstringed function so the model gets a clean schema without the library’s full surface.


Related