Creating an Agent With Custom Tools

AI Agents with Hugging Face smolagents

Adel Nehme

VP of AI Curriculum, DataCamp

AI Agents with Hugging Face smolagents

Benefits of Custom Tools

  • Reliability: Write and test logic explicitly instead of relying on the agent to guess
  • Reusability: Use tools across projects and agents
  • Consistency: Get predictable behavior across runs (great for debugging)
  • Controlled access: Expose only what you want (files, APIs, databases, etc.)
AI Agents with Hugging Face smolagents

Scenario: You Run a Retail Store

  • Inventory data is stored in a CSV file (size, color, quantity, and price)
  • Code agents can write code to read CSVs
  • But they don't have access to files by default
  • You need to wrap file access in a custom tool

AI Agents with Hugging Face smolagents

Anatomy of a 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 with Hugging Face smolagents

Best Practices for Custom Tools

AI Agents with Hugging Face smolagents

Do we have any t-shirts in stock?

AI Agents with Hugging Face smolagents

Registering a Custom Tool with Your 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 with Hugging Face smolagents

Custom Tools in Production Projects

AI Agents with Hugging Face smolagents

Let's practice!

AI Agents with Hugging Face smolagents

Preparing Video For Download...