Understanding Tools

Tools in PraisonAI are functions that agents can use to interact with external systems, perform computations, or access data. They extend the capabilities of agents beyond just language processing.

Tools Overview

Search Tools

Tools for searching and retrieving information from various sources

File Tools

Tools for reading, writing, and manipulating files

API Tools

Tools for interacting with external APIs and services

Creating Custom Tool

1

Create any function that you want to use as a tool, that performs a specific task.

from duckduckgo_search import DDGS
from typing import List, Dict

# Tool Implementation
def internet_search_tool(query: str) -> List[Dict]:
    """
    Perform Internet Search using DuckDuckGo
    
    Args:
        query (str): The search query string
        
    Returns:
        List[Dict]: List of search results containing title, URL, and snippet
    """
    results = []
    ddgs = DDGS()
    for result in ddgs.text(keywords=query, max_results=5):
        results.append({
            "title": result.get("title", ""),
            "url": result.get("href", ""),
            "snippet": result.get("body", "")
        })
    return results
2

Assign the tool to an agent

    data_agent = Agent(
        name="DataCollector",
        role="Search Specialist",
        goal="Perform internet searches to collect relevant information.",
        backstory="Expert in finding and organising internet data.",
        tools=[internet_search_tool], ## Add the tool to the agent i.e the function name
    )

That's it!

You have created a custom tool and assigned it to an agent.

Implementing Tools Full Code Example

Tools are implemented as Python functions with type hints and docstrings. Here’s a complete example:

from praisonaiagents import Agent, Task, PraisonAIAgents
from duckduckgo_search import DDGS
from typing import List, Dict

# 1. Tool Implementation
def internet_search_tool(query: str) -> List[Dict]:
    """
    Perform Internet Search using DuckDuckGo
    
    Args:
        query (str): The search query string
        
    Returns:
        List[Dict]: List of search results containing title, URL, and snippet
    """
    results = []
    ddgs = DDGS()
    for result in ddgs.text(keywords=query, max_results=5):
        results.append({
            "title": result.get("title", ""),
            "url": result.get("href", ""),
            "snippet": result.get("body", "")
        })
    return results

# 2. Assign the tool to an agent
data_agent = Agent(
    name="DataCollector",
    role="Search Specialist",
    goal="Perform internet searches to collect relevant information.",
    backstory="Expert in finding and organising internet data.",
    tools=[internet_search_tool],
    self_reflect=False
)

# 3. Task Definition
collect_task = Task(
    description="Perform an internet search using the query: 'AI job trends in 2024'. Return results as a list of title, URL, and snippet.",
    expected_output="List of search results with titles, URLs, and snippets.",
    agent=data_agent,
    name="collect_data",
)

# 4. Start Agents
agents = PraisonAIAgents(
    agents=[data_agent],
    tasks=[collect_task],
    process="sequential"
)

agents.start()

Advanced Tool Features

Tool Configuration

def configured_tool(
    query: str,
    max_results: int = 5,
    timeout: int = 10
) -> List[Dict]:
    """
    Example of a configurable tool
    
    Args:
        query (str): Search query
        max_results (int): Maximum number of results
        timeout (int): Request timeout in seconds
        
    Returns:
        List[Dict]: Search results
    """
    # Tool implementation
    pass

Tool Chaining

def chain_tools(input_data: str) -> Dict:
    """
    Example of chaining multiple tools
    
    Args:
        input_data (str): Input data
        
    Returns:
        Dict: Processed results
    """
    # 1. Search for data
    search_results = internet_search_tool(input_data)
    
    # 2. Process results
    processed_data = process_tool(search_results)
    
    # 3. Format output
    return format_tool(processed_data)

Tool Categories

  1. Data Collection Tools

    • Web scraping
    • API integration
    • Database queries
  2. Processing Tools

    • Data transformation
    • Text analysis
    • Image processing
  3. Output Tools

    • File generation
    • Report creation
    • Data visualization

Tool Integration

Adding Tools to Agents

# Multiple tools
agent = Agent(
    name="MultiTool Agent",
    tools=[
        internet_search_tool,
        file_processing_tool,
        api_integration_tool
    ]
)

Tool Dependencies

# Tool with dependencies
def advanced_tool(data: Dict) -> Dict:
    """
    Tool that depends on external libraries
    
    Args:
        data (Dict): Input data
        
    Returns:
        Dict: Processed data
    """
    try:
        import required_library
        # Tool implementation
        return processed_result
    except ImportError:
        raise Exception("Required library not installed")

Tool Guidelines

Best Practices

  1. Type Hints

    • Use Python type hints
    • Define clear input/output types
    • Document complex types
  2. Documentation

    • Write clear docstrings
    • Explain parameters
    • Provide usage examples
  3. Error Handling

    • Handle exceptions gracefully
    • Return meaningful errors
    • Validate inputs

Tool Types

  1. Search Tools

    • Web search
    • Database queries
    • Document search
  2. File Tools

    • Read/write operations
    • File conversion
    • Data extraction
  3. API Tools

    • REST API calls
    • GraphQL queries
    • Service integration

Best Practices Summary

  1. Design Principles

    • Single responsibility
    • Clear interfaces
    • Proper documentation
    • Error handling
  2. Performance

    • Efficient processing
    • Resource management
    • Caching when appropriate
    • Asynchronous operations
  3. Security

    • Input validation
    • Rate limiting
    • API key management
    • Error masking

Was this page helpful?