跳转到主要内容

概述

CrewAI 工具赋予代理从网络搜索和数据分析到协作和委派任务给同事的各种能力。本文档概述了如何在 CrewAI 框架中创建、集成和利用这些工具,包括对协作工具的新重点。

什么是工具?

在 CrewAI 中,工具是代理可以用来执行各种操作的技能或功能。这包括来自 CrewAI 工具包LangChain 工具 的工具,实现从简单搜索到复杂交互以及代理之间有效协作的所有功能。
CrewAI AOP 提供了一个全面的工具库,其中包含针对常见业务系统和 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一个用于与网页浏览器交互和从中提取数据的工具。
CodeDocsSearchTool一个经过优化的 RAG 工具,用于搜索代码文档和相关的技术文档。
CodeInterpreterTool一个用于解释 Python 代码的工具。
ComposioTool启用 Composio 工具的使用。
CSVSearchTool一个为搜索 CSV 文件而设计的 RAG 工具,专门用于处理结构化数据。
DALL-E 工具一个使用 DALL-E API 生成图像的工具。
DirectorySearchTool一个用于搜索目录的 RAG 工具,可用于导航文件系统。
DOCXSearchTool一个旨在搜索 DOCX 文档的 RAG 工具,非常适合处理 Word 文件。
DirectoryReadTool方便读取和处理目录结构及其内容。
EXASearchTool一个旨在对各种数据源执行详尽搜索的工具。
FileReadTool启用从文件读取和提取数据,支持各种文件格式。
FirecrawlSearchTool一个使用 Firecrawl 搜索网页并返回结果的工具。
FirecrawlCrawlWebsiteTool一个使用 Firecrawl 爬取网页的工具。
FirecrawlScrapeWebsiteTool一个使用 Firecrawl 抓取网页 URL 并返回其内容的工具。
GithubSearchTool一个用于在 GitHub 存储库中搜索的 RAG 工具,可用于代码和文档搜索。
SerperDevTool一个专用于开发目的的工具,具有正在开发中的特定功能。
TXTSearchTool一个专注于搜索文本 (.txt) 文件中的 RAG 工具,适用于非结构化数据。
JSONSearchTool一个旨在搜索 JSON 文件中的 RAG 工具,适用于结构化数据处理。
LlamaIndexTool启用 LlamaIndex 工具的使用。
MDXSearchTool一个专门用于搜索 Markdown (MDX) 文件中的 RAG 工具,可用于文档。
PDFSearchTool一个旨在搜索 PDF 文档中的 RAG 工具,非常适合处理扫描文档。
PGSearchTool一个经过优化的 RAG 工具,用于在 PostgreSQL 数据库中搜索,适用于数据库查询。
视觉工具一个使用 DALL-E API 生成图像的工具。
RagTool一个通用的 RAG 工具,能够处理各种数据源和类型。
ScrapeElementFromWebsiteTool启用从网站抓取特定元素,可用于有针对性的数据提取。
ScrapeWebsiteTool方便抓取整个网站,非常适合全面的数据收集。
WebsiteSearchTool一个用于搜索网站内容的 RAG 工具,经过优化以进行网络数据提取。
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 工作流程和基于流程的工作流程中都能无缝运行
代码
# 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 生态系统。考虑利用错误处理、缓存机制和工具参数的灵活性来优化代理的性能和能力。