แค่เพิ่ม @tool: เขียน Custom Tool
คุณเพิ่งเริ่มงานที่ AgentsCafé ซึ่งลูกค้าแต่ละโต๊ะสามารถสั่งเครื่องดื่มได้หลายรายการ
ปัจจุบันบาริสต้าเขียนรหัสออเดอร์ด้วยมือ เช่น T5_Latte_20250812_0915 แต่การพิมพ์ผิดและรูปแบบที่ไม่สม่ำเสมอมักทำให้เกิดความสับสนและส่งเครื่องดื่มผิดโต๊ะ
เพื่อแก้ปัญหานี้ คุณจะสร้างเครื่องมือง่าย ๆ ชื่อ generate_order_id ที่รับหมายเลขโต๊ะและชื่อเครื่องดื่ม แล้วเติม timestamp ต่อท้าย เพื่อให้รหัสออเดอร์ทุกรายการชัดเจนและสม่ำเสมอ
หมายเหตุ: ไลบรารี datetime ถูก import ไว้เรียบร้อยแล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
AI Agents ด้วย Hugging Face smolagents
คำแนะนำการฝึกหัด
- Import decorator
toolจากไลบรารีsmolagents - ใช้ decorator
@toolเพื่อลงทะเบียนฟังก์ชันgenerate_order_idให้เป็นเครื่องมือ - คืนค่าสตริง order ID ที่จัดรูปแบบแล้ว ซึ่งประกอบด้วยหมายเลขโต๊ะ ชื่อเครื่องดื่ม และ timestamp ปัจจุบัน
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# 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 ____