Hugging Face 推出 smolagents 智能體程式庫,支援以程式碼編寫動作
Introducing smolagents: simple agents that write actions in code.
Hugging Face 推出 smolagents,讓語言模型智能體可用程式碼編寫動作。它提供以程式碼運作的 CodeAgent,也支援以 JSON/text 編寫動作的 ToolCallingAgent,並可透過 E2B 在沙盒環境執行。
文章説明程式碼表達動作在組合與重用上的優勢,並展示 smolagents 仍支援 JSON/text 工具調用。
今天我們推出 smolagents,這是一個非常簡潔的程式庫,讓語言模型具備 Agent 能力。先看看它的概況:
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel
agent = CodeAgent(tools=[DuckDuckGoSearchTool()], model=HfApiModel())
agent.run("How many seconds would it take for a leopard at full speed to run through Pont des Arts?")
目錄
🤔 甚麼是 Agent?
任何有效運用 AI 的系統,都需要讓 LLM 以某種方式接觸現實世界,例如使用搜尋工具取得外部資訊,或操作某些程式來完成任務。換言之,LLM 應該具備自主行動能力。Agent 程式就是 LLM 通往外部世界的橋樑。
AI Agent 是由 LLM 輸出控制工作流程的程式。
任何運用 LLM 的系統,都會把 LLM 輸出整合到程式碼中。LLM 的輸入對程式工作流程影響有多大,就是該系統中 LLM 自主行動能力的程度。
請注意,按此定義,「Agent」並非 0 或 1 的離散分類;相反,隨着你給予 LLM 的工作流程控制權增加或減少,其「自主行動能力」會沿着連續光譜變化。
下表説明不同系統的自主行動能力如何變化:
| 自主程度 | 描述 | 稱為 | 範例模式 |
|---|---|---|---|
| ☆☆☆ | LLM 輸出不影響程式流程 | 簡單處理器 | process_llm_output(llm_response) |
| ★☆☆ | LLM 輸出決定基本控制流程 | 路由器 | if llm_decision(): path_a() else: path_b() |
| ★★☆ | LLM 輸出決定函式執行 | 工具呼叫 | run_function(llm_chosen_tool, llm_chosen_args) |
| ★★★ | LLM 輸出控制迭代及程式是否繼續 | 多步驟 Agent | while llm_should_continue(): execute_next_step() |
| ★★★ | 一個 Agent 工作流程可以啟動另一個 Agent 工作流程 | 多 Agent | if llm_trigger(): execute_agent() |
多步驟 Agent 的程式結構如下:
memory = [user_defined_task]
while llm_should_continue(memory): # this loop is the multi-step part
action = llm_get_next_action(memory) # this is the tool-calling part
observations = execute_action(action)
memory += [action, observations]
這個系統會以迴圈方式執行,每一步都採取新行動(行動可以包括呼叫預先定義、以函式形式實作的工具),直至根據觀察結果判斷已達到足以完成任務的狀態。以下示範多步驟 Agent 如何解答一道簡單數學題:
✅ 何時使用 Agent/⛔ 何時避免使用
當你需要 LLM 決定應用程式的工作流程時,Agent 很有用,但很多時候它們只是過度設計。問題是:要有效完成當前任務,我是否真的需要具彈性的工作流程? 如果預先設定的工作流程經常無法應付情況,便代表你需要更大的彈性。 舉例説,假設你正在為一個衝浪旅行網站開發處理客戶要求的應用程式。
你可能預先知道,按用戶選擇,要求只會屬於 2 類,而這 2 種情況各有預設工作流程。
- 想查詢行程?⇒ 提供搜尋欄,讓他們搜尋你的知識庫。
- 想聯絡銷售?⇒ 讓他們填寫聯絡表格。
如果這個確定性工作流程適用於所有查詢,那就直接把所有流程寫成程式吧!這樣就能得到 100% 可靠的系統,不會因不可預測的 LLM 介入工作流程而引入錯誤風險。為求簡潔和穩健,建議盡量避免採用 Agent 行為。
但如果無法預先準確確定工作流程呢?
例如,用戶想問:"I can come on Monday, but I forgot my passport so risk being delayed to Wednesday, is it possible to take me and my stuff to surf on Tuesday morning, with a cancellation insurance?"這個問題取決於多項因素,上述預設準則大概沒有一項足以應付這個要求。
如果預先設定的工作流程經常無法應付情況,便代表你需要更大的彈性。
這正是 Agent 設定能發揮作用的地方。
以上述例子來説,你可以建立一個多步驟 Agent,讓它使用天氣預報 API、計算路程的 Google Maps API、員工可用時間儀錶板,以及知識庫的 RAG 系統。
直到最近,電腦程式仍受限於預先設定的工作流程,通常只能不斷堆疊 if/else 分支來處理複雜情況。它們專注於極狹窄的任務,例如「計算這些數字的總和」或「找出圖中最短路徑」。但事實上,大部分現實任務,例如上面的行程例子,都無法套用預先設定的工作流程。Agent 系統為程式開啟了廣闊的真實世界任務!
在多步驟 Agent 中,LLM 每一步都可以撰寫一項行動,形式是呼叫一些外部工具。Anthropic、OpenAI 及其他多家公司常用的格式,大致是「把行動寫成 JSON,列出要使用的工具名稱和參數,再剖析它以確定要執行甚麼工具和傳入甚麼參數」的不同變體。
多篇研究論文指出,把工具呼叫交由程式碼中的 LLM 處理,效果好得多。
原因很簡單:我們專門設計程式語言,讓它成為表達電腦執行動作的最佳方式。如果 JSON 片段更適合表達程式指令,JSON 早已成為最流行的程式語言,而編程亦會變成一場惡夢。
以下圖片取自《Executable Code Actions Elicit Better LLM Agents》,展示以程式碼撰寫行動的一些優點:

相較於類似 JSON 的片段,以程式碼撰寫行動在以下方面更佳:
- 可組合性:你可以像定義 Python 函式一樣,在 JSON 中巢狀放入其他 JSON 行動,或定義一組日後重用的 JSON 行動嗎?
- 物件管理:如何在 JSON 中儲存
generate_image這類行動的輸出? - 通用性:程式碼天生就能簡單表達電腦可執行的任何事情。
- 在 LLM 訓練數據中的表示:LLM 的訓練數據已包含大量優質程式碼行動,因此模型早已受過相關訓練!
隆重介紹 smolagents:讓 Agent 更簡單 🥳
我們按以下目標建立了 smolagents:
✨ 簡潔:Agent 邏輯只需約數千行程式碼(見此檔案)。我們只保留最基本的抽象,盡量貼近原始程式碼!
🧑💻 優先支援 Code Agent,也就是以程式碼撰寫行動的 Agent(而不是用來編寫程式碼的 Agent)。為確保安全,我們支援透過 E2B 在沙盒環境中執行。
- 除了這個
CodeAgent類別,我們也支援標準的ToolCallingAgent,以 JSON/文字區塊撰寫行動。
🤗 Hub 整合:你可以在 Hub 分享和載入工具,更多功能亦即將推出!
🌐 支援任何 LLM:它支援在 Hub 託管、以 transformers 版本載入或透過我們推論 API 使用的模型;亦透過 LiteLLM 整合,支援 OpenAI、Anthropic 等多家公司的模型。
smolagents 是 transformers.agents 的後繼程式庫;待日後 transformers.agents 棄用後,它將取而代之。
建立 Agent
建立 Agent 至少需要兩個元素:
tools:Agent 可使用的工具清單model:作為 Agent 引擎的 LLM。
至於 model,你可以使用任何 LLM:可以透過 HfApiModel 類別使用開放模型,該類別會運用 Hugging Face 免費推論 API(如上方 leopard 範例所示);亦可使用 LiteLLMModel,透過 litellm 從 100 多種雲端 LLM 中選擇。
至於工具,只需建立一個函式,為輸入和輸出加入型別提示,並以 docstring 説明輸入,再使用 @tool 裝飾器將它變成工具。
以下示範如何建立自訂工具,使用 Google Maps 取得行程時間,以及如何在行程規劃 Agent 中使用它:
from typing import Optional
from smolagents import CodeAgent, HfApiModel, tool
@tool
def get_travel_duration(start_location: str, destination_location: str, transportation_mode: Optional[str] = None) -> str:
"""Gets the travel time between two places.
Args:
start_location: the place from which you start your ride
destination_location: the place of arrival
transportation_mode: The transportation mode, in 'driving', 'walking', 'bicycling', or 'transit'. Defaults to 'driving'.
"""
import os # All imports are placed within the function, to allow for sharing to Hub.
import googlemaps
from datetime import datetime
gmaps = googlemaps.Client(os.getenv("GMAPS_API_KEY"))
if transportation_mode is None:
transportation_mode = "driving"
try:
directions_result = gmaps.directions(
start_location,
destination_location,
mode=transportation_mode,
departure_time=datetime(2025, 6, 6, 11, 0), # At 11, date far in the future
)
if len(directions_result) == 0:
return "No way found between these places with the required transportation mode."
return directions_result[0]["legs"][0]["duration"]["text"]
except Exception as e:
print(e)
return e
agent = CodeAgent(tools=[get_travel_duration], model=HfApiModel(), additional_authorized_imports=["datetime"])
agent.run("Can you give me a nice one-day trip around Paris with a few locations and the times? Could be in the city or outside, but should fit in one day. I'm travelling only with a rented bicycle.")
Agent 收集行程時間並執行數次計算後,會提出以下最終方案:
One-day Paris bike trip itinerary:
1. Start at Eiffel Tower at 9:00 AM.
2. Sightseeing at Eiffel Tower until 10:30 AM.
3. Travel to Notre-Dame Cathedral at 10:46 AM.
4. Sightseeing at Notre-Dame Cathedral until 12:16 PM.
5. Travel to Montmartre at 12:41 PM.
6. Sightseeing at Montmartre until 2:11 PM.
7. Travel to Jardin du Luxembourg at 2:33 PM.
8. Sightseeing at Jardin du Luxembourg until 4:03 PM.
9. Travel to Louvre Museum at 4:12 PM.
10. Sightseeing at Louvre Museum until 5:42 PM.
11. Lunch break until 6:12 PM.
12. Planned end time: 6:12 PM.
建立工具後,只需以下指令便可分享到 Hub:
get_travel_duration.push_to_hub("{your_username}/get-travel-duration-tool")
你可以在這個 Space查看結果。
你可以在 Space 的tool.py 檔案查看工具邏輯。如你所見,這個工具實際上會匯出成繼承 Tool 類別的 class,而這是我們所有工具的底層結構。
開放模型處理 Agent 工作流程的能力有多強?
我們以多個領先模型建立了 CodeAgent 實例,並用這個基準測試進行比較。該測試彙集了數個不同基準的問題,組成多元挑戰組合。
在此查看基準測試,瞭解所用的 Agent 設定;亦可比較 Code Agent 與工具呼叫 Agent(劇透:程式碼方式更佳)。
這項比較顯示,開源模型如今已可挑戰最優秀的閉源模型!
下一步 🚀
- 先閲讀導覽,熟悉這個程式庫。
- 閲讀更深入的教學,瞭解工具或一般最佳實務。
- 參考各種範例,建立特定系統:text-to-SQL、Agentic RAG或多 Agent 協作編排。
- 深入瞭解 Agent:
來源:Hugging Face Blog · huggingface.co