| name | smolagents |
| description | Build lightweight AI agents with HuggingFace Smolagents — use CodeAgent (writes Python to act) or ToolCallingAgent (JSON tool calls), add built-in or custom Tools, orchestrate multi-agent pipelines with ManagedAgent, and run locally or via HF Inference API. |
| triggers | ["smolagents","smol agents","huggingface agents","code agent smolagents","smolagents tool","smolagents codeagent","smolagents toolcallingagent","smolagents managed agent","smolagents multi agent","hf agent framework","smolagents web search","transformers agents"] |
| do_not_use_for | ["Complex multi-agent crews with roles — use crewai instead","State graph agents — use langgraph instead","Workflow automation — use n8n-automation instead"] |
| see_also | ["crewai","langgraph","pydantic-ai"] |
Smolagents — Lightweight HuggingFace Agents
Source: huggingface/smolagents (Apache 2.0) — minimal, fast, code-first agent framework
Why Smolagents
- CodeAgent: writes and executes Python code as actions (more flexible than JSON tool calls)
- Tiny footprint: ~1K lines of core code, easy to understand and customize
- HF-native: works with Transformers, Inference API, Hub models
- Multi-agent: orchestrate agents calling other agents via
ManagedAgent
Install
pip install smolagents
pip install smolagents[transformers]
pip install smolagents[gradio]
pip install smolagents[vision]
pip install smolagents[toolkit]
Quick Start
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel
agent = CodeAgent(
tools=[DuckDuckGoSearchTool()],
model=HfApiModel("Qwen/Qwen2.5-72B-Instruct"),
)
result = agent.run("What are the top 3 AI news stories today?")
print(result)
Models
from smolagents import (
HfApiModel,
LiteLLMModel,
TransformersModel,
OpenAIServerModel,
AmazonBedrockServerModel,
)
model = HfApiModel("Qwen/Qwen2.5-Coder-32B-Instruct")
model = LiteLLMModel("anthropic/claude-sonnet-4-5", api_key="your-key")
model = LiteLLMModel("openai/gpt-4o")
model = TransformersModel(
model_id="Qwen/Qwen2.5-7B-Instruct",
device_map="auto",
torch_dtype="bfloat16",
)
model = OpenAIServerModel(
model_id="llama3.2",
api_base="http://localhost:11434/v1",
api_key="ollama",
)
Agent Types
CodeAgent (default — recommended)
Writes Python code as actions. More flexible, can do multi-step computation.
from smolagents import CodeAgent, LiteLLMModel
agent = CodeAgent(
tools=[],
model=LiteLLMModel("anthropic/claude-sonnet-4-5"),
max_steps=10,
verbosity_level=2,
)
result = agent.run("Calculate the compound interest on $10,000 at 5% for 10 years")
print(result)
ToolCallingAgent (JSON tool calls)
Uses standard function-calling API. More predictable, less flexible.
from smolagents import ToolCallingAgent, DuckDuckGoSearchTool, LiteLLMModel
agent = ToolCallingAgent(
tools=[DuckDuckGoSearchTool()],
model=LiteLLMModel("anthropic/claude-sonnet-4-5"),
)
result = agent.run("Search for the latest news about LLMs")
Built-in Tools
from smolagents import (
DuckDuckGoSearchTool,
WikipediaSearchTool,
VisitWebpageTool,
PythonInterpreterTool,
FinalAnswerTool,
UserInputTool,
SpeechToTextTool,
TextToImageTool,
)
agent = CodeAgent(
tools=[
DuckDuckGoSearchTool(),
VisitWebpageTool(),
WikipediaSearchTool(),
],
model=LiteLLMModel("anthropic/claude-sonnet-4-5"),
)
Custom Tools
Decorator style (simplest)
from smolagents import tool
@tool
def get_stock_price(ticker: str) -> str:
"""
Get the current stock price for a ticker symbol.
Args:
ticker: Stock ticker symbol (e.g., 'AAPL', 'GOOGL')
"""
price = fetch_price(ticker)
return f"{ticker}: ${price:.2f}"
agent = CodeAgent(tools=[get_stock_price], model=LiteLLMModel("anthropic/claude-sonnet-4-5"))
result = agent.run("What is Apple's current stock price?")
Class style (for complex tools)
from smolagents import Tool
class DatabaseQueryTool(Tool):
name = "database_query"
description = "Execute a SQL query against the company database"
inputs = {
"query": {
"type": "string",
"description": "SQL query to execute (SELECT only)",
}
}
output_type = "string"
def __init__(self, connection_string: str):
super().__init__()
self.conn = connect(connection_string)
def forward(self, query: str) -> str:
if not query.strip().upper().startswith("SELECT"):
raise ValueError("Only SELECT queries allowed")
results = self.conn.execute(query).fetchall()
return str(results)
db_tool = DatabaseQueryTool("postgresql://localhost/mydb")
agent = CodeAgent(tools=[db_tool], model=LiteLLMModel("anthropic/claude-sonnet-4-5"))
Multi-Agent Orchestration
from smolagents import CodeAgent, ManagedAgent, DuckDuckGoSearchTool, LiteLLMModel
model = LiteLLMModel("anthropic/claude-sonnet-4-5")
web_agent = CodeAgent(
tools=[DuckDuckGoSearchTool(), VisitWebpageTool()],
model=model,
name="web_researcher",
description="Expert at finding information on the web",
)
managed_web = ManagedAgent(
agent=web_agent,
name="web_researcher",
description="Use this agent to search the web for information",
)
orchestrator = CodeAgent(
tools=[managed_web],
model=model,
)
result = orchestrator.run(
"Research AI trends in 2025 and write a comprehensive report"
)
Vision / Multimodal
from smolagents import CodeAgent, LiteLLMModel
from PIL import Image
model = LiteLLMModel("anthropic/claude-opus-4-5")
agent = CodeAgent(tools=[], model=model)
image = Image.open("chart.png")
result = agent.run(
"Analyze this chart and extract the key data points",
images=[image],
)
Memory / Context
from smolagents import CodeAgent, LiteLLMModel
agent = CodeAgent(tools=[], model=LiteLLMModel("anthropic/claude-sonnet-4-5"))
agent.run("My name is Alice and I work in AI")
result = agent.run("What do you know about me?")
agent.memory.reset()
Gradio UI
from smolagents import CodeAgent, DuckDuckGoSearchTool, LiteLLMModel, GradioUI
agent = CodeAgent(
tools=[DuckDuckGoSearchTool()],
model=LiteLLMModel("anthropic/claude-sonnet-4-5"),
)
GradioUI(agent).launch()
Sandbox Safety (Docker/E2B)
from smolagents import CodeAgent, LiteLLMModel, E2BSandbox
agent = CodeAgent(
tools=[],
model=LiteLLMModel("anthropic/claude-sonnet-4-5"),
executor_type="e2b",
)
from smolagents import LocalPythonInterpreter
agent = CodeAgent(
tools=[],
model=LiteLLMModel("anthropic/claude-sonnet-4-5"),
executor_type="local",
additional_authorized_imports=["pandas", "numpy", "matplotlib"],
)
Anti-Fake-Pass Checks