Skip to content

smolagents - Code-First AI Agents Cheatsheet

smolagents - Code-First AI Agents Cheatsheet

smolagents is a minimal, code-first agent library from Hugging Face. Its central idea: instead of having the model emit tool calls as JSON blobs, a CodeAgent writes and executes Python code directly. Expressing actions as code lets a single step call multiple tools, use loops and variables, and chain logic — which reduces the number of LLM round-trips (roughly ~30% fewer) and improves performance on complex tasks. It is model-agnostic, supports sandboxed execution, and stays deliberately small and hackable.

Installation

MethodCommand
pippip install smolagents
With tools extraspip install "smolagents[toolkit]"
Sandbox extraspip install "smolagents[e2b]" (or [docker])
Set a model keyexport HF_TOKEN=... or provider keys
Verifypython -c "import smolagents; print('ok')"

Core Concepts

TermMeaning
CodeAgentAgent that writes Python actions (the default)
ToolCallingAgentAgent that emits classic JSON tool calls
ToolA callable the agent can use (with a schema)
ModelThe LLM backend (HF, OpenAI, LiteLLM, local)
SandboxWhere generated code runs (local, E2B, Docker, Modal)

A Minimal CodeAgent

from smolagents import CodeAgent, WebSearchTool, InferenceClientModel

agent = CodeAgent(
    tools=[WebSearchTool()],
    model=InferenceClientModel(),   # HF Inference API
)

agent.run("How many seconds would it take a cheetah to cross the Golden Gate Bridge?")
ObjectRole
CodeAgent(tools=[...], model=...)The agent
agent.run("task")Execute a task end to end
WebSearchTool()A built-in tool
InferenceClientModel()HF-hosted model backend

Models

BackendClass
HF Inference APIInferenceClientModel
Local transformersTransformersModel
Any provider via LiteLLMLiteLLMModel(model_id="openai/gpt-4o")
OpenAI-compatible serverOpenAIServerModel(...)
vLLM / local endpointsvia LiteLLM / OpenAI-compatible

Defining Tools

from smolagents import tool

@tool
def get_weather(city: str) -> str:
    """Return the weather for a city.

    Args:
        city: The city to look up.
    """
    return f"Sunny in {city}"

agent = CodeAgent(tools=[get_weather], model=InferenceClientModel())
MechanismUse
@tool decoratorTurn a typed function into a tool
Tool subclassMore control over schema/behavior
Tool CollectionsImport sets of tools (e.g. from the Hub)
MCP toolsConnect Model Context Protocol servers

Sandboxed Execution (Important)

Because CodeAgents run generated Python, isolate it in production.

SandboxHow
Local (default)Runs in-process — fine for trusted dev only
E2Bexecutor_type="e2b" (remote sandbox)
Dockerexecutor_type="docker"
ModalRemote sandboxed execution
Allowed importsRestrict which modules generated code may import
agent = CodeAgent(tools=[...], model=..., executor_type="e2b")

Multi-Agent & Retrieval

PatternHow
Managed agentsGive one agent other agents as tools
Retrieval/RAGAdd a retriever tool for grounded answers
PlanningEnable periodic planning steps for hard tasks
HandoffsCompose specialists under a manager agent

Common Workflows

# A research agent that browses and computes in code
from smolagents import CodeAgent, WebSearchTool, InferenceClientModel
agent = CodeAgent(tools=[WebSearchTool()], model=InferenceClientModel(),
                  executor_type="docker")
agent.run("Compare the population growth of Tokyo and Delhi since 2000.")

smolagents vs Other Agent Frameworks

AspectsmolagentsLangGraphPydantic AI
Action formatPython codeGraph/state machineTyped tool calls
Size/philosophyMinimal, hackableFull state orchestrationType-safe, FastAPI-style
LLM efficiencyFewer calls (code)DependsStandard
Best forSingle-agent code loopsDurable stateful agentsType-safe production agents

Resources