CrewAI 工具为智能体赋予了从网络搜索、数据分析到协作以及在同事间委派任务等多种能力。本文档概述了如何在 CrewAI 框架内创建、集成和利用这些工具,包括对协作工具的新关注点。
在 CrewAI 中,工具是智能体可以用来执行各种操作的技能或功能。这包括来自 CrewAI 工具包 和 LangChain 工具 的工具,能够实现从简单搜索到复杂交互以及智能体之间有效团队合作的各种功能。
CrewAI AMP 提供了一个全面的工具库,其中包含针对常见业务系统和 API 的预构建集成。您可以在几分钟而不是几天内部署带有企业级工具的智能体。企业工具库包括:
- 为热门企业系统预构建的连接器
- 自定义工具创建界面
- 版本控制和共享功能
- 安全与合规功能
- 实用性:专为网络搜索、数据分析、内容生成和智能体协作等任务而设计。
- 集成性:通过将工具无缝集成到智能体的工作流程中,增强其能力。
- 可定制性:提供了开发自定义工具或利用现有工具的灵活性,以满足智能体的特定需求。
- 错误处理:内置强大的错误处理机制,确保平稳运行。
- 缓存机制:具有智能缓存功能,以优化性能并减少冗余操作。
- 异步支持:同时处理同步和异步工具,实现非阻塞操作。
要使用 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()
- 错误处理:所有工具都内置了错误处理功能,允许智能体优雅地处理异常并继续执行任务。
- 缓存机制:所有工具都支持缓存,使智能体能够高效地重用先前获得的结果,减少对外部资源的负载并加快执行时间。您还可以使用工具上的
cache_function 属性对缓存机制进行更精细的控制。
以下是可用工具及其描述的列表
| 工具 | 描述 |
|---|
| ApifyActorsTool | 将 Apify Actors 与您的工作流集成,用于网络抓取和自动化任务的工具。 |
| BrowserbaseLoadTool | 用于与网络浏览器交互并从中提取数据的工具。 |
| CodeDocsSearchTool | 一个 RAG 工具,优化用于在代码文档和相关技术文档中进行搜索。 |
| CodeInterpreterTool | 用于解释 python 代码的工具。 |
| ComposioTool | 启用 Composio 工具的使用。 |
| CSVSearchTool | 一个 RAG 工具,专为在 CSV 文件内搜索而设计,适合处理结构化数据。 |
| DALL-E Tool | 使用 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 数据库内搜索,适用于数据库查询。 |
| Vision Tool | 使用 DALL-E API 生成图像的工具。 |
| RagTool | 一个通用的 RAG 工具,能够处理各种数据源和类型。 |
| ScrapeElementFromWebsiteTool | 能够从网站上抓取特定元素,有助于进行有针对性的数据提取。 |
| ScrapeWebsiteTool | 便于抓取整个网站,非常适合进行全面的数据收集。 |
| WebsiteSearchTool | 一个 RAG 工具,用于搜索网站内容,优化用于网络数据提取。 |
| XMLSearchTool | 一个 RAG 工具,专为在 XML 文件内搜索而设计,适用于结构化数据格式。 |
| YoutubeChannelSearchTool | 一个 RAG 工具,用于在 YouTube 频道内搜索,有助于视频内容分析。 |
| YoutubeVideoSearchTool | 一个 RAG 工具,旨在搜索 YouTube 视频,非常适合视频数据提取。 |
开发者可以为他们的智能体需求量身打造自定义工具,或利用预构建的选项。
创建 CrewAI 工具有两种主要方式
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 或其他异步操作,而不会阻塞主执行线程。
您可以通过两种方式创建异步工具
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}"
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 框架会自动处理同步和异步工具的执行,因此您无需担心如何以不同方式调用它们。
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 生态系统的发展。考虑利用错误处理、缓存机制以及工具参数的灵活性来优化智能体的性能和能力。