Skip to main content
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, AgentTeam
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],
    reflection=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 = AgentTeam(
    agents=[data_agent],
    tasks=[collect_task],
    process="sequential"
)

agents.start()
4

Start Agents

Execute your script:
Terminal
python app.py

MCP Tools (Model Context Protocol)

MCP allows agents to use external tools via standardized protocols. This is the recommended way to add powerful tools to your agents.
from praisonaiagents import Agent, MCP

# Use MCP tools with environment variables
agent = Agent(
    instructions="Search the web for information",
    tools=MCP(
        command="npx",
        args=["-y", "@anthropic/mcp-server-brave-search"],
        env={"BRAVE_API_KEY": "your-api-key"}
    )
)

agent.start("Search for AI trends in 2025")

MCP Overview

Introduction to Model Context Protocol

MCP Transports

stdio, HTTP, WebSocket, and SSE transports

Built-in Search Tools

PraisonAI includes built-in search tools that work with multiple providers:
from praisonaiagents import Agent

# Tavily Search (recommended)
agent = Agent(
    instructions="Search and analyze information",
    tools=["tavily"]  # Requires TAVILY_API_KEY
)

# You.com Search
agent = Agent(
    instructions="Search the web",
    tools=["you"]  # Requires YOU_API_KEY
)

# Exa Search
agent = Agent(
    instructions="Find relevant content",
    tools=["exa"]  # Requires EXA_API_KEY
)

Tavily

AI-optimized search with web search, news, and content extraction

You.com

Web search with AI-powered results

Exa

Neural search for finding similar content
Fast Context provides rapid parallel code search for AI agents - 10-20x faster than traditional methods:
from praisonaiagents import Agent
from praisonaiagents.context.fast import FastContext

# Create agent with context management
agent = Agent(
    instructions="You are a code assistant",
    context=True,  # Enable context management
)

# Use FastContext directly for code search
fc = FastContext(workspace_path="/path/to/codebase")
result = fc.search("find authentication handlers")
context = result.to_context_string() if result.files else None

Fast Context

Rapid parallel code search with caching and multi-language support

In-build Tools in PraisonAI

Search Tools

Tools for searching and retrieving information from various sources

Tavily Tools

AI-optimized web search, news, and content extraction

You.com Tools

Web search with AI-powered results

Exa Tools

Neural search for finding similar content

Python Tools

Essential Python utilities for data manipulation and scripting

Spider Tools

Web crawling and scraping capabilities for data extraction

Arxiv Tools

Access and search academic papers from arXiv repository

Newspaper Tools

Extract and parse content from news articles and websites

DuckDB Tools

Fast analytical SQL database operations and queries

DuckDuckGo Tools

Web search functionality using DuckDuckGo’s API

SearxNG Tools

Privacy-focused web search using local SearxNG instance

Calculator Tools

Perform mathematical calculations and conversions

YAML Tools

Parse and manipulate YAML format data

JSON Tools

Handle JSON data structures and operations

Pandas Tools

Data analysis and manipulation using Pandas

YFinance Tools

Fetch financial market data from Yahoo Finance

Shell Tools

Execute shell commands and system operations

AST-Grep Tools

AST-based structural code search and rewrite

Wikipedia Tools

Access and search Wikipedia articles and data

XML Tools

Process and manipulate XML format data

File Tools

File system operations and management utilities

Excel Tools

Work with Excel spreadsheets and workbooks

CSV Tools

Handle CSV file operations and transformations

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

Each tool should have one clear purpose and do it well. Avoid creating tools that try to do too many things.
# Good Example
def process_image(image: np.array) -> np.array:
    return processed_image

# Avoid
def process_and_save_and_upload(image):
    # Too many responsibilities
    pass
Define explicit input/output types and maintain consistent parameter naming.
def search_tool(
    query: str,
    max_results: int = 10
) -> List[Dict[str, Any]]:
    """
    Search for information with clear parameters
    """
    pass
Always include detailed docstrings and type hints.
def analyze_text(
    text: str,
    language: str = "en"
) -> Dict[str, float]:
    """
    Analyze text sentiment and emotions.
    
    Args:
        text: Input text to analyze
        language: ISO language code
        
    Returns:
        Dict with sentiment scores
    """
    pass

Performance Optimization

Optimize resource usage and processing time.
# Use generators for large datasets
def process_large_data():
    for chunk in data_generator():
        yield process_chunk(chunk)
Properly handle resource allocation and cleanup.
async with aiohttp.ClientSession() as session:
    # Resource automatically managed
    await process_data(session)
Implement caching for frequently accessed data.
@cache.memoize(timeout=300)
def expensive_operation(data: str) -> Dict:
    return process_expensive(data)
Use async/await for I/O-bound operations.
async def fetch_data(urls: List[str]):
    async with aiohttp.ClientSession() as session:
        tasks = [fetch_url(session, url) for url in urls]
        return await asyncio.gather(*tasks)

Security Best Practices

Always validate and sanitize inputs to prevent security vulnerabilities.
def process_user_input(data: str) -> str:
    if not isinstance(data, str):
        raise ValueError("Input must be string")
    return sanitize_input(data.strip())
Implement rate limiting for API calls to prevent abuse.
@rate_limit(calls=100, period=60)
async def api_call():
    return await make_request()
Securely handle API keys and credentials using environment variables.
# Use environment variables
api_key = os.getenv('API_KEY')
if not api_key:
    raise ConfigError("API key not found")
Hide sensitive information in error messages to prevent information leakage.
try:
    result = process_sensitive_data()
except Exception as e:
    # Log detailed error internally
    logger.error(f"Detailed error: {str(e)}")
    # Return sanitized error to user
    raise PublicError("Processing failed")

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

Forcing Tool Usage with tool_choice

By default, LLMs may skip calling tools even when instructed. Use tool_choice to control this behavior.
agents:
  researcher:
    role: Research Specialist
    tools:
      - search_web
    tool_choice: required  # Forces the agent to call a tool
    llm: gpt-4o-mini
tool_choice
string
default:"auto"
Controls when the LLM calls tools:
  • auto - LLM decides whether to call tools (default)
  • required - LLM must call a tool before responding
  • none - LLM cannot call tools (text response only)
Use tool_choice: required in YAML workflows when you need guaranteed tool execution. This is especially important for research agents that must search the web.

Tool Profiles

Tool profiles are composable, named sets of tools that eliminate duplication across agent configurations. The SDK ships with built-in profiles that auto-sync to all consumers.

Built-in Profiles

ProfileToolsDescription
file_opsread_file, write_file, list_files, copy_file, move_file, delete_file, get_file_infoFile system operations
shellexecute_command, list_processes, get_system_infoShell and system tools
webinternet_search, search_web, web_crawlWeb search and crawling
memorystore_memory, search_memoryActive memory store/search
learningstore_learning, search_learningCategorized knowledge store/search
scheduleschedule_add, schedule_list, schedule_removeAgent-centric scheduling
code_intelligenceast_grep_search, ast_grep_rewrite, ast_grep_scanStructural code search
code_execexecute_code, analyze_code, format_code, lint_codeCode execution and analysis
autonomyAll of the above combinedDefault for autonomous agents

Using Profiles

from praisonaiagents.tools.profiles import resolve_profiles

# Get tools from specific profiles
tool_names = resolve_profiles("file_ops", "web", "memory")

# Register custom profiles
from praisonaiagents.tools.profiles import register_profile, ToolProfile
register_profile(ToolProfile(
    name="my_tools",
    tools=["my_custom_tool"],
    description="My custom tool set"
))