只要加上 @tool:撰寫自訂工具
你剛到 AgentsCafé 上班,每桌客人可能會點多杯飲料。
目前吧檯手會手寫像是 T5_Latte_20250812_0915 這樣的訂單代碼,但常因為手誤或格式不一致而造成混淆與送錯。
為了解決這個問題,你要建立一個名為 generate_order_id 的簡單工具,輸入桌號與飲料名稱,並在後面加上時間戳,確保每筆訂單代碼清楚且一致。
注意:已經匯入 datetime 函式庫。
本練習屬於課程
使用 Hugging Face smolagents 的 AI 代理
練習說明
- 從
smolagents函式庫匯入tool裝飾器。 - 使用
@tool裝飾器,將你的generate_order_id函式註冊為工具。 - 回傳格式化後的訂單代碼字串,將桌號、飲料名稱與目前時間戳結合起來。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import the tool decorator
from smolagents import ____
# Create a tool with the @tool decorator
____
def generate_order_id(table_id: str, drink_name: str) -> str:
"""
Generates a unique order ID for a café order.
Args:
table_id: The table's identifier (e.g. "T5")
drink_name: Name of the drink (e.g. "Latte")
Returns:
A string in the format "{table_id}_{drink_name}_{YYYYMMDD_HHMM}"
"""
timestamp = datetime.now().strftime("%Y%m%d_%H%M")
order_id = f"{table_id}_{drink_name}_{timestamp}"
# Return the order ID
return ____