Tools
理解并利用 CrewAI 框架中的 tools,以支持 agent 协作和任务执行。
概述
CrewAI tools 为 agents 提供了从网页搜索、数据分析到协作与将任务委派给同事等多种能力。 本文档概述了如何在 CrewAI 框架中创建、集成并利用这些 tools,并新增聚焦于协作工具的内容。
什么是 Tool?
在 CrewAI 中,tool 是一种 agent 可用于执行各种操作的技能或函数。 这包括来自 CrewAI Toolkit 和 LangChain Tools 的工具, 使 agents 能够完成从简单搜索到复杂交互,以及高效团队协作的各种任务。
Tools 的关键特性
- 实用性:专为网页搜索、数据分析、内容生成和 agent 协作等任务打造。
- 集成性:通过将 tools 无缝集成到工作流中,增强 agent 能力。
- 可定制性:可灵活开发自定义 tools 或使用现有 tools,以满足 agents 的特定需求。
- 错误处理:内置健壮的错误处理机制,以确保平稳运行。
- 缓存机制:具备智能缓存能力,可优化性能并减少重复操作。
- 异步支持:同时支持同步和异步 tools,实现非阻塞操作。
使用 CrewAI Tools
要使用 crewAI tools 增强 agents 的能力,请先安装我们的扩展工具包:
pip install 'crewai[tools]'
下面是一个演示其用法的示例:
import osfrom crewai import Agent, Task, Crew# Importing crewAI toolsfrom crewai_tools import (DirectoryReadTool,FileReadTool,SerperDevTool,WebsiteSearchTool)# Set up API keysos.environ["SERPER_API_KEY"] = "Your Key" # serper.dev API keyos.environ["OPENAI_API_KEY"] = "Your Key"# Instantiate toolsdocs_tool = DirectoryReadTool(directory='./blog-posts')file_tool = FileReadTool()search_tool = SerperDevTool()web_rag_tool = WebsiteSearchTool()# Create agentsresearcher = 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 tasksresearch = 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 enabledcrew = Crew(agents=[researcher, writer],tasks=[research, write],verbose=True,planning=True, # Enable planning feature)# Execute taskscrew.kickoff()
可用的 CrewAI Tools
- 错误处理:所有 tools 都内置错误处理能力,使 agents 能够优雅地处理异常并继续任务。
- 缓存机制:所有 tools 都支持缓存,使 agents 可以高效复用先前获取的结果,减少对外部资源的负载并加快执行速度。你还可以通过 tool 上的
cache_function属性,对缓存机制进行更细粒度的控制。
以下是可用 tools 及其说明列表:
| Tool | 说明 |
|---|---|
| ApifyActorsTool | 将 Apify Actors 集成到你的工作流中,用于网页抓取和自动化任务。 |
| BrowserbaseLoadTool | 用于与浏览器交互并从中提取数据的工具。 |
| CodeDocsSearchTool | 针对代码文档和相关技术文档搜索优化的 RAG 工具。 |
| CodeInterpreterTool | 用于解释 python 代码的工具。 |
| ComposioTool | 支持使用 Composio tools。 |
| CSVSearchTool | 专为 CSV 文件搜索设计的 RAG 工具,适合处理结构化数据。 |
| DALL-E Tool | 使用 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 tools。 |
| MDXSearchTool | 面向 Markdown(MDX)文件搜索的 RAG 工具,适合文档检索。 |
| PDFSearchTool | 用于 PDF 文档搜索的 RAG 工具,适合处理扫描文档。 |
| PGSearchTool | 针对 PostgreSQL 数据库搜索优化的 RAG 工具,适合数据库查询。 |
| Vision Tool | 使用 DALL-E API 生成图像的工具。 |
| RagTool | 通用型 RAG 工具,可处理多种数据源和类型。 |
| ScrapeElementFromWebsiteTool | 用于从网站中抓取特定元素,适合定向数据提取。 |
| ScrapeWebsiteTool | 用于抓取整个网站,适合全面数据采集。 |
| WebsiteSearchTool | 用于网站内容搜索的 RAG 工具,针对网页数据提取进行了优化。 |
| XMLSearchTool | 用于 XML 文件搜索的 RAG 工具,适合结构化数据格式。 |
| YoutubeChannelSearchTool | 用于 YouTube 频道搜索的 RAG 工具,适合视频内容分析。 |
| YoutubeVideoSearchTool | 用于 YouTube 视频搜索的 RAG 工具,适合视频数据提取。 |
创建你自己的 Tools
custom tools,
也可以直接使用预构建选项。
创建 CrewAI tool 主要有两种方式:
继承 BaseTool
from crewai.tools import BaseToolfrom pydantic import BaseModel, Fieldclass 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] = MyToolInputdef _run(self, argument: str) -> str:# Your tool's logic herereturn "Tool's result"
异步 Tool 支持
CrewAI 支持异步 tools,这意味着你可以实现执行非阻塞操作的工具,例如网络请求、文件 I/O 或其他异步操作,而不会阻塞主执行线程。
创建异步 Tools
你可以通过两种方式创建异步 tools:
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 operationawait asyncio.sleep(1)return f"Data retrieved for {query}"
2. 在自定义 Tool 类中实现异步方法
from crewai.tools import BaseToolclass 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 hereawait asyncio.sleep(1)return f"Processed {query} asynchronously"
使用异步 Tools
异步 tools 可在标准 Crew 工作流和基于 Flow 的工作流中无缝运行:
# In standard Crewagent = Agent(role="researcher", tools=[async_custom_tool])# In Flowclass MyFlow(Flow):@start()async def begin(self):crew = Crew(agents=[agent])result = await crew.kickoff_async()return result
CrewAI 框架会自动处理同步与异步 tools 的执行,因此你无需担心如何以不同方式调用它们。
使用 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 herereturn "Result from your custom tool"
自定义缓存机制
cache_function,以更细致地控制缓存行为。
该函数会根据特定条件判断是否缓存结果,从而对缓存逻辑提供更高颗粒度的控制。
from crewai.tools import tool@tooldef multiplication_tool(first_number: int, second_number: int) -> str:"""Useful for when you need to multiply two numbers together."""return first_number * second_numberdef cache_func(args, result):# In this case, we only cache the result if it's a multiple of 2cache = result % 2 == 0return cachemultiplication_tool.cache_function = cache_funcwriter1 = 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 是扩展 CrewAI agents 能力的关键,它们使 agents 能够执行广泛的任务并进行高效协作。 在使用 CrewAI 构建解决方案时,请充分利用自定义和现有 tools,为 agents 赋能并增强整个 AI 生态。你也可以结合错误处理、 缓存机制以及灵活的工具参数,来优化 agents 的性能与能力。
