AI Agents with Tools

Learn how to create AI agents that can use tools to interact with external systems and perform actions.

See also: Five-Layer Agent Stack — Tools are part of Layer 3 (the Harness).

Diagram

Agents

Tools

Internet Search

Code Execution

Formatting

Input

Agent 1

Agent 2

Agent 3

Output

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. Step

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

    python
    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. Step

    Assign the tool to an agent

    python
    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!

Implementing Tools Full Code Example

Code

  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

    python
    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

No Code

  1. Install PraisonAI

    Install the core package and duckduckgo_search package:

    Terminal
    pip install praisonai duckduckgo_search
  2. Create Custom Tool

    Create a new file tools.py with the following content:

    python
    from duckduckgo_search import DDGS
    from typing import List, Dict
    
    # 1. Tool
    def internet_search_tool(query: str) -> List[Dict]:
        """
        Perform Internet Search
        """
        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  
  3. Create Agent

    Create a new file agents.yaml with the following content:

    yaml
    framework: praisonai
    topic: create movie script about cat in mars
    agents:  # Canonical: use 'agents' instead of 'roles'
      scriptwriter:
        instructions:  # Canonical: use 'instructions' instead of 'backstory' Expert in dialogue and script structure, translating concepts into
          scripts.
        goal: Write a movie script about a cat in Mars
        role: Scriptwriter
        tools:
          - internet_search_tool # <-- Tool assigned to Agent here
        tasks:
          scriptwriting_task:
            description: Turn the story concept into a production-ready movie script,
              including dialogue and scene details.
            expected_output: Final movie script with dialogue and scene details.
  4. Start Agents

    Execute your script:

    Terminal
    praisonai agents.yaml

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.

python
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")

Built-in Search Tools

PraisonAI includes built-in search tools that work with multiple providers:

python
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
)

Fast Context (Code Search)

Fast Context provides parallel, cached code search for AI agents:

python
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

Tools Overview

Advanced Tool Features

Tool Configuration

python
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

python
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

Tool Integration

Adding Tools to Agents

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

Tool Dependencies

python
# 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 Summary




Forcing Tool Usage with tool_choice

Diagram

tool_choice Options

auto

LLM decides

required

Must call tool

none

Cannot call tools

YAML

yaml
agents:
  researcher:
    role: Research Specialist
    tools:
      - search_web
    tool_choice: required  # Forces the agent to call a tool
    llm: gpt-4o-mini

Python

python
from praisonaiagents import Agent
from praisonaiagents.tools import search_web

# For direct Agent usage, tool_choice is passed via chat()
agent = Agent(
    name="researcher",
    tools=[search_web],
    llm="gpt-4o-mini"
)

# Force tool usage in a specific call
response = agent.chat("Search for AI news", tool_choice="required")
tool_choice string

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)

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.

Diagram

Consumers

SDK Core (praisonaiagents)

BUILTIN_PROFILES

resolve_profiles

lazy getattr

tools/profiles.py

agent.py autonomy

External consumers

tools/init.py
TOOL_MAPPINGS

Tool Resolution

AIUI Provider

CLI Interactive

TUI App

Bots

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

python
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"
))