Skip to content

Tools

CrewAI tools empower agents with capabilities ranging from web searching and data analysis to collaboration and delegating tasks among coworkers. This documentation outlines how to create, integrate, and leverage these tools within the CrewAI framework, including a new focus on collaboration tools.

A tool in CrewAI is a skill or function that agents can utilize to perform various actions. This includes tools from the CrewAI Toolkit and LangChain Tools, enabling everything from simple searches to complex interactions and effective teamwork among agents.

  • Utility: Crafted for tasks such as web searching, data analysis, content generation, and agent collaboration.
  • Integration: Boosts agent capabilities by seamlessly integrating tools into their workflow.
  • Customizability: Provides the flexibility to develop custom tools or utilize existing ones, catering to the specific needs of agents.
  • Error Handling: Incorporates robust error handling mechanisms to ensure smooth operation.
  • Caching Mechanism: Features intelligent caching to optimize performance and reduce redundant operations.
  • Asynchronous Support: Handles both synchronous and asynchronous tools, enabling non-blocking operations.
  • Typed Outputs: Uses optional Pydantic models to give agents clear JSON fields while direct Python calls still receive the tool’s normal return value.

To enhance your agents’ capabilities with crewAI tools, begin by installing our extra tools package:

Terminal window
pip install 'crewai[tools]'

Here’s an example demonstrating their use:

import os
from crewai import Agent, Task, Crew
# Importing crewAI tools
from crewai_tools import (
DirectoryReadTool,
FileReadTool,
SerperDevTool,
WebsiteSearchTool
)
# Set up API keys
os.environ["SERPER_API_KEY"] = "Your Key" # serper.dev API key
os.environ["OPENAI_API_KEY"] = "Your Key"
# Instantiate tools
docs_tool = DirectoryReadTool(directory='./blog-posts')
file_tool = FileReadTool()
search_tool = SerperDevTool()
web_rag_tool = WebsiteSearchTool()
# Create agents
researcher = Agent(
role='Market Research Analyst',
goal='Provide up-to-date market analysis of the AI industry',
backstory='An expert analyst with a keen eye for market trends.',
tools=[search_tool, web_rag_tool],
verbose=True
)
writer = Agent(
role='Content Writer',
goal='Craft engaging blog posts about the AI industry',
backstory='A skilled writer with a passion for technology.',
tools=[docs_tool, file_tool],
verbose=True
)
# Define tasks
research = Task(
description='Research the latest trends in the AI industry and provide a summary.',
expected_output='A summary of the top 3 trending developments in the AI industry with a unique perspective on their significance.',
agent=researcher
)
write = Task(
description='Write an engaging blog post about the AI industry, based on the research analyst's summary. Draw inspiration from the latest blog posts in the directory.',
expected_output='A 4-paragraph blog post formatted in markdown with engaging, informative, and accessible content, avoiding complex jargon.',
agent=writer,
output_file='blog-posts/new_post.md' # The final blog post will be saved here
)
# Assemble a crew with planning enabled
crew = Crew(
agents=[researcher, writer],
tasks=[research, write],
verbose=True,
planning=True, # Enable planning feature
)
# Execute tasks
crew.kickoff()
  • Error Handling: All tools are built with error handling capabilities, allowing agents to gracefully manage exceptions and continue their tasks.
  • Caching Mechanism: All tools support caching, enabling agents to efficiently reuse previously obtained results, reducing the load on external resources and speeding up the execution time. You can also define finer control over the caching mechanism using the cache_function attribute on the tool.

Here is a list of the available tools and their descriptions:

ToolDescription
ApifyActorsToolA tool that integrates Apify Actors with your workflows for web scraping and automation tasks.
BrowserbaseLoadToolA tool for interacting with and extracting data from web browsers.
CodeDocsSearchToolA RAG tool optimized for searching through code documentation and related technical documents.
CodeInterpreterToolA tool for interpreting python code.
ComposioToolEnables use of Composio tools.
CSVSearchToolA RAG tool designed for searching within CSV files, tailored to handle structured data.
DALL-E ToolA tool for generating images using the DALL-E API.
DirectorySearchToolA RAG tool for searching within directories, useful for navigating through file systems.
DOCXSearchToolA RAG tool aimed at searching within DOCX documents, ideal for processing Word files.
DirectoryReadToolFacilitates reading and processing of directory structures and their contents.
ExaSearchToolSearch the web with Exa, the fastest and most accurate web search API. Supports token-efficient highlights and full page content.
FileReadToolEnables reading and extracting data from files, supporting various file formats.
FirecrawlSearchToolA tool to search webpages using Firecrawl and return the results.
FirecrawlCrawlWebsiteToolA tool for crawling webpages using Firecrawl.
FirecrawlScrapeWebsiteToolA tool for scraping webpages URL using Firecrawl and returning its contents.
GithubSearchToolA RAG tool for searching within GitHub repositories, useful for code and documentation search.
SerperDevToolA specialized tool for development purposes, with specific functionalities under development.
TXTSearchToolA RAG tool focused on searching within text (.txt) files, suitable for unstructured data.
JSONSearchToolA RAG tool designed for searching within JSON files, catering to structured data handling.
LlamaIndexToolEnables the use of LlamaIndex tools.
MDXSearchToolA RAG tool tailored for searching within Markdown (MDX) files, useful for documentation.
PDFSearchToolA RAG tool aimed at searching within PDF documents, ideal for processing scanned documents.
PGSearchToolA RAG tool optimized for searching within PostgreSQL databases, suitable for database queries.
Vision ToolA tool for generating images using the DALL-E API.
RagToolA general-purpose RAG tool capable of handling various data sources and types.
ScrapeElementFromWebsiteToolEnables scraping specific elements from websites, useful for targeted data extraction.
ScrapeWebsiteToolFacilitates scraping entire websites, ideal for comprehensive data collection.
WebsiteSearchToolA RAG tool for searching website content, optimized for web data extraction.
XMLSearchToolA RAG tool designed for searching within XML files, suitable for structured data formats.
YoutubeChannelSearchToolA RAG tool for searching within YouTube channels, useful for video content analysis.
YoutubeVideoSearchToolA RAG tool aimed at searching within YouTube videos, ideal for video data extraction.

