跳转到主要内容

文档索引

获取完整文档索引: https://docs.crewai.com.cn/llms.txt

在深入了解之前,请使用此文件来浏览所有可用页面。

概述

CrewAI 工具赋予智能体各种能力,从网络搜索、数据分析,到团队协作及在同事间委派任务。本文档概述了如何在 CrewAI 框架内创建、集成和利用这些工具,并重点介绍了协作工具。
工具为智能体提供了**可调用的函数**来采取行动。它们与 MCP(远程工具服务器)、应用(平台集成)、技能(领域专长)和 知识(检索到的事实)协同工作。请参阅 智能体能力 概述,以了解何时使用各项功能。

什么是工具?

CrewAI 中的工具是指智能体可以用来执行各种动作的技能或函数。这包括来自 CrewAI 工具包LangChain 工具 的资源,支持从简单的搜索到复杂的交互,以及实现智能体之间的高效协作。
CrewAI AMP 提供了一个全面的工具库,其中包含针对常见业务系统和 API 的预构建集成。您可以在几天甚至几分钟内为智能体部署企业级工具。企业工具库包括:
  • 针对常用企业系统的预构建连接器
  • 自定义工具创建接口
  • 版本控制与共享功能
  • 安全与合规特性

工具的核心特性

  • 实用性:专为网页搜索、数据分析、内容生成和智能体协作等任务而设计。
  • 集成性:通过将工具无缝集成到工作流中来增强智能体的能力。
  • 可定制性:提供开发自定义工具或利用现有工具的灵活性,满足智能体的特定需求。
  • 错误处理:内置强大的错误处理机制,确保运行顺畅。
  • 缓存机制:具有智能缓存功能,以优化性能并减少冗余操作。
  • 异步支持:处理同步和异步工具,实现非阻塞操作。

使用 CrewAI 工具

要使用 CrewAI 工具增强智能体的能力,请首先安装我们的额外工具包
pip install 'crewai[tools]'
以下是演示其用法的示例
代码
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()

可用的 CrewAI 工具

  • 错误处理:所有工具都具备错误处理能力,允许智能体优雅地管理异常并继续执行任务。
  • 缓存机制:所有工具均支持缓存,使智能体能够高效复用之前获取的结果,减少对外部资源的负载并加快执行时间。您还可以通过工具的 cache_function 属性对缓存机制进行精细控制。
以下是可用工具及其描述的列表
工具描述
ApifyActorsTool将 Apify Actors 集成到工作流中,用于网页抓取和自动化任务的工具。
BrowserbaseLoadTool用于与 Web 浏览器交互并从中提取数据的工具。
CodeDocsSearchTool一种 RAG 工具,优化用于搜索代码文档及相关技术文档。
CodeInterpreterTool用于解释 Python 代码的工具。
ComposioTool启用对 Composio 工具的使用。
CSVSearchTool一种专为搜索 CSV 文件设计的 RAG 工具,适合处理结构化数据。
DALL-E 工具使用 DALL-E API 生成图像的工具。
DirectorySearchTool用于在目录中进行搜索的 RAG 工具,有助于浏览文件系统。
DOCXSearchTool旨在搜索 DOCX 文档的 RAG 工具,非常适合处理 Word 文件。
DirectoryReadTool有助于读取和处理目录结构及其内容。
ExaSearchTool使用 Exa 进行网页搜索,这是最快、最准确的网页搜索 API。支持节省 Token 的摘要和全页内容。
FileReadTool能够读取和提取文件数据,支持多种文件格式。
FirecrawlSearchTool使用 Firecrawl 搜索网页并返回结果的工具。
FirecrawlCrawlWebsiteTool使用 Firecrawl 爬取网页的工具。
FirecrawlScrapeWebsiteTool使用 Firecrawl 抓取网址并返回其内容的工具。
GithubSearchTool用于在 GitHub 仓库中搜索的 RAG 工具,适用于代码和文档搜索。
SerperDevTool一种专用于开发目的的工具,其特定功能正在开发中。
TXTSearchTool专注于搜索文本(.txt)文件的 RAG 工具,适合处理非结构化数据。
JSONSearchTool专为搜索 JSON 文件设计的 RAG 工具,满足结构化数据处理需求。
LlamaIndexTool启用对 LlamaIndex 工具的使用。
MDXSearchTool专门用于搜索 Markdown (MDX) 文件的 RAG 工具,对文档编写非常有用。
PDFSearchTool旨在搜索 PDF 文档的 RAG 工具,非常适合处理扫描文档。
PGSearchTool优化用于在 PostgreSQL 数据库中搜索的 RAG 工具,适用于数据库查询。
视觉工具使用 DALL-E API 生成图像的工具。
RagTool一种通用的 RAG 工具,能够处理各种数据源和类型。
ScrapeElementFromWebsiteTool支持从网站抓取特定元素,适用于目标数据提取。
ScrapeWebsiteTool支持抓取整个网站,非常适合进行全面的数据收集。
WebsiteSearchTool用于搜索网站内容的 RAG 工具,针对 Web 数据提取进行了优化。
XMLSearchTool设计用于搜索 XML 文件的 RAG 工具,适用于结构化数据格式。
YoutubeChannelSearchTool用于搜索 YouTube 频道的 RAG 工具,适用于视频内容分析。
YoutubeVideoSearchTool旨在搜索 YouTube 视频内容的 RAG 工具,非常适合视频数据提取。

创建您自己的工具

开发者可以针对智能体的需求定制 自定义工具,或利用预构建的选项。
创建 CrewAI 工具主要有两种方式

继承 BaseTool

代码
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"

异步工具支持

CrewAI 支持异步工具,允许您实现执行非阻塞操作(如网络请求、文件 I/O 或其他异步操作)的工具,而不会阻塞主执行线程。

创建异步工具

您可以通过两种方式创建异步工具

1. 使用带异步函数的 tool 装饰器

代码
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. 在自定义工具类中实现异步方法

代码
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"

使用异步工具

异步工具可以在标准 Crew 工作流和基于 Flow 的工作流中无缝运行
代码
# 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
CrewAI 框架会自动处理同步和异步工具的执行,因此您无需担心如何以不同方式调用它们。

使用 tool 装饰器

代码
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"

自定义缓存机制

工具可以选择性地实现 cache_function 来微调缓存行为。该函数根据特定条件确定何时缓存结果,从而提供对缓存逻辑的精细控制。
代码
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,
    )
    #...

结论

工具在扩展 CrewAI 智能体能力方面起着核心作用,使它们能够承担广泛的任务并进行有效协作。在使用 CrewAI 构建解决方案时,请利用自定义工具和现有工具来增强您的智能体并加强 AI 生态系统。考虑利用错误处理、缓存机制和工具参数的灵活性来优化智能体的性能和能力。