Tạo Agent với công cụ tùy chỉnh

AI Agents với Hugging Face smolagents

Adel Nehme

VP of AI Curriculum, DataCamp

AI Agents với Hugging Face smolagents

Lợi ích của công cụ tùy chỉnh

  • Độ tin cậy: Viết và kiểm thử logic rõ ràng thay vì để agent đoán
  • Tái sử dụng: Dùng công cụ giữa nhiều dự án và agent
  • Nhất quán: Hành vi dự đoán được qua các lần chạy (tốt cho debug)
  • Kiểm soát truy cập: Chỉ mở những gì bạn muốn (tệp, API, cơ sở dữ liệu, v.v.)
AI Agents với Hugging Face smolagents

Tình huống: Bạn vận hành cửa hàng bán lẻ

  • Dữ liệu tồn kho lưu trong tệp CSV (size, màu, số lượng, giá)
  • Code agent có thể viết mã để đọc CSV
  • Nhưng mặc định không truy cập được tệp
  • Cần gói truy cập tệp trong một công cụ tùy chỉnh

AI Agents với Hugging Face smolagents

Cấu trúc của công cụ tùy chỉnh

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 với Hugging Face smolagents

Thực hành tốt cho công cụ tùy chỉnh

AI Agents với Hugging Face smolagents

Chúng ta còn áo phông trong kho không?

AI Agents với Hugging Face smolagents

Đăng ký công cụ tùy chỉnh với 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 với Hugging Face smolagents

Công cụ tùy chỉnh trong dự án production

AI Agents với Hugging Face smolagents

Ayo berlatih!

AI Agents với Hugging Face smolagents

Preparing Video For Download...