CrewAI Tools 整合:讓 Agent 真的能查、能讀、能做事

2 min read

沒有工具的 Agent,就像會講很多理論但手邊沒鍵盤的工程師。
能聊,但做不出東西。

常見內建 Tool

CrewAI 常用工具大概這幾種:

  • SerperDevTool:網路搜尋
  • FileReadTool:讀檔
  • FileWriterTool:寫檔
  • ScrapeWebsiteTool:抓網頁內容

把 Tool 掛到 Agent

from crewai import Agent
from crewai_tools import SerperDevTool
 
search_tool = SerperDevTool()
 
researcher = Agent(
    role="Researcher",
    goal="Find trustworthy sources about the topic",
    backstory="You validate facts before writing.",
    tools=[search_tool],
    allow_delegation=False,
    verbose=True,
)

💡 同一個 search_tool 可以共用,不用每個 Agent 重建一次(DRY)。

自訂 Tool 的最小樣板

from crewai.tools import BaseTool
from pydantic import BaseModel, Field
 
class QueryInput(BaseModel):
    keyword: str = Field(description="Search keyword")
 
class KeywordTool(BaseTool):
    name: str = "Keyword Tool"
    description: str = "Return a short explanation for a keyword."
    args_schema: type[BaseModel] = QueryInput
 
    def _run(self, keyword: str) -> str:
        return f"Result for: {keyword}"

Tool 設計 4 原則

  1. 只做一件事:查資料就查資料,別順便寫檔
  2. 描述清楚description 要講清楚用途與輸入
  3. 參數可驗證:用 Pydantic 管輸入
  4. 回傳穩定格式:讓下游 Task 好解析

常見錯誤

現象 原因 修正
Tool 不被呼叫 任務描述沒明確要求查資料 在 Task 指令中寫清楚「先使用工具」
參數亂傳 args_schema 不清楚 補上 Field(description=...)
回傳很難用 回傳自由文字太散 改成固定段落或 JSON 字串

下一步

有了工具後,下一個重點是「輸出一致性」。
下一篇我們用 Pydantic 把結果鎖成結構化:
👉 結構化輸出 Pydantic