การสร้าง Agent ด้วย Custom Tools

AI Agents ด้วย Hugging Face smolagents

Adel Nehme

VP of AI Curriculum, DataCamp

AI Agents ด้วย Hugging Face smolagents

ประโยชน์ของ Custom Tools

  • ความน่าเชื่อถือ: เขียนและทดสอบลอจิกได้ชัดเจน ไม่ต้องให้ agent เดาเอง
  • นำกลับมาใช้ใหม่ได้: ใช้ tools ข้ามโปรเจกต์และ agent ได้
  • ความสม่ำเสมอ: ผลลัพธ์คาดเดาได้ ช่วยให้ดีบักง่ายขึ้น
  • ควบคุมการเข้าถึง: เปิดเผยเฉพาะสิ่งที่ต้องการ (ไฟล์, API, ฐานข้อมูล ฯลฯ)
AI Agents ด้วย Hugging Face smolagents

สถานการณ์: คุณเปิดร้านค้าปลีก

  • ข้อมูลคลังสินค้าเก็บอยู่ในไฟล์ CSV (ขนาด สี จำนวน และราคา)
  • Code agent เขียนโค้ดเพื่ออ่าน CSV ได้
  • แต่โดยค่าเริ่มต้น agent ไม่มีสิทธิ์เข้าถึงไฟล์
  • ต้องห่อการเข้าถึงไฟล์ไว้ใน custom tool

AI Agents ด้วย Hugging Face smolagents

โครงสร้างของ Custom Tool

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
AI Agents ด้วย Hugging Face smolagents

แนวทางปฏิบัติที่ดีสำหรับ Custom Tools

AI Agents ด้วย Hugging Face smolagents

มีเสื้อยืดในสต็อกไหม?

AI Agents ด้วย Hugging Face smolagents

ลงทะเบียน Custom Tool กับ 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.
AI Agents ด้วย Hugging Face smolagents

Custom Tools ในโปรเจกต์จริง

AI Agents ด้วย Hugging Face smolagents

มาฝึกกันเถอะ!

AI Agents ด้วย Hugging Face smolagents

Preparing Video For Download...