智慧體課程文件
使用 smolagents 建立我們的第一個 Agent
並獲得增強的文件體驗
開始使用
使用 smolagents 建立我們的第一個 Agent
在上一節中,我們學習瞭如何使用 Python 程式碼從頭開始建立 Agent,我們看到了這個過程是多麼繁瑣。幸運的是,許多 Agent 庫透過為您處理大量繁重的工作來簡化了這項工作。
在本教程中,您將建立您的第一個 Agent,它能夠執行影像生成、網頁搜尋、時區檢查等操作!
您還將把您的 Agent 釋出到 Hugging Face Space,這樣您就可以與朋友和同事分享它。
讓我們開始吧!
什麼是 smolagents?

為了建立這個 Agent,我們將使用 smolagents
,這是一個提供易於開發 Agent 的框架的庫。
這個輕量級庫旨在簡化操作,但它抽象了構建 Agent 的大部分複雜性,讓您可以專注於設計 Agent 的行為。
我們將在下一個單元深入探討 smolagents。同時,您還可以檢視這篇部落格文章或該庫的GitHub 倉庫。
簡而言之,smolagents
是一個專注於 codeAgent 的庫,這種 Agent 透過程式碼塊執行“行動”,然後透過執行程式碼“觀察”結果。
這是一個我們將要構建的示例!
我們為 Agent 提供了一個影像生成工具,並要求它生成一張貓的圖片。
smolagents
中的 Agent 將具有與我們之前構建的自定義 Agent 相同的行為:它將迴圈思考、行動和觀察,直到得出最終答案。
很激動人心,對吧?
讓我們構建我們的 Agent!
首先,複製此 Space:https://huggingface.co/spaces/agents-course/First_agent_template
感謝 Aymeric 提供的這個模板!🙌
複製此空間意味著在您自己的個人資料上建立一個本地副本。