There are two main ways for one to create a CrewAI tool:

from crewai.tools import BaseTool
from pydantic import BaseModel, Field
class MyToolInput(BaseModel):
"""Input schema for MyCustomTool."""
argument: str = Field(..., description="Description of the argument.")
class MyCustomTool(BaseTool):
name: str = "Name of my tool"
description: str = "What this tool does. It's vital for effective utilization."
args_schema: Type[BaseModel] = MyToolInput
def _run(self, argument: str) -> str:
# Your tool's logic here
return "Tool's result"

When a tool returns structured data, define a Pydantic output model. This gives the agent field names it can trust, such as sku, quantity, or needs_reorder.

Direct Python calls still receive the value your tool returns. When an agent uses the tool, CrewAI sends the agent a JSON string based on the output model.

from crewai.tools import BaseTool
from pydantic import BaseModel
class InventoryResult(BaseModel):
sku: str
quantity: int
needs_reorder: bool
class InventoryTool(BaseTool):
name: str = "Inventory Check"
description: str = "Checks current stock for a product SKU."
def _run(self, sku: str) -> InventoryResult:
quantity = {"SKU-123": 14, "SKU-456": 0}.get(sku, 0)
return InventoryResult(sku=sku, quantity=quantity, needs_reorder=quantity < 5)
tool = InventoryTool()
# Direct calls receive the raw Pydantic object.
result = tool.run(sku="SKU-123")
print(result.quantity)

To send Markdown or another short text format to the agent, override format_output_for_agent. Direct calls to tool.run(...) still return the normal Python value.

class InventoryTool(BaseTool):
name: str = "Inventory Check"
description: str = "Checks current stock for a product SKU."
def _run(self, sku: str) -> InventoryResult:
quantity = {"SKU-123": 14, "SKU-456": 0}.get(sku, 0)
return InventoryResult(sku=sku, quantity=quantity, needs_reorder=quantity < 5)
def format_output_for_agent(self, raw_result: object) -> str:
result = InventoryResult.model_validate(raw_result)
status = "reorder needed" if result.needs_reorder else "stock is healthy"
return f"{result.sku}: {result.quantity} units. {status}."

If you do not override format_output_for_agent, typed outputs are sent to the agent as JSON. Plain string results work as before.

CrewAI supports asynchronous tools, allowing you to implement tools that perform non-blocking operations like network requests, file I/O, or other async operations without blocking the main execution thread.

You can create async tools in two ways:

1. Using the tool Decorator with Async Functions

Section titled “1. Using the tool Decorator with Async Functions”
from crewai.tools import tool
@tool("fetch_data_async")
async def fetch_data_async(query: str) -> str:
"""Asynchronously fetch data based on the query."""
# Simulate async operation
await asyncio.sleep(1)
return f"Data retrieved for {query}"

2. Implementing Async Methods in Custom Tool Classes

Section titled “2. Implementing Async Methods in Custom Tool Classes”
from crewai.tools import BaseTool
class AsyncCustomTool(BaseTool):
name: str = "async_custom_tool"
description: str = "An asynchronous custom tool"
async def _run(self, query: str = "") -> str:
"""Asynchronously run the tool"""
# Your async implementation here
await asyncio.sleep(1)
return f"Processed {query} asynchronously"

Async tools work seamlessly in both standard Crew workflows and Flow-based workflows:

# In standard Crew
agent = Agent(role="researcher", tools=[async_custom_tool])
# In Flow
class MyFlow(Flow):
@start()
async def begin(self):
crew = Crew(agents=[agent])
result = await crew.kickoff_async()
return result

The CrewAI framework automatically handles the execution of both synchronous and asynchronous tools, so you don’t need to worry about how to call them differently.

from crewai.tools import tool
@tool("Name of my tool")
def my_tool(question: str) -> str:
"""Clear description for what this tool is useful for, your agent will need this information to use it."""
# Function logic here
return "Result from your custom tool"
from crewai.tools import tool
@tool
def multiplication_tool(first_number: int, second_number: int) -> str:
"""Useful for when you need to multiply two numbers together."""
return first_number * second_number
def cache_func(args, result):
# In this case, we only cache the result if it's a multiple of 2
cache = result % 2 == 0
return cache
multiplication_tool.cache_function = cache_func
writer1 = Agent(
role="Writer",
goal="You write lessons of math for kids.",
backstory="You're an expert in writing and you love to teach kids but you know nothing of math.",
tools=[multiplication_tool],
allow_delegation=False,
)
#...

Tools are pivotal in extending the capabilities of CrewAI agents, enabling them to undertake a broad spectrum of tasks and collaborate effectively. When building solutions with CrewAI, leverage both custom and existing tools to empower your agents and enhance the AI ecosystem. Consider utilizing error handling, caching mechanisms, and the flexibility of tool arguments to optimize your agents’ performance and capabilities.