使用自定义工具创建代理

使用 Hugging Face smolagents 的 AI Agents

Adel Nehme

VP of AI Curriculum, DataCamp

使用 Hugging Face smolagents 的 AI Agents

自定义工具的优势

  • 可靠性:显式编写并测试逻辑,而非让代理猜测
  • 可复用性:在不同项目与代理间复用工具
  • 一致性:跨多次运行行为可预测(便于调试)
  • 受控访问:仅暴露所需内容(文件、API、数据库等)
使用 Hugging Face smolagents 的 AI Agents

情境:你经营一家零售店

  • 库存数据存于 CSV(尺寸、颜色、数量、价格)
  • 代码代理可编写代码读取 CSV
  • 但默认无法访问文件
  • 需用自定义工具封装文件访问

使用 Hugging Face smolagents 的 AI Agents

自定义工具结构解析

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 Agents

自定义工具最佳实践

使用 Hugging Face smolagents 的 AI Agents

我们有 T 恤现货吗?

使用 Hugging Face smolagents 的 AI Agents

为代理注册自定义工具

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 Agents

在生产项目中使用自定义工具

使用 Hugging Face smolagents 的 AI Agents

Passons à la pratique !

使用 Hugging Face smolagents 的 AI Agents

Preparing Video For Download...