智慧體課程文件
工具
並獲得增強的文件體驗
開始使用
工具
正如我們在第一單元中探討的,Agent 使用工具來執行各種操作。在 smolagents
中,工具被視為 LLM 可以在 Agent 系統中呼叫的函式。
要與工具互動,LLM 需要一個包含以下關鍵元件的介面描述:
- 名稱:工具的名稱
- 工具描述:工具的功能
- 輸入型別和描述:工具接受的引數
- 輸出型別:工具返回的內容
例如,在為韋恩莊園的派對做準備時,阿爾弗雷德需要各種工具來收集資訊——從搜尋餐飲服務到尋找派對主題創意。以下是一個簡單的搜尋工具介面的樣子:
- 名稱:
web_search
- 工具描述: 在網路上搜索特定查詢
- 輸入:
query
(字串) - 要查詢的搜尋詞 - 輸出: 包含搜尋結果的字串
透過使用這些工具,阿爾弗雷德可以做出明智的決定,並收集策劃完美派對所需的所有資訊。
下面,您可以看到一個說明工具呼叫如何被管理的動畫。
工具建立方法
在 `smolagents` 中,可以透過兩種方式定義工具:
- 使用 `@tool` 裝飾器,適用於簡單的基於函式的工具
- 建立 `Tool` 的子類,適用於更復雜的功能
@tool 裝飾器
`@tool` 裝飾器是定義簡單工具的推薦方式。在底層,smolagents 會從 Python 中解析函式的基本資訊。因此,如果你給函式起一個清晰的名稱並編寫一個好的文件字串,LLM 會更容易使用它。
使用這種方法,我們定義一個函式時需要:
- 一個清晰且描述性的函式名,以幫助 LLM 理解其用途。
- 為輸入和輸出提供型別提示,以確保正確使用。
- 詳細的描述,包括一個 `Args:` 部分,其中明確描述了每個引數。這些描述為 LLM 提供了寶貴的上下文,因此仔細編寫它們非常重要。
生成一個檢索評分最高的餐飲服務的工具

假設阿爾弗雷德已經決定了派對的選單,但現在他需要幫助為這麼多客人準備食物。為此,他想聘請一家餐飲服務公司,並需要確定評分最高的選項。阿爾弗雷德可以利用一個工具來搜尋他所在地區的最佳餐飲服務。
下面是阿爾弗雷德如何使用 `@tool` 裝飾器來實現這一目標的示例
from smolagents import CodeAgent, InferenceClientModel, tool
# Let's pretend we have a function that fetches the highest-rated catering services.
@tool
def catering_service_tool(query: str) -> str:
"""
This tool returns the highest-rated catering service in Gotham City.
Args:
query: A search term for finding catering services.
"""
# Example list of catering services and their ratings
services = {
"Gotham Catering Co.": 4.9,
"Wayne Manor Catering": 4.8,
"Gotham City Events": 4.7,
}
# Find the highest rated catering service (simulating search query filtering)
best_service = max(services, key=services.get)
return best_service
agent = CodeAgent(tools=[catering_service_tool], model=InferenceClientModel())
# Run the agent to find the best catering service
result = agent.run(
"Can you give me the name of the highest-rated catering service in Gotham City?"
)
print(result) # Output: Gotham Catering Co.
將工具定義為 Python 類
這種方法涉及建立 Tool
的一個子類。對於複雜的工具,我們可以實現一個類而不是一個 Python 函式。該類將函式與元資料包裝在一起,幫助 LLM 理解如何有效地使用它。在這個類中,我們定義了
name
:工具的名稱。description
:用於填充 Agent 系統提示的描述。inputs
:一個包含type
和description
鍵的字典,為 Python 直譯器處理輸入提供資訊。output_type
:指定預期的輸出型別。forward
:包含要執行的推理邏輯的方法。
下面,我們可以看到一個使用 Tool
構建的工具示例,以及如何將其整合到 CodeAgent
中。
生成一個關於超級英雄主題派對創意的工具
阿爾弗雷德在莊園的派對是一個超級英雄主題活動,但他需要一些創意來讓它真正特別。作為一位出色的主人,他想用一個獨特的主題給客人們一個驚喜。
為此,他可以使用一個 Agent,根據給定的類別生成超級英雄主題的派對創意。這樣,阿爾弗雷德就可以找到完美的派對主題來驚豔他的客人。
from smolagents import Tool, CodeAgent, InferenceClientModel
class SuperheroPartyThemeTool(Tool):
name = "superhero_party_theme_generator"
description = """
This tool suggests creative superhero-themed party ideas based on a category.
It returns a unique party theme idea."""
inputs = {
"category": {
"type": "string",
"description": "The type of superhero party (e.g., 'classic heroes', 'villain masquerade', 'futuristic Gotham').",
}
}
output_type = "string"
def forward(self, category: str):
themes = {
"classic heroes": "Justice League Gala: Guests come dressed as their favorite DC heroes with themed cocktails like 'The Kryptonite Punch'.",
"villain masquerade": "Gotham Rogues' Ball: A mysterious masquerade where guests dress as classic Batman villains.",
"futuristic Gotham": "Neo-Gotham Night: A cyberpunk-style party inspired by Batman Beyond, with neon decorations and futuristic gadgets."
}
return themes.get(category.lower(), "Themed party idea not found. Try 'classic heroes', 'villain masquerade', or 'futuristic Gotham'.")
# Instantiate the tool
party_theme_tool = SuperheroPartyThemeTool()
agent = CodeAgent(tools=[party_theme_tool], model=InferenceClientModel())
# Run the agent to generate a party theme idea
result = agent.run(
"What would be a good superhero party idea for a 'villain masquerade' theme?"
)
print(result) # Output: "Gotham Rogues' Ball: A mysterious masquerade where guests dress as classic Batman villains."
有了這個工具,阿爾弗雷德將成為終極超級主人,用一個他們不會忘記的超級英雄主題派對給他的客人們留下深刻印象!🦸♂️🦸♀️
預設工具箱
smolagents
自帶一套預構建的工具,可以直接注入到你的 Agent 中。預設工具箱 包括:
- PythonInterpreterTool
- FinalAnswerTool
- UserInputTool
- DuckDuckGoSearchTool
- GoogleSearchTool
- VisitWebpageTool
阿爾弗雷德可以使用各種工具來確保韋恩莊園的派對完美無瑕:
首先,他可以使用 `DuckDuckGoSearchTool` 來尋找富有創意的超級英雄主題派對點子。
對於餐飲,他會依賴 `GoogleSearchTool` 來尋找哥譚市評分最高的餐飲服務。
為了管理座位安排,阿爾弗雷德可以使用 `PythonInterpreterTool` 來進行計算。
一旦所有資訊都收集完畢,他會使用 `FinalAnswerTool` 來整理計劃。
有了這些工具,阿爾弗雷德保證了派對既卓越又順暢。🦇💡
分享和匯入工具
smolagents 最強大的功能之一是它能夠在 Hub 上分享自定義工具,並無縫整合社群建立的工具。這包括與 HF Spaces 和 LangChain 工具的連線,極大地增強了阿爾弗雷德在韋恩莊園策劃一場難忘派對的能力。🎭
透過這些整合,阿爾弗雷德可以利用先進的活動策劃工具——無論是調整燈光以營造完美的氛圍,策劃派對的理想播放列表,還是與哥譚市最好的餐飲服務商協調。
以下是一些展示這些功能如何提升派對體驗的例子:
將工具分享到 Hub
與社群分享你的自定義工具非常簡單!只需使用 `push_to_hub()` 方法將其上傳到你的 Hugging Face 賬戶。
例如,阿爾弗雷德可以分享他的 `party_theme_tool` 來幫助他人在哥譚市找到最好的餐飲服務。方法如下:
party_theme_tool.push_to_hub("{your_username}/party_theme_tool", token="<YOUR_HUGGINGFACEHUB_API_TOKEN>")
從 Hub 匯入工具
您可以使用 `load_tool()` 函式輕鬆匯入其他使用者建立的工具。例如,阿爾弗雷德可能想用 AI 為派對生成一張宣傳圖片。他可以利用社群中一個預定義的工具,而不是從頭開始構建一個。
from smolagents import load_tool, CodeAgent, InferenceClientModel
image_generation_tool = load_tool(
"m-ric/text-to-image",
trust_remote_code=True
)
agent = CodeAgent(
tools=[image_generation_tool],
model=InferenceClientModel()
)
agent.run("Generate an image of a luxurious superhero-themed party at Wayne Manor with made-up superheros.")
將 Hugging Face Space 作為工具匯入
你也可以使用 `Tool.from_space()` 將一個 HF Space 作為工具匯入。這為與社群中數千個 Space 整合開闢了可能性,可以用於從影像生成到資料分析的各種任務。
該工具將使用 `gradio_client` 與 Space 的 Gradio 後端連線,所以如果你還沒有安裝,請確保透過 `pip` 安裝它。
對於派對,阿爾弗雷德可以使用一個現有的 HF Space 來生成用於公告的 AI 生成影像(而不是我們之前提到的預構建工具)。讓我們來構建它吧!
from smolagents import CodeAgent, InferenceClientModel, Tool
image_generation_tool = Tool.from_space(
"black-forest-labs/FLUX.1-schnell",
name="image_generator",
description="Generate an image from a prompt"
)
model = InferenceClientModel("Qwen/Qwen2.5-Coder-32B-Instruct")
agent = CodeAgent(tools=[image_generation_tool], model=model)
agent.run(
"Improve this prompt, then generate an image of it.",
additional_args={'user_prompt': 'A grand superhero-themed party at Wayne Manor, with Alfred overseeing a luxurious gala'}
)
匯入 LangChain 工具
我們將在接下來的章節中討論 `LangChain` 框架。現在,我們只需要知道可以在 smolagents 工作流中重用 LangChain 工具!
你可以使用 `Tool.from_langchain()` 方法輕鬆載入 LangChain 工具。阿爾弗雷德,這位永遠的完美主義者,正在韋恩夫婦外出期間為韋恩莊園準備一場壯觀的超級英雄之夜。為了確保每個細節都超出預期,他利用 LangChain 工具來尋找頂級的娛樂創意。
透過使用 `Tool.from_langchain()`,阿爾弗雷德毫不費力地為他的 smolagent 添加了高階搜尋功能,使他能夠僅用幾條命令就發現獨家的派對創意和服務。
他是這樣做的:
from langchain.agents import load_tools
from smolagents import CodeAgent, InferenceClientModel, Tool
search_tool = Tool.from_langchain(load_tools(["serpapi"])[0])
agent = CodeAgent(tools=[search_tool], model=model)
agent.run("Search for luxury entertainment ideas for a superhero-themed event, such as live performances and interactive experiences.")
從任何 MCP 伺服器匯入工具集合
smolagents
還允許從 glama.ai 或 smithery.ai 上數百個可用的 MCP 伺服器匯入工具。如果你想深入瞭解 MCP,可以檢視我們的免費 MCP 課程。
安裝 mcp 客戶端
我們首先需要為 `smolagents` 安裝 `mcp` 整合。
pip install "smolagents[mcp]"
MCP 伺服器工具可以按如下方式載入到一個 ToolCollection 物件中:
import os
from smolagents import ToolCollection, CodeAgent
from mcp import StdioServerParameters
from smolagents import InferenceClientModel
model = InferenceClientModel("Qwen/Qwen2.5-Coder-32B-Instruct")
server_parameters = StdioServerParameters(
command="uvx",
args=["--quiet", "pubmedmcp@0.1.3"],
env={"UV_PYTHON": "3.12", **os.environ},
)
with ToolCollection.from_mcp(server_parameters, trust_remote_code=True) as tool_collection:
agent = CodeAgent(tools=[*tool_collection.tools], model=model, add_base_tools=True)
agent.run("Please find a remedy for hangover.")
透過這種設定,阿爾弗雷德可以迅速發現豪華的娛樂選擇,確保哥譚市的精英客人們擁有一次難忘的體驗。這個工具幫助他為韋恩莊園策劃完美的超級英雄主題活動!🎉
資源
- 工具教程 - 探索此教程以學習如何有效地使用工具。
- 工具文件 - 關於工具的全面參考文件。
- 工具導覽 - 一步一步的導覽,幫助您高效地構建和利用工具。
- 構建高效的 Agent - 關於開發可靠和高效能自定義功能 Agent 的最佳實踐的詳細指南。