CrewAI Tools 整合:讓 Agent 真的能查資料、讀檔案、做事
沒有工具的 Agent,就像一個會講很多理論但手邊沒鍵盤的工程師——能聊,但做不出東西。
Agent 預設只能靠模型自身的訓練資料回答問題,沒辦法查 Google、讀你的資料庫、存取你的 API。Tools 就是讓 Agent 有手腳的機制——給它什麼工具,它就能做什麼事。
你最常用到的內建 Tool
CrewAI 的 crewai-tools 套件內建了幾個最常用的工具,拿到就能用:
SerperDevTool:呼叫 Serper API 做 Google 搜尋,需要 Serper API KeyFileReadTool:讀取本機檔案內容FileWriterTool:把結果寫到本機檔案ScrapeWebsiteTool:讀取指定 URL 的網頁內容
這四個工具組合起來,基本上能覆蓋大多數「研究 + 輸出」類型的任務。
把 Tool 掛到 Agent
from crewai import Agent
from crewai_tools import SerperDevTool
search_tool = SerperDevTool()
researcher = Agent(
role="Researcher",
goal="Find trustworthy and current sources about the topic",
backstory="You always verify facts before writing anything down.",
tools=[search_tool],
allow_delegation=False,
verbose=True,
)注意 search_tool 只建立一次,可以傳給多個 Agent——不用每個 Agent 各自建一個實例,節省資源也符合 DRY 原則。
工具是在 Agent 層級設定的,不是在 Task 層級。但你可以在 Task 的 description 裡明確要求 Agent 使用工具,這會讓模型更確定應該呼叫它。
為什麼 Tool 有時候沒被呼叫?
這是新手最常遇到的困惑——明明掛了工具,但 Agent 自己回答了,根本沒去查。
原因通常是:Task 的描述沒有明確要求使用工具,模型認為它已經知道答案,就不會去呼叫了。
解法很直接,在 Task 的 description 裡加一行:
research_task:
description: >
Use the search tool to find the latest information about {topic}.
Do NOT rely on your own knowledge — always search first.
Focus on articles and updates from 2026.
expected_output: >
10 bullet points with title, summary, and source URL.
agent: researcher「Use the search tool」和「Do NOT rely on your own knowledge」這兩句話加了之後,工具呼叫率會明顯提升。
自訂 Tool:當內建工具不夠用
如果你需要對接自己的 API 或資料庫,就要自己寫 Tool。框架很固定,按著寫就好:
from crewai.tools import BaseTool
from pydantic import BaseModel, Field
class ProductQueryInput(BaseModel):
product_id: str = Field(description="The product ID to look up")
class ProductLookupTool(BaseTool):
name: str = "Product Lookup Tool"
description: str = (
"Look up product details by product ID. "
"Use this when you need accurate product information from the database."
)
args_schema: type[BaseModel] = ProductQueryInput
def _run(self, product_id: str) -> str:
# 這裡呼叫你的資料庫或 API
return f"Product {product_id}: Name=Example, Price=100, Stock=50"description 這個欄位模型會讀到,用來判斷什麼情況下應該呼叫這個工具。寫清楚「什麼時候用、輸入是什麼、輸出是什麼」,模型才知道怎麼用它。
設計 Tool 的 4 個原則
只做一件事:查資料的 Tool 就只查,不要順便寫檔案。責任單一,測試和除錯才容易。
description 要說清楚用途:不是給工程師看的,是給模型看的。用自然語言說明「何時用、輸入是什麼格式、輸出是什麼」。
參數用 Pydantic 管理:args_schema 不只是讓程式碼漂亮,它讓模型知道參數的型別和用途,傳錯參數的機率大幅降低。
回傳格式要穩定:下游任務要解析你的輸出,如果回傳格式每次不一樣,後面的 Task 會很難處理。固定用結構化字串或 JSON 格式。
常見問題
Q:SerperDevTool 需要什麼設定?
需要 Serper API Key,在 .env 裡設定 SERPER_API_KEY=你的key。Serper 有免費額度,測試用夠了。
Q:Tool 可以有 async 的版本嗎?
可以,實作 _arun 方法就好。對於需要同時呼叫多個外部 API 的情境,async Tool 可以明顯縮短執行時間。
Q:一個 Agent 可以掛多少個 Tool?
沒有硬性限制,但工具太多反而會讓模型不知道該用哪個。建議一個 Agent 掛 2-4 個功能相關的工具就好,不要把所有工具都掛給同一個 Agent。
下一步
工具接上去之後,下一個問題是:Agent 的輸出怎麼保持一致? 不用 Pydantic 的話,格式每次都在飄。
👉 結構化輸出 Pydantic