SmolAgents Quick Start Template

Agent

Minimal template for getting started with SmolAgents code-based agents.

SmolAgents Quick Start Template

Overview

This template provides a minimal starting point for building AI agents with SmolAgents, Hugging Face's lightweight, code-based agent framework. It's designed for developers who want to understand how agents work internally and build transparent, observable agent systems.

SmolAgents takes a radically simple approach: agents think in code. With approximately 1,000 lines of code, it prioritizes transparency and simplicity over feature complexity.

Prerequisites

  • Python 3.10+
  • Hugging Face account (for model access)
  • Basic understanding of Python

Project Structure

smolagents-project/
├── agent.py              # Main agent definition
├── tools.py              # Custom tools
├── config.py             # Configuration
├── requirements.txt      # Dependencies
└── README.md             # Project documentation

Installation

# Create virtual environment
python -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate

# Install dependencies
pip install smolagents[toolkit]

Quick Start

1. Basic Agent

Create agent.py:

from smolagents import CodeAgent, HfApiModel

# Initialize model
model = HfApiModel(model_id="Qwen/Qwen2.5-72B-Instruct")

# Create agent with no tools
agent = CodeAgent(tools=[], model=model)

# Run a simple task
result = agent.run("What is the capital of France?")
print(result)

2. Adding Tools

Create tools.py:

from smolagents import tool
import requests

@tool
def get_weather(location: str) -> str:
    """Get the current weather for a location.
    
    Args:
        location: The city name (e.g., "Paris", "New York")
    
    Returns:
        A string with the current weather information
    """
    # Replace with actual weather API call
    return f"The weather in {location} is sunny, 25°C"

@tool
def search_web(query: str) -> str:
    """Search the web for information.
    
    Args:
        query: The search query
    
    Returns:
        Search results as a string
    """
    # Replace with actual search API (e.g., Brave Search, Serper)
    return f"Search results for: {query}"

Update agent.py:

from smolagents import CodeAgent, HfApiModel
from tools import get_weather, search_web

model = HfApiModel(model_id="Qwen/Qwen2.5-72B-Instruct")

agent = CodeAgent(
    tools=[get_weather, search_web],
    model=model,
)

# Run a task that uses tools
result = agent.run("What's the weather like in Paris and what are the top news stories today?")
print(result)

3. Multi-Agent System

Create multi_agent.py:

from smolagents import CodeAgent, HfApiModel
from tools import search_web, get_weather

model = HfApiModel(model_id="Qwen/Qwen2.5-72B-Instruct")

# Research agent
researcher = CodeAgent(
    tools=[search_web],
    model=model,
    name="researcher",
    description="Researches topics and gathers information from the web",
)

# Writer agent
writer = CodeAgent(
    tools=[],
    model=model,
    name="writer",
    description="Writes articles and summaries based on research",
)

# Orchestrate
research_result = researcher.run("Research the latest developments in AI agents")
article = writer.run(f"Write a blog post about: {research_result}")

print(article)

Configuration

Create config.py:

from dataclasses import dataclass
from typing import List

@dataclass
class AgentConfig:
    model_id: str = "Qwen/Qwen2.5-72B-Instruct"
    max_iterations: int = 10
    tools: List[str] = None
    
    def __post_init__(self):
        if self.tools is None:
            self.tools = []

# Default configuration
DEFAULT_CONFIG = AgentConfig()

Advanced Examples

Web Agent

from smolagents import web_agent

result = web_agent.run("""
Find the latest news about AI agents and summarize the top 3 stories.
Include links to the original articles.
""")

Code Interpreter

from smolagents import CodeAgent, HfApiModel
import pandas as pd

model = HfApiModel("Qwen/Qwen2.5-72B-Instruct")

agent = CodeAgent(
    tools=[],  # Code interpreter is built-in
    model=model,
)

result = agent.run("""
Create a DataFrame with sample sales data:
- Month: Jan, Feb, Mar, Apr, May
- Sales: 12000, 15000, 18000, 22000, 25000

Calculate the growth rate and create a visualization.
""")

Custom Model

from smolagents import CodeAgent
from smolagents.models import ChatMessage, Model

class CustomModel(Model):
    def __init__(self, api_key: str):
        self.api_key = api_key
    
    def generate(self, prompt: str, **kwargs) -> str:
        # Implement custom model call
        # Could be OpenAI, Anthropic, local model, etc.
        pass
    
    def count_tokens(self, text: str) -> int:
        return len(text.split())

model = CustomModel(api_key="your-api-key")
agent = CodeAgent(tools=[], model=model)

Best Practices

  1. Keep tools simple: Each tool should do one thing well
  2. Write clear docstrings: Agents rely on tool descriptions
  3. Test tools independently: Verify tools work before adding to agent
  4. Use appropriate models: Larger models for complex reasoning
  5. Monitor agent behavior: Code-based execution is transparent—use it

Troubleshooting

Agent not using tools

  • Check tool docstrings are clear and descriptive
  • Ensure the task actually requires the tool
  • Try rephrasing the prompt

Model errors

  • Verify API key is correct
  • Check model ID is valid
  • Ensure sufficient rate limit/quota

Code execution errors

  • Review the generated code for syntax errors
  • Check sandbox permissions
  • Simplify the task if too complex

Resources

View on GitHub

Related Templates