Tools 工具

工具是 Agent 可调用的函数:搜索、读文件、查库、调 API。它们与 MCP(远程工具服务)、AppsSkills(领域说明)、Knowledge(检索到的事实)并列,见官方 Agent Capabilities。本课聚焦 crewai_tools 与自定义工具。

pip install 'crewai[tools]'
# 或 uv add 'crewai[tools]'

挂到 Agent 上

from crewai import Agent, Task, Crew
from crewai_tools import (
    DirectoryReadTool,
    FileReadTool,
    SerperDevTool,
    WebsiteSearchTool,
)

search = SerperDevTool()
docs = DirectoryReadTool(directory="./blog-posts")
files = FileReadTool()
web_rag = WebsiteSearchTool()

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, web_rag],
    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, files],
    verbose=True,
)

SerperDevTool 需要 SERPER_API_KEY。JSONC 里写 "tools": ["SerperDevTool"] 即可按类名加载;自定义工具用 "custom:" 指向 tools/*.py

常用内置类(完整表见 Tools 概念页):FileReadToolFileWriterToolDirectoryReadTool、各类 *SearchTool(PDF / CSV / 站点 RAG)、ScrapeWebsiteToolCodeInterpreterToolRagToolLlamaIndexToolLangChainTool

文档型检索应对齐本站 RAG 的切块与评估原则;索引实现可交给 LlamaIndex,再用 LlamaIndexTool 包一层。LangChain 工具可用 LangChainTool 包装后交给 CrewAI Agent。


自定义:@tool

from crewai.tools import tool

@tool("Name of my tool")
def my_tool(question: str) -> str:
    """Clear description of when to use this tool."""
    return "Result from your custom tool"

异步函数同样可用 @tool 装饰 async def。Docstring 会进入工具说明,写清楚何时用、参数含义


自定义:子类 BaseTool

from typing import Type
from pydantic import BaseModel, Field
from crewai.tools import BaseTool

class MyToolInput(BaseModel):
    argument: str = Field(..., description="Description of the argument.")

class MyCustomTool(BaseTool):
    name: str = "Name of my tool"
    description: str = "What this tool does. Vital for the agent to choose it."
    args_schema: Type[BaseModel] = MyToolInput

    def _run(self, argument: str) -> str:
        return "Tool's result"

可返回 Pydantic 模型作为 typed output;Agent 侧通常收到 JSON 字段。业务失败不要只返回「看起来像错误的字符串」,官方提供 ToolFailurecrewai.tools.tool_failure),并可用 tool_failure_policyignore / warn / raise)控制后续行为。


MCP

CrewAI 能把 MCP Server 暴露成工具(crewai-tools 的适配器,或 Agent 上的 MCP DSL / mcps 字段)。传输包括 stdio、SSE、Streamable HTTP。安全注意与本站 MCP 教程 一致:只接信任的服务器,限制工具范围。细节见官方 MCP 文档,不要臆造客户端 API。


实践要点

  • 工具越少越好:只给该角色真正需要的能力。
  • 任务级 tools=[...] 可收紧权限(例如写作者不能搜索外网)。
  • 内置缓存减少重复外部调用;可用 cache_function 细调。
  • RAG 质量问题先查 RAG 教程 的切块 / 召回,而不是再加一个 Agent。

下一步

评论