Back to Blog

Agent EngineeringAug 4, 202612 min read

smolagents Framework: The Complete Python Guide to Building AI Agents (2026)

Master the smolagents framework: CodeAgent, tools, multi-agent systems, and agentic RAG with real Python examples. Prep for the 80+ MLQuiz questions.

smolagents Framework: The Complete Python Guide to Building AI Agents (2026)

The smolagents framework by Hugging Face packs full agentic power into roughly 1,000 lines of Python code. That's not a typo. Most agent frameworks arrive bloated with abstractions nobody asked for. smolagents cuts straight to what matters: let an LLM write and run code to complete real tasks.

MLQuiz has published 80+ MCQ questions covering every corner of smolagents. This guide walks you through all seven topic areas so you arrive at the quiz knowing the material cold.

Key Takeaways

  • smolagents keeps its core at roughly 1,000 lines - the leanest production-ready agent framework in 2025 (Hugging Face, smolagents docs)
  • CodeAgent writes executable Python instead of JSON blobs, cutting LLM round-trips for multi-step tasks
  • The framework is model-agnostic: use any LLM from the HF Hub, OpenAI, Anthropic, or local Transformers
  • 80+ MLQuiz questions span 7 subtopics: intro, CodeAgent, tools, RAG, multi-agent, vision, and tool sharing

1. What Is smolagents and Why Should You Learn It?

smolagents is a lightweight, open-source Python library by Hugging Face built for developers who want agents without the framework tax. Its entire core fits in roughly 1,000 lines of code. You can read the source in an afternoon and understand every moving part.

The design philosophy is deliberate: minimal abstractions, maximum transparency. When your agent fails, you see exactly why - not a stack trace buried six layers deep.

Key Features

FeatureDescription
SimplicityMinimal code complexity, easy to extend
Code-FirstCodeAgent writes actions in Python, not JSON
Model-AgnosticWorks with any LLM: local, API, or HF Hub
HF Hub IntegrationShare agents and tools as Spaces
Modality-AgnosticSupports text, vision, video, and audio
Tool-AgnosticUse tools from MCP, LangChain, or Hub Spaces

smolagents vs LangChain vs LangGraph

AspectsmolagentsLangGraph
PhilosophyCode-first, minimal abstractionsGraph-based workflow orchestration
ComplexityLow (~1,000 lines)High (enterprise-grade)
Best forPrototyping, HF ecosystemComplex stateful production systems
Learning curveShallowSteep
State persistenceEphemeralDurable with checkpoint replay

smolagents wins on simplicity and speed to prototype. LangGraph wins on complex stateful workflows. For the MLQuiz test, know this table cold.

Resources:

  • Official docs: https://huggingface.co/docs/smolagents/index
  • GitHub repo: https://github.com/huggingface/smolagents

2. How Does CodeAgent Work?

CodeAgent is the default and recommended agent type in smolagents. Instead of generating a JSON blob to call a tool, it writes actual Python code and executes it in a sandboxed environment. This is the core innovation of the framework.

Internal Flow

  1. Task Initialization: SystemPromptStep and TaskStep are loaded into memory.
  2. Memory Conversion: write_memory_to_messages() converts logs into LLM chat messages.
  3. Code Generation: Model generates a Python code block representing the action.
  4. Parsing: Code parser extracts the valid Python snippet.
  5. Execution: Snippet runs inside a sandboxed environment.
  6. Logging: Execution outputs and variables are stored in an ActionStep.
  7. Loop Control: Process repeats iteratively until final_answer() is called.

Financial Example: Stock Price Alert Agent

This real-world example shows CodeAgent using yfinance to check a stock price against a threshold and raise an alert.

from smolagents import CodeAgent, TransformersModel, tool
import yfinance as yf

@tool
def stock_price(ticker: str, threshold: float) -> str:
    """Get real-time stock price and alert if above threshold.
    Args:
        ticker: Stock symbol (e.g., AAPL)
        threshold: Alert price level
    """
    stock = yf.Ticker(ticker)
    price = stock.history(period="1d")['Close'].iloc[-1]
    return f"{ticker}: ${price:.2f} {'up' if price > threshold else 'ok'} vs ${threshold}"

model = TransformersModel(
    model_id="HuggingFaceTB/SmolLM2-1.7B-Instruct",
    max_new_tokens=256,
    temperature=0.1,
    model_kwargs={"low_cpu_mem_usage": True},
)

agent = CodeAgent(tools=[stock_price], model=model, max_steps=3)
result = agent.run("Check AAPL stock at $200.")
print(result)
# Output: AAPL: $336.91 up vs $200 - EXCEEDS threshold

