简介

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

什么是工具?

CrewAI 中的工具是代理可以用来执行各种操作的技能或功能。这包括 CrewAI 工具包和 LangChain 工具中的工具,使代理能够进行从简单搜索到复杂交互以及有效的团队协作等一切操作。

CrewAI 企业版提供了一个全面的工具仓库,其中包含针对常见业务系统和 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一种 RAG 工具,专为在 CSV 文件内搜索而设计,适用于处理结构化数据。
DALL-E 工具一种使用 DALL-E API 生成图像的工具。
DirectorySearchTool一种 RAG 工具,用于在目录内搜索,适用于浏览文件系统。
DOCXSearchTool一种 RAG 工具,旨在搜索 DOCX 文档,非常适合处理 Word 文件。
DirectoryReadTool方便读取和处理目录结构及其内容。
EXASearchTool一种设计用于在各种数据源上执行详尽搜索的工具。
FileReadTool能够读取和提取文件中的数据,支持各种文件格式。
FirecrawlSearchTool一种使用 Firecrawl 搜索网页并返回结果的工具。
FirecrawlCrawlWebsiteTool一种使用 Firecrawl 抓取网页的工具。
FirecrawlScrapeWebsiteTool一种使用 Firecrawl 爬取网页 URL 并返回其内容的工具。
GithubSearchTool一种 RAG 工具,用于在 GitHub 仓库中搜索,适用于代码和文档搜索。
SerperDevTool一种专用于开发目的的工具,正在开发特定功能。
TXTSearchTool一种 RAG 工具,专注于在文本 (.txt) 文件中搜索,适用于非结构化数据。
JSONSearchTool一种 RAG 工具,设计用于在 JSON 文件中搜索,适用于结构化数据处理。
LlamaIndexTool启用使用 LlamaIndex 工具。
MDXSearchTool一种 RAG 工具,专为在 Markdown (MDX) 文件中搜索而定制,适用于文档。
PDFSearchTool一种 RAG 工具,旨在搜索 PDF 文档,非常适合处理扫描文档。
PGSearchTool一种 RAG 工具,专为在 PostgreSQL 数据库中搜索而优化,适用于数据库查询。
视觉工具一种使用 DALL-E API 生成图像的工具。
RagTool一种通用的 RAG 工具,能够处理各种数据源和类型。
ScrapeElementFromWebsiteTool能够从网站上抓取特定元素,适用于有针对性的数据提取。
ScrapeWebsiteTool方便抓取整个网站,非常适合全面数据收集。
WebsiteSearchTool一种 RAG 工具,用于搜索网站内容,专为网页数据提取而优化。
XMLSearchTool一种 RAG 工具,设计用于在 XML 文件中搜索,适用于结构化数据格式。
YoutubeChannelSearchTool一种 RAG 工具,用于在 YouTube 频道内搜索,适用于视频内容分析。
YoutubeVideoSearchTool一种 RAG 工具,旨在搜索 YouTube 视频,非常适合视频数据提取。

创建您自己的工具

开发者可以精心制作针对其代理需求量身定制的自定义工具,或利用预构建选项。

创建 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"

利用 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 生态系统。考虑利用错误处理、缓存机制以及工具参数的灵活性来优化代理的性能和能力。