介绍

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

什么是工具?

CrewAI中的一个工具是代理可以利用的技能或功能,以执行各种操作。 这包括来自CrewAI ToolkitLangChain Tools的工具, 使代理能够从简单的搜索到复杂的交互和有效的团队合作。

工具的关键特性

  • 实用工具: 专为网页搜索、数据分析、内容生成和代理协作等任务设计。
  • 集成: 通过将工具无缝集成到他们的工作流程中,提升代理的能力。
  • 可定制性: 提供开发自定义工具或利用现有工具的灵活性,以满足代理的特定需求。
  • 错误处理: 包含强大的错误处理机制,以确保平稳运行。
  • 缓存机制: 具有智能缓存功能,以优化性能并减少冗余操作。

使用CrewAI工具

要使用crewAI工具增强您的代理能力,首先安装我们的额外工具包:

pip install 'crewai[tools]'

这里有一个展示它们用法的例子:

Code
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属性定义对缓存机制的更精细控制。

以下是可用工具及其描述的列表:

工具描述
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一个专为在PostgreSQL数据库中进行搜索而优化的RAG工具,适用于数据库查询。
Vision Tool一个使用DALL-E API生成图像的工具。
RagTool一个通用的RAG工具,能够处理各种数据源和类型。
ScrapeElementFromWebsiteTool允许从网站抓取特定元素,适用于目标数据提取。
ScrapeWebsiteTool便于抓取整个网站,非常适合全面的数据收集。
WebsiteSearchTool一个用于搜索网站内容的RAG工具,专为网页数据提取优化。
XMLSearchTool一个专为在XML文件中搜索而设计的RAG工具,适用于结构化数据格式。
YoutubeChannelSearchTool一个用于在YouTube频道内搜索的RAG工具,对视频内容分析非常有用。
YoutubeVideoSearchTool一个旨在在YouTube视频中搜索的RAG工具,非常适合视频数据提取。

创建你自己的工具

开发者可以为其代理的需求定制custom tools或使用预构建的选项。

有两种主要方式可以创建CrewAI工具:

子类化 BaseTool

Code
from crewai.tools import BaseTool


class MyCustomTool(BaseTool):
    name: str = "Name of my tool"
    description: str = "Clear description for what this tool is useful for, your agent will need this information to use it."

    def _run(self, argument: str) -> str:
        # Implementation goes here
        return "Result from custom tool"

利用tool装饰器

Code
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"

结构化工具

StructuredTool 类将函数包装为工具,提供灵活性和验证,同时减少样板代码。它支持自定义模式和动态逻辑,以实现复杂功能的无缝集成。

示例:

使用StructuredTool.from_function,你可以包装一个与外部API或系统交互的函数,提供一个结构化的接口。这使得验证更加健壮,执行更加一致,从而更容易将复杂功能集成到你的应用程序中,如下例所示:

from crewai.tools.structured_tool import CrewStructuredTool
from pydantic import BaseModel

# Define the schema for the tool's input using Pydantic
class APICallInput(BaseModel):
    endpoint: str
    parameters: dict

# Wrapper function to execute the API call
def tool_wrapper(*args, **kwargs):
    # Here, you would typically call the API using the parameters
    # For demonstration, we'll return a placeholder string
    return f"Call the API at {kwargs['endpoint']} with parameters {kwargs['parameters']}"

# Create and return the structured tool
def create_structured_tool():
    return CrewStructuredTool.from_function(
        name='Wrapper API',
        description="A tool to wrap API calls with structured input.",
        args_schema=APICallInput,
        func=tool_wrapper,
    )

# Example usage
structured_tool = create_structured_tool()

# Execute the tool with structured input
result = structured_tool._run(**{
    "endpoint": "https://example.com/api",
    "parameters": {"key1": "value1", "key2": "value2"}
})
print(result)  # Output: Call the API at https://example.com/api with parameters {'key1': 'value1', 'key2': 'value2'}

自定义缓存机制

工具可以选择性地实现一个cache_function来微调缓存行为。此函数根据特定条件确定何时缓存结果,提供对缓存逻辑的精细控制。

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

这个页面有帮助吗?