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).
| Feature | Knowledge | Tools |
|---|---|---|
| Purpose | Static reference information | Dynamic interaction capabilities |
| Access | Read-only reference | Execute actions and commands |
| Updates | Manual through files | Real-time through tool calls |
| Storage | Knowledge base | Assigned to specific agents |
| Persistence | Permanent until changed | Available 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
- 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 - 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 )
Implementing Tools Full Code Example
Code
- Install PraisonAI
Install the core package:
Terminal pip install praisonaiagents duckduckgo-search - Configure Environment
Terminal export OPENAI_API_KEY=your_openai_keyGenerate your OpenAI API key from OpenAI Use other LLM providers like Ollama, Anthropic, Groq, Google, etc. Please refer to the Models for more information.
- Create Agent with Tool
Create
app.pypython 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() - Start Agents
Execute your script:
Terminal python app.py
No Code
- Install PraisonAI
Install the core package and duckduckgo_search package:
Terminal pip install praisonai duckduckgo_search - Create Custom Tool
Create a new file
tools.pywith 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 - Create Agent
Create a new file
agents.yamlwith 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. - 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.
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")Introduction to Model Context Protocol
MCP Transportsstdio, 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
)AI-optimized search with web search, news, and content extraction
You.comWeb search with AI-powered results
ExaNeural search for finding similar content
Fast Context (Code Search)
Fast Context provides parallel, cached code search for AI agents:
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 NoneRapid parallel code search with caching and multi-language support
In-build Tools in PraisonAI
Tools for searching and retrieving information from various sources
Tavily ToolsAI-optimized web search, news, and content extraction
You.com ToolsWeb search with AI-powered results
Exa ToolsNeural search for finding similar content
Python ToolsEssential Python utilities for data manipulation and scripting
Spider ToolsWeb crawling and scraping capabilities for data extraction
Arxiv ToolsAccess and search academic papers from arXiv repository
Newspaper ToolsExtract and parse content from news articles and websites
DuckDB ToolsFast analytical SQL database operations and queries
DuckDuckGo ToolsWeb search functionality using DuckDuckGo’s API
SearxNG ToolsPrivacy-focused web search using local SearxNG instance
Calculator ToolsPerform mathematical calculations and conversions
YAML ToolsParse and manipulate YAML format data
JSON ToolsHandle JSON data structures and operations
Pandas ToolsData analysis and manipulation using Pandas
YFinance ToolsFetch financial market data from Yahoo Finance
Shell ToolsExecute shell commands and system operations
AST-Grep ToolsAST-based structural code search and rewrite
Wikipedia ToolsAccess and search Wikipedia articles and data
XML ToolsProcess and manipulate XML format data
File ToolsFile system operations and management utilities
Excel ToolsWork with Excel spreadsheets and workbooks
CSV ToolsHandle CSV file operations and transformations
Tools Overview
Tools for searching and retrieving information from various sources
File ToolsTools for reading, writing, and manipulating files
API ToolsTools 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
passTool 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
- Web scraping
- API integration
- Database queries
- Data transformation
- Text analysis
- Image processing
- 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
- Type Hints
- Use Python type hints
- Define clear input/output types
- Document complex types
- Documentation
- Write clear docstrings
- Explain parameters
- Provide usage examples
- Error Handling
- Handle exceptions gracefully
- Return meaningful errors
- Validate inputs
- Search Tools
- Web search
- Database queries
- Document search
- File Tools
- Read/write operations
- File conversion
- Data extraction
- API Tools
- REST API calls
- GraphQL queries
- Service integration
Best Practices Summary
Forcing Tool Usage with tool_choice
YAML
agents:
researcher:
role: Research Specialist
tools:
- search_web
tool_choice: required # Forces the agent to call a tool
llm: gpt-4o-miniPython
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")stringControls 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.
Built-in Profiles
| Profile | Tools | Description |
|---|---|---|
file_ops | read_file, write_file, list_files, copy_file, move_file, delete_file, get_file_info | File system operations |
shell | execute_command, list_processes, get_system_info | Shell and system tools |
web | internet_search, search_web, web_crawl | Web search and crawling |
memory | store_memory, search_memory | Active memory store/search |
learning | store_learning, search_learning | Categorized knowledge store/search |
schedule | schedule_add, schedule_list, schedule_remove | Agent-centric scheduling |
code_intelligence | ast_grep_search, ast_grep_rewrite, ast_grep_scan | Structural code search |
code_exec | execute_code, analyze_code, format_code, lint_code | Code execution and analysis |
autonomy | All of the above combined | Default 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"
))