The agent writes Python to call stock_price, reads the output, and returns the result. No JSON parsing, no intermediate layers. The financial output also mirrors the full example from your data:

  • Input: "Check AAPL stock at $200" - Output: AAPL is $336.91 - EXCEEDS $200
  • Input: "Check TSLA stock at $250" - Output: TSLA is $245.30 - Below $250

Code Execution Security

Because CodeAgent runs real Python, sandboxing is non-negotiable in production. smolagents supports three backends:

  • E2B - Cloud sandboxed microVMs
  • Docker - Containerized local execution
  • Modal - Serverless Python execution

The MLQuiz test asks about this directly. Answer: sandboxed via Modal, E2B, or Docker.


3. CodeAgent vs ToolCallingAgent: Which Should You Use?

smolagents ships two agent types. This comparison appears across multiple MCQ questions - know it precisely.

Side-by-Side Comparison

AspectCodeAgentToolCallingAgent
Action formatPython codeJSON blob
Examplestock_price(AAPL, 200)name: stock_price, args: ticker=AAPL
ParserExtracts code blockParses JSON
ComposabilityHigh - loops, conditionals, object reuseLimited
SecuritySandboxed executionDepends on model
Reliability with small modelsHighLower

Trace Output Comparison

Agent TypeTrace Format
CodeAgentExecuting parsed code: stock_price(AAPL, 200.0)
ToolCallingAgentCalling tool: web_search with arguments: query=best music

When to Use Which

ScenarioRecommended Agent
Complex logic, loops, conditionalsCodeAgent
Simple single function callsToolCallingAgent
Local small models (e.g., SmolLM2)CodeAgent - more reliable
Models fine-tuned for JSON (e.g., Qwen)ToolCallingAgent

The key insight: Python is more expressive than JSON, so CodeAgent handles more cases reliably. Use ToolCallingAgent only when your model handles structured JSON output and the task is a simple single call.


4. How to Create and Share Tools in smolagents

Every tool in smolagents has four required components: name, description, input types and descriptions, and output type. Get these four right and the agent will know exactly how to use your tool.

Method 1: The @tool Decorator (Recommended)

from smolagents import tool

@tool
def portfolio_risk_analyzer(ticker: str, position_size: float) -> str:
    """
    Calculates value at risk and returns risk classification for a portfolio holding.
    Args:
        ticker: Stock or asset symbol (e.g., AAPL, NVDA)
        position_size: Dollar amount invested in the position
    """
    risk_scores = {"AAPL": 0.12, "NVDA": 0.28, "TSLA": 0.35}
    score = risk_scores.get(ticker.upper(), 0.20)
    var = position_size * score
    return f"{ticker}: Estimated 95% VaR is ${var:,.2f} (Risk Score: {score})"

The docstring is not optional. smolagents parses it automatically to extract the tool description and argument descriptions. A poor docstring means a confused agent.

Method 2: Subclassing Tool

Use subclassing when your tool needs state, setup logic, or complex initialization.

from smolagents import Tool

class MarketSentimentTool(Tool):
    name = "market_sentiment_analyzer"
    description = "Analyzes financial sentiment for a sector or index."
    inputs = {
        "sector": {
            "type": "string",
            "description": "Financial sector or asset class (e.g., technology, energy)"
        }
    }
    output_type = "string"

    def forward(self, sector: str):
        sentiments = {
            "technology": "Bullish: Heavy institutional buying detected",
            "energy": "Bearish: Crude inventory surplus weighting on outlook"
        }
        return sentiments.get(sector.lower(), "Neutral sentiment baseline.")

Default Toolbox

smolagents ships six built-in tools you can use without writing a single line of custom code:

ToolPurpose
PythonInterpreterToolExecute Python code
FinalAnswerToolReturn the final answer
UserInputToolGet input from the user
DuckDuckGoSearchToolWeb search via DuckDuckGo
GoogleSearchToolGoogle search
VisitWebpageToolRead webpage content

Sharing and Importing Tools

MethodPurpose
push_to_hub()Share your tool to the HF Hub
load_tool()Import a tool from the HF Hub
Tool.from_space()Import an HF Space as a tool
Tool.from_langchain()Import a LangChain tool
ToolCollection.from_mcp()Import tools from an MCP server

Resources:

  • HF Hub tools browser: https://huggingface.co/tools

5. What Is Agentic RAG and How Does It Differ from Traditional RAG?

Traditional RAG runs a single retrieval step and feeds the results to the LLM. Agentic RAG hands the retrieval process to the agent itself, letting it refine, expand, and validate queries dynamically.

