FeatureKnowledgeTools
PurposeStatic reference informationDynamic interaction capabilities
AccessRead-only referenceExecute actions and commands
UpdatesManual through filesReal-time through tool calls
StorageKnowledge baseAssigned to specific agents
PersistencePermanent until changedAvailable during agent execution

Quick Start

Tools are functions that agents can use to interact with external systems and perform actions. They are essential for creating agents that can do more than just process text.

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

1

Install PraisonAI

Install the core package:

Terminal
pip install praisonaiagents duckduckgo-search
2

Configure Environment

Terminal
export OPENAI_API_KEY=your_openai_key

Generate your OpenAI API key from OpenAI Use other LLM providers like Ollama, Anthropic, Groq, Google, etc. Please refer to the Models for more information.

3

Create Agent with Tool

Create app.py

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()
4

Start Agents

Execute your script:

Terminal
python app.py

In-build Tools in PraisonAI

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

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

Data Collection Tools

  • Web scraping
  • API integration
  • Database queries

Processing Tools

  • Data transformation
  • Text analysis
  • Image processing

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

Following these best practices will help you create robust, efficient, and secure tools in PraisonAI.

Design Principles


Performance Optimization


Security Best Practices


Pro Tip: Start with these practices from the beginning of your project. It’s easier to maintain good practices than to retrofit them later.

Was this page helpful?