用自訂工具建立 Agent

使用 Hugging Face smolagents 的 AI 代理

Adel Nehme

VP of AI Curriculum, DataCamp

使用 Hugging Face smolagents 的 AI 代理

自訂工具的優點

  • 可靠性: 明確撰寫並測試邏輯,而非讓 agent 猜測
  • 可重用性: 跨專案與 agent 重複使用工具
  • 一致性: 執行結果可預期(利於除錯)
  • 存取控管: 只曝露你要的資源(檔案、API、資料庫等)
使用 Hugging Face smolagents 的 AI 代理

情境:你經營一家零售店

  • 庫存資料存於 CSV(包含尺寸、顏色、數量、價格)
  • 程式碼型 agent 能撰寫程式讀取 CSV
  • 但預設無法存取檔案
  • 你需要用自訂工具包裝檔案存取

使用 Hugging Face smolagents 的 AI 代理

自訂工具的結構

from smolagents import tool
import pandas as pd

@tool
def check_inventory(product_name: str) -> int:
    """
    Check the available quantity of a product in the inventory CSV.

    Args:
        product_name (str): The name of the product to look up.

    Returns:
        int: The quantity in stock. Returns 0 if the product is not found.
    """
    df = pd.read_csv("store_inventory.csv")
    match = df[df["product_name"] == product_name]
    stock_quantity = int(match.iloc[0]["quantity"]) if not match.empty else 0
    return stock_quantity
使用 Hugging Face smolagents 的 AI 代理

自訂工具的最佳做法

使用 Hugging Face smolagents 的 AI 代理

我們有現貨的 T 恤嗎?

使用 Hugging Face smolagents 的 AI 代理

將自訂工具註冊到你的 Agent

from smolagents import CodeAgent

agent = CodeAgent(
    tools=[check_inventory], # Add custom tool
    model=InferenceClientModel(),
    additional_authorized_imports=["pandas"]  # Allow external package
)

agent.run("Do we have any large t-shirts in stock?")
Yes, we have 8 large t-shirts in stock.
使用 Hugging Face smolagents 的 AI 代理

在正式環境中的自訂工具

使用 Hugging Face smolagents 的 AI 代理

一起來練習吧!

使用 Hugging Face smolagents 的 AI 代理

Preparing Video For Download...