Traditional RAG vs Agentic RAG

AspectTraditional RAGAgentic RAG
Retrieval stepsSingle, fixedMultiple, dynamic
Query formulationFixed upfrontAutonomous, reformulated per result
Result critiqueNoneAgent critiques and refines
Tool usageLimitedFull tool access

Seven Enhanced Retrieval Capabilities

  1. Query Reformulation - Rewrite the query based on what the first search returns
  2. Query Decomposition - Split complex queries into focused sub-queries
  3. Query Expansion - Rephrase the query in multiple wordings to broaden recall
  4. Reranking - Score retrieved documents by semantic relevance
  5. Multi-Step Retrieval - Use results from one query to shape the next
  6. Source Integration - Combine web search results with a local knowledge base
  7. Result Validation - Check document relevance before including it

Custom Knowledge Base Example

from langchain_community.retrievers import BM25Retriever
from smolagents import Tool

class EarningsReportRetrieverTool(Tool):
    name = "earnings_report_retriever"
    description = "Searches SEC 10-K filings and financial reports from a local knowledge base."
    inputs = {"query": {"type": "string", "description": "Financial search query"}}
    output_type = "string"

    def __init__(self, docs, **kwargs):
        super().__init__(**kwargs)
        self.retriever = BM25Retriever.from_documents(docs, k=5)

    def forward(self, query: str) -> str:
        docs = self.retriever.invoke(query)
        return "\nRetrieved SEC filings:\n" + "".join([doc.page_content for doc in docs])

The MLQuiz test asks specifically which retriever is used in the official agentic RAG example. The answer is BM25Retriever.


6. How Do Multi-Agent Systems Work in smolagents?

A multi-agent system routes tasks to specialized agents rather than overloading a single agent with everything. smolagents calls the coordinator the Manager Agent.

Architecture

1. Manager Agent (Orchestrator)

  • Plans tasks dynamically using planning_interval
  • Delegates domain sub-tasks to specialized sub-agents
  • Aggregates outputs and outputs the final response

2. Specialized Sub-Agents

  • Web Agent: Uses DuckDuckGoSearchTool and VisitWebpageTool (max_steps=10)
  • Retriever Agent: Uses custom EarningsReportRetrieverTool (max_steps=3)

Key Parameters

ParameterPurpose
managed_agentsList of agents the manager can delegate to
planning_intervalRe-plan every N steps
final_answer_checksValidate before accepting the final answer
visualize()Print the full agent structure as a tree

Code Example

from smolagents import CodeAgent, DuckDuckGoSearchTool, VisitWebpageTool

web_agent = CodeAgent(
    model=model,
    tools=[DuckDuckGoSearchTool(), VisitWebpageTool()],
    name="web_agent",
    description="Browses financial news and SEC filings",
    max_steps=10,
)

manager_agent = CodeAgent(
    model=model,
    tools=[stock_price],
    managed_agents=[web_agent],
    additional_authorized_imports=["pandas", "yfinance", "numpy"],
    planning_interval=5,
    max_steps=15,
)

manager_agent.run("Find top moving tech stocks today and calculate 30-day volatility.")
# Result: Tech stock movers with calculated volatility table and financial trend summary

The manager does not browse the web itself. It delegates that work to web_agent via managed_agents and then synthesizes the results.


7. Vision Agents: How to Pass Images to smolagents

Vision-Language Models (VLMs) let agents process images alongside text. smolagents supports this through two distinct approaches.

Approach 1: Pre-Provided Images

Pass images into agent.run() at the start of the task. The agent sees all images from step one.

from smolagents import CodeAgent, OpenAIServerModel

model = OpenAIServerModel(model_id="gpt-4o")
agent = CodeAgent(tools=[], model=model, max_steps=20)

response = agent.run(
    "Analyze the technical chart patterns and identify support/resistance levels in these stock charts.",
    images=[chart_image1, chart_image2]
)
# Output: Double bottom pattern detected at $180 support; resistance at $210

Approach 2: Dynamic Retrieval with Screenshots

The agent captures screenshots during execution and attaches them to ActionStep for analysis.

1. Task and optional initial images loaded into TaskStep
2. While final_answer not called:
   2.1 write_inner_memory_from_logs() builds chat messages from history
   2.2 Model generates a code blob
   2.3 Code executes; screenshots saved to observation_images
   2.4 ActionStep appended with observation_images attached
3. When final_answer() is called, return its argument

Key Components

ComponentDescription
images parameter in run()Pass images at task start
observation_images in ActionStepScreenshots captured during execution
step_callbacksHook to capture and save screenshots at each step

