Tools

理解并利用 CrewAI 框架中的 tools,以支持 agent 协作和任务执行。

概述

CrewAI tools 为 agents 提供了从网页搜索、数据分析到协作与将任务委派给同事等多种能力。 本文档概述了如何在 CrewAI 框架中创建、集成并利用这些 tools,并新增聚焦于协作工具的内容。

什么是 Tool?

在 CrewAI 中,tool 是一种 agent 可用于执行各种操作的技能或函数。 这包括来自 CrewAI ToolkitLangChain Tools 的工具, 使 agents 能够完成从简单搜索到复杂交互,以及高效团队协作的各种任务。

CrewAI AMP 提供了一个全面的 Tools Repository,其中包含适用于常见企业系统和 API 的预构建集成。你可以在几分钟内,而不是几天内,为 agents 部署企业级工具。 企业 Tools Repository 包括: 面向流行企业系统的预构建连接器 自定义工具创建界面 版本控制与共享能力 安全与合规特性

Tools 的关键特性

  • 实用性:专为网页搜索、数据分析、内容生成和 agent 协作等任务打造。
  • 集成性:通过将 tools 无缝集成到工作流中,增强 agent 能力。
  • 可定制性:可灵活开发自定义 tools 或使用现有 tools,以满足 agents 的特定需求。
  • 错误处理:内置健壮的错误处理机制,以确保平稳运行。
  • 缓存机制:具备智能缓存能力,可优化性能并减少重复操作。
  • 异步支持:同时支持同步和异步 tools,实现非阻塞操作。

使用 CrewAI Tools

要使用 crewAI tools 增强 agents 的能力,请先安装我们的扩展工具包:

  1. pip install 'crewai[tools]'

下面是一个演示其用法的示例:

  1. import os
  2. from crewai import Agent, Task, Crew
  3. # Importing crewAI tools
  4. from crewai_tools import (
  5. DirectoryReadTool,
  6. FileReadTool,
  7. SerperDevTool,
  8. WebsiteSearchTool
  9. )
  10. # Set up API keys
  11. os.environ["SERPER_API_KEY"] = "Your Key" # serper.dev API key
  12. os.environ["OPENAI_API_KEY"] = "Your Key"
  13. # Instantiate tools
  14. docs_tool = DirectoryReadTool(directory='./blog-posts')
  15. file_tool = FileReadTool()
  16. search_tool = SerperDevTool()
  17. web_rag_tool = WebsiteSearchTool()
  18. # Create agents
  19. researcher = Agent(
  20. role='Market Research Analyst',
  21. goal='Provide up-to-date market analysis of the AI industry',
  22. backstory='An expert analyst with a keen eye for market trends.',
  23. tools=[search_tool, web_rag_tool],
  24. verbose=True
  25. )
  26. writer = Agent(
  27. role='Content Writer',
  28. goal='Craft engaging blog posts about the AI industry',
  29. backstory='A skilled writer with a passion for technology.',
  30. tools=[docs_tool, file_tool],
  31. verbose=True
  32. )
  33. # Define tasks
  34. research = Task(
  35. description='Research the latest trends in the AI industry and provide a summary.',
  36. expected_output='A summary of the top 3 trending developments in the AI industry with a unique perspective on their significance.',
  37. agent=researcher
  38. )
  39. write = Task(
  40. 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.',
  41. expected_output='A 4-paragraph blog post formatted in markdown with engaging, informative, and accessible content, avoiding complex jargon.',
  42. agent=writer,
  43. output_file='blog-posts/new_post.md' # The final blog post will be saved here
  44. )
  45. # Assemble a crew with planning enabled
  46. crew = Crew(
  47. agents=[researcher, writer],
  48. tasks=[research, write],
  49. verbose=True,
  50. planning=True, # Enable planning feature
  51. )
  52. # Execute tasks
  53. crew.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

开发者可以根据 agent 的需求构建 custom tools, 也可以直接使用预构建选项。

创建 CrewAI tool 主要有两种方式:

继承 BaseTool

  1. from crewai.tools import BaseTool
  2. from pydantic import BaseModel, Field
  3. class MyToolInput(BaseModel):
  4. """Input schema for MyCustomTool."""
  5. argument: str = Field(..., description="Description of the argument.")
  6. class MyCustomTool(BaseTool):
  7. name: str = "Name of my tool"
  8. description: str = "What this tool does. It's vital for effective utilization."
  9. args_schema: Type[BaseModel] = MyToolInput
  10. def _run(self, argument: str) -> str:
  11. # Your tool's logic here
  12. return "Tool's result"

异步 Tool 支持

CrewAI 支持异步 tools,这意味着你可以实现执行非阻塞操作的工具,例如网络请求、文件 I/O 或其他异步操作,而不会阻塞主执行线程。

创建异步 Tools

你可以通过两种方式创建异步 tools:

1. 使用 tool 装饰器配合异步函数

  1. from crewai.tools import tool
  2. @tool("fetch_data_async")
  3. async def fetch_data_async(query: str) -> str:
  4. """Asynchronously fetch data based on the query."""
  5. # Simulate async operation
  6. await asyncio.sleep(1)
  7. return f"Data retrieved for {query}"

2. 在自定义 Tool 类中实现异步方法

  1. from crewai.tools import BaseTool
  2. class AsyncCustomTool(BaseTool):
  3. name: str = "async_custom_tool"
  4. description: str = "An asynchronous custom tool"
  5. async def _run(self, query: str = "") -> str:
  6. """Asynchronously run the tool"""
  7. # Your async implementation here
  8. await asyncio.sleep(1)
  9. return f"Processed {query} asynchronously"

使用异步 Tools

异步 tools 可在标准 Crew 工作流和基于 Flow 的工作流中无缝运行:

  1. # In standard Crew
  2. agent = Agent(role="researcher", tools=[async_custom_tool])
  3. # In Flow
  4. class MyFlow(Flow):
  5. @start()
  6. async def begin(self):
  7. crew = Crew(agents=[agent])
  8. result = await crew.kickoff_async()
  9. return result

CrewAI 框架会自动处理同步与异步 tools 的执行,因此你无需担心如何以不同方式调用它们。

使用 tool 装饰器

  1. from crewai.tools import tool
  2. @tool("Name of my tool")
  3. def my_tool(question: str) -> str:
  4. """Clear description for what this tool is useful for, your agent will need this information to use it."""
  5. # Function logic here
  6. return "Result from your custom tool"

自定义缓存机制

Tools 可以选择实现 cache_function,以更细致地控制缓存行为。 该函数会根据特定条件判断是否缓存结果,从而对缓存逻辑提供更高颗粒度的控制。
  1. from crewai.tools import tool
  2. @tool
  3. def multiplication_tool(first_number: int, second_number: int) -> str:
  4. """Useful for when you need to multiply two numbers together."""
  5. return first_number * second_number
  6. def cache_func(args, result):
  7. # In this case, we only cache the result if it's a multiple of 2
  8. cache = result % 2 == 0
  9. return cache
  10. multiplication_tool.cache_function = cache_func
  11. writer1 = Agent(
  12. role="Writer",
  13. goal="You write lessons of math for kids.",
  14. backstory="You're an expert in writing and you love to teach kids but you know nothing of math.",
  15. tools=[multiplication_tool],
  16. allow_delegation=False,
  17. )
  18. #...

结论

Tools 是扩展 CrewAI agents 能力的关键,它们使 agents 能够执行广泛的任务并进行高效协作。 在使用 CrewAI 构建解决方案时,请充分利用自定义和现有 tools,为 agents 赋能并增强整个 AI 生态。你也可以结合错误处理、 缓存机制以及灵活的工具参数,来优化 agents 的性能与能力。