Two Agent Modes
Code Agent (Recommended)
The LLM writes Python code to use tools:
from smolagents import CodeAgent, tool, LiteLLMModel
@tool
def search_web(query: str) -> str:
'Search the web and return results.'
import requests
return requests.get(f"https://api.tavily.com/search?q={query}").text
agent = CodeAgent(tools=[search_web], model=LiteLLMModel("anthropic/claude-sonnet-4-20250514"))
result = agent.run("Find the latest news about AI agents")The agent generates Python like:
results = search_web("latest AI agent news 2026")
print(results)Tool Calling Agent
Traditional JSON-based tool calls:
from smolagents import ToolCallingAgent
agent = ToolCallingAgent(tools=[search_web], model=model)Why Code Agent is Better
| Aspect | Code Agent | Tool Calling |
|---|---|---|
| Flexibility | Write any Python logic | Limited to tool schemas |
| Composability | Chain tools with code | Sequential only |
| Data processing | Manipulate results directly | Need extra tools |
| Debugging | Read the generated code | Parse JSON traces |
Custom Tools
from smolagents import tool
@tool
def calculate_roi(investment: float, returns: float) -> str:
'Calculate return on investment percentage.'
roi = ((returns - investment) / investment) * 100
return f"ROI: {roi:.1f}%"
@tool
def query_database(sql: str) -> str:
'Execute SQL query and return results.'
import sqlite3
conn = sqlite3.connect("data.db")
result = conn.execute(sql).fetchall()
return str(result)Multi-Step Agents
from smolagents import CodeAgent, ManagedAgent
# Create specialist agents
researcher = CodeAgent(tools=[search_web], model=model)
writer = CodeAgent(tools=[], model=model)
# Orchestrate with a manager
managed_researcher = ManagedAgent(agent=researcher, name="researcher")
manager = CodeAgent(tools=[], model=model, managed_agents=[managed_researcher])
manager.run("Research AI trends and write a summary")HuggingFace Hub Integration
from smolagents import load_tool
# Load tools from HuggingFace Hub
image_gen = load_tool("image-generation", model="black-forest-labs/FLUX.1-schnell")
speech = load_tool("text-to-speech")
agent = CodeAgent(tools=[image_gen, speech], model=model)Key Stats
- 15,000+ GitHub stars
- By HuggingFace
- 10-line agent setup
- Code Agent mode (unique)
- HuggingFace Hub integration
FAQ
Q: What is Smolagents? A: A minimalist Python agent framework by HuggingFace where you build agents with tool use in under 30 lines of code, featuring a unique Code Agent mode.
Q: Is Smolagents free? A: Yes, open-source under Apache 2.0 license.
Q: How is Smolagents different from LangChain? A: Smolagents is deliberately minimal — 10 lines to a working agent vs 50+ in LangChain. Its Code Agent mode writes Python directly instead of using JSON tool calls.