8. smolagents Quiz Prep: What MLQuiz Tests You On

MLQuiz has published 80+ questions across seven subtopics. Here is the full breakdown with what each section focuses on.

Question Distribution

TopicMCQsCore Focus
Introduction to smolagents16Design philosophy, agent types, model classes
Building Agents That Use Code15CodeAgent flow, composability, security
Writing actions as code or JSON11When to use which, trace output format
Tools14@tool vs subclass, default toolbox, sharing
Retrieval Agents (RAG)12Agentic vs traditional, BM25Retriever, 7 capabilities
Multi-Agent Systems12Manager agent, planning_interval, delegation
Vision Agents~10images parameter, observation_images, VLMs

Sample Hard Questions with Answers

Q: What is the main abstraction all agents inherit from in smolagents? A: MultiStepAgent

Q: Which method converts agent logs to LLM-readable chat messages? A: write_memory_to_messages()

Q: What does additional_authorized_imports do in CodeAgent? A: It allows the agent to import additional Python packages in its generated code

Q: Where are screenshots stored during dynamic vision agent execution? A: In ActionStep as observation_images

Q: What is Query Expansion in Agentic RAG? A: Reformulating the query in multiple different wordings to broaden retrieval recall

Difficulty Tips

  • Easy - Vocabulary: what is CodeAgent, what does push_to_hub() do, name the six default tools
  • Medium - Mechanics: how does the internal loop work, which method does what, trace output format
  • Hard - Architecture: why use additional_authorized_imports, what inherits from what, how dynamic image retrieval flows

Resources:

  • Take the practice test: https://www.quizforml.com

Frequently Asked Questions

Is smolagents ready for production?

smolagents is production-capable when paired with a sandboxed execution backend such as E2B, Docker, or Modal. The framework itself is stable and actively maintained by Hugging Face. The risk is running LLM-generated code without sandboxing on your host system. With proper containment, teams have deployed smolagents-based systems in live products since 2024.

How is smolagents different from LangChain?

smolagents replaces JSON tool calls with executable Python code, which is more expressive and composable. LangChain uses chain-based abstractions and JSON actions. smolagents is also dramatically simpler at its core: roughly 1,000 lines vs LangChain's much larger codebase. smolagents fits quick prototypes and HF Hub integration best. LangChain fits established production pipelines that already rely on its ecosystem.

What models work with smolagents?

Any model accessible via the Hugging Face Inference API, OpenAI API, or local Transformers library works with smolagents. Use InferenceClientModel for HF Hub models, OpenAIServerModel for OpenAI-compatible APIs, and TransformersModel for local models. For CodeAgent tasks, prefer models with strong code generation ability: GPT-4o, Claude 3.5 Sonnet, or Qwen-Coder variants.

How do I run CodeAgent safely in production?

Use one of three sandboxed backends: E2B cloud microVMs, Docker containers, or Modal serverless functions. All three isolate LLM-generated code from your host system. Never run CodeAgent in production without one of these backends. The MLQuiz test includes a direct question on this topic.

Where are the 80+ smolagents questions on MLQuiz?

Visit https://www.quizforml.com and select the smolagents topic from the practice test or question bank. Questions are organized by subtopic and difficulty level. Start with the Introduction section to build vocabulary, then work through Building Agents for the harder mechanics questions.


Conclusion

smolagents covers seven distinct areas - all tested on MLQuiz. Here is what you've covered in this guide:

  • What smolagents is and how it compares to LangGraph
  • How CodeAgent works end to end, including the financial stock price alert example
  • When to choose CodeAgent over ToolCallingAgent
  • How to build and share tools using @tool and Tool subclasses
  • Agentic RAG and its seven retrieval capabilities over traditional RAG
  • Multi-agent systems with a Manager Agent delegating to specialists
  • Vision agents and both image-passing approaches

The next step is to test yourself. 80+ questions are waiting. You know the material - now prove it.

Practice test: https://www.quizforml.com


References

  • Hugging Face smolagents documentation, retrieved 2025-08-04: https://huggingface.co/docs/smolagents/index
  • smolagents GitHub repository: https://github.com/huggingface/smolagents
  • smolagents.org: https://smolagents.org
  • Hugging Face AI Agents Course, Unit 2: https://huggingface.co/learn/agents-course/unit2/smolagents/introduction
  • DataCamp smolagents tutorial: https://www.datacamp.com/tutorial/smolagents

This article summarises the smolagents framework as covered in the MLQuiz practice question bank.

quizforml.com - Learn. Build. Fail. Learn Again.