複製 Space 後,您需要新增您的 Hugging Face API 令牌,以便您的 Agent 可以訪問模型 API。
- 首先,從 https://huggingface.co/settings/tokens 獲取您的 Hugging Face 令牌,並授予推理許可權(如果您還沒有的話)。
- 進入您複製的 Space,然後點選設定 (Settings) 選項卡。
- 向下滾動到變數和秘密 (Variables and Secrets) 部分,然後點選新建秘密 (New Secret)。
- 建立一個名為
HF_TOKEN
的秘密,並將您的令牌貼上為值。 - 點選儲存 (Save) 以安全地儲存您的令牌。
在整個課程中,您唯一需要修改的檔案是(目前不完整的)“app.py”。您可以在模板中的原始檔案中檢視它。要找到您的檔案,請轉到您的 Space 副本,然後點選 Files
選項卡,再點選目錄列表中的 app.py
。
讓我們一起分解程式碼
- 檔案開頭是一些簡單但必需的庫匯入。
from smolagents import CodeAgent, DuckDuckGoSearchTool, FinalAnswerTool, InferenceClientModel, load_tool, tool
import datetime
import requests
import pytz
import yaml
如前所述,我們將直接使用 smolagents 中的 CodeAgent 類。
工具
現在讓我們開始瞭解工具!如果您想複習工具,請隨時返回課程的工具部分。
@tool
def my_custom_tool(arg1:str, arg2:int)-> str: # it's important to specify the return type
# Keep this format for the tool description / args description but feel free to modify the tool
"""A tool that does nothing yet
Args:
arg1: the first argument
arg2: the second argument
"""
return "What magic will you build ?"
@tool
def get_current_time_in_timezone(timezone: str) -> str:
"""A tool that fetches the current local time in a specified timezone.
Args:
timezone: A string representing a valid timezone (e.g., 'America/New_York').
"""
try:
# Create timezone object
tz = pytz.timezone(timezone)
# Get current time in that timezone
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
return f"The current local time in {timezone} is: {local_time}"
except Exception as e:
return f"Error fetching time for timezone '{timezone}': {str(e)}"
工具是我們在本節中鼓勵您構建的!我們為您提供了兩個示例:
- 一個不工作的虛擬工具,您可以修改它以使其有用。
- 一個實際工作的工具,可以獲取世界某地的當前時間。
要定義您的工具,重要的是:
- 為您的函式提供輸入和輸出型別,例如在
get_current_time_in_timezone(timezone: str) -> str:
中。 - 格式良好的文件字串。
smolagents
要求所有引數在文件字串中具有文字描述。
Agent
它使用 Qwen/Qwen2.5-Coder-32B-Instruct
作為 LLM 引擎。這是一個功能強大的模型,我們將透過無伺服器 API 訪問它。
final_answer = FinalAnswerTool()
model = InferenceClientModel(
max_tokens=2096,
temperature=0.5,
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
custom_role_conversions=None,
)
with open("prompts.yaml", 'r') as stream:
prompt_templates = yaml.safe_load(stream)
# We're creating our CodeAgent
agent = CodeAgent(
model=model,
tools=[final_answer], # add your tools here (don't remove final_answer)
max_steps=6,
verbosity_level=1,
grammar=None,
planning_interval=None,
name=None,
description=None,
prompt_templates=prompt_templates
)
GradioUI(agent).launch()
此 Agent 仍然使用我們在早期部分中透過 InferenceClientModel 類看到的 InferenceClient
!
我們將在單元 2 中介紹該框架時提供更深入的示例。現在,您需要關注的是使用 Agent 的 tools
引數將新工具新增到工具列表中。
例如,您可以使用程式碼第一行中匯入的 DuckDuckGoSearchTool
,或者您可以檢視稍後在程式碼中從 Hub 載入的 image_generation_tool
。
新增工具將賦予您的 Agent 新的能力,請在此處發揮您的創造力!
系統提示
Agent 的系統提示儲存在單獨的 prompts.yaml
檔案中。此檔案包含指導 Agent 行為的預定義指令。
將提示儲存在 YAML 檔案中可以輕鬆地在不同 Agent 或用例之間進行自定義和重用。
您可以檢視 Space 的檔案結構,瞭解 prompts.yaml
檔案所在的位置以及它在專案中是如何組織的。
完整的“app.py”
from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel, load_tool, tool
import datetime
import requests
import pytz
import yaml
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI
# Below is an example of a tool that does nothing. Amaze us with your creativity!
@tool
def my_custom_tool(arg1:str, arg2:int)-> str: # it's important to specify the return type
# Keep this format for the tool description / args description but feel free to modify the tool
"""A tool that does nothing yet
Args:
arg1: the first argument
arg2: the second argument
"""
return "What magic will you build ?"
@tool
def get_current_time_in_timezone(timezone: str) -> str:
"""A tool that fetches the current local time in a specified timezone.
Args:
timezone: A string representing a valid timezone (e.g., 'America/New_York').
"""
try:
# Create timezone object
tz = pytz.timezone(timezone)
# Get current time in that timezone
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
return f"The current local time in {timezone} is: {local_time}"
except Exception as e:
return f"Error fetching time for timezone '{timezone}': {str(e)}"
final_answer = FinalAnswerTool()
model = InferenceClientModel(
max_tokens=2096,
temperature=0.5,
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
custom_role_conversions=None,
)
# Import tool from Hub
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
# Load system prompt from prompt.yaml file
with open("prompts.yaml", 'r') as stream:
prompt_templates = yaml.safe_load(stream)
agent = CodeAgent(
model=model,
tools=[final_answer], # add your tools here (don't remove final_answer)
max_steps=6,
verbosity_level=1,
grammar=None,
planning_interval=None,
name=None,
description=None,
prompt_templates=prompt_templates # Pass system prompt to CodeAgent
)
GradioUI(agent).launch()
您的目標是熟悉 Space 和 Agent。
目前,模板中的 Agent 不使用任何工具,因此請嘗試為其提供一些預製的工具,甚至自己製作一些新工具!
我們熱切期待您在 Discord 頻道 #agents-course-showcase 中展示您的精彩 Agent 輸出!
恭喜,您已經構建了您的第一個 Agent!不要猶豫,與您的朋友和同事分享它。
由於這是您的第一次嘗試,如果它有點 Bug 或執行緩慢,這是完全正常的。在未來的單元中,我們將學習如何構建更好的 Agent。
學習的最佳方式是嘗試,所以不要猶豫,更新它,新增更多工具,嘗試不同的模型等。
在下一節中,您將完成最終測驗並獲得您的證書!
< > 在 GitHub 上更新