
If you read our earlier overview on What is SmolAgents?, you already know why Hugging Face’s minimalist agent library stands out: instead of forcing an LLM to emit brittle JSON blobs for every tool call, CodeAgent lets the model write and execute Python directly.
In this tutorial, you’ll go from zero to a working research and file-automation agent in under 50 lines of Python. By the end, your agent will be able to:
- Search the web for live information.
- Process and synthesize what it finds using Python.
- Save a structured Markdown report safely to your local
reports/ folder using a custom @tool.
Prerequisites
You need Python 3.10+ and an LLM API key (either a free Hugging Face token or an OpenAI/Anthropic/local Ollama model via LiteLLM).
Install smolagents with the default toolkit (which includes web search):
pip install "smolagents[toolkit]"
Set your Hugging Face token in your terminal:
# macOS / Linux
export HF_TOKEN="hf_your_token_here"
# Windows (PowerShell)
$env:HF_TOKEN="hf_your_token_here"
Tip: Want to use OpenAI, Anthropic, or a local Ollama model instead? Install pip install "smolagents[litellm]" and swap InferenceClientModel for LiteLLMModel(model_id="openai/gpt-4o-mini") or LiteLLMModel(model_id="ollama_chat/qwen2.5-coder:7b").
Step 1: Understand the Two Building Blocks
To build a useful tool-using agent in smolagents, you only need two concepts:
CodeAgent: The agent loop. At each step, the LLM writes a short Python snippet, executes it in a restricted Python interpreter, inspects the output (Observation), and repeats until it calls final_answer(...).
@tool Decorator: Turns any regular Python function into an agent-callable tool. smolagents uses your function’s type hints and docstring to teach the LLM how and when to call it—so clear docstrings and Args: descriptions are required.
Giving an agent raw filesystem access is risky. Instead, wrap file writing in a dedicated @tool that restricts all writes to a specific reports/ directory and sanitizes the filename:
from pathlib import Path
from smolagents import tool
REPORTS_DIR = Path("reports")
@tool
def save_markdown_report(filename: str, content: str) -> str:
"""
Save a Markdown report inside the local reports directory.
Args:
filename: Name of the file, e.g. 'ai_news.md'. Directory paths are stripped.
content: Full Markdown text to write into the file.
"""
REPORTS_DIR.mkdir(exist_ok=True)
safe_name = Path(filename).name
if not safe_name.endswith(".md"):
safe_name += ".md"
target = REPORTS_DIR / safe_name
target.write_text(content, encoding="utf-8")
return f"Saved report to {target}"
Notice why this pattern works well for beginners and production alike:
- Path traversal protection:
Path(filename).name strips any ../ or nested directory tricks.
- Self-documenting schema: The LLM reads
Args: and knows filename is a string and content is Markdown.
Step 3: Put It Together (Under 50 Lines)
Create a file named research_agent.py and paste the complete 39-line script below:
from pathlib import Path
from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel, tool
REPORTS_DIR = Path("reports")
@tool
def save_markdown_report(filename: str, content: str) -> str:
"""
Save a Markdown report inside the local reports directory.
Args:
filename: Name of the file, e.g. 'summary.md'. Directory paths are stripped.
content: Full Markdown text to write into the file.
"""
REPORTS_DIR.mkdir(exist_ok=True)
safe_name = Path(filename).name
if not safe_name.endswith(".md"):
safe_name += ".md"
target = REPORTS_DIR / safe_name
target.write_text(content, encoding="utf-8")
return f"Saved report to {target}"
model = InferenceClientModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct")
agent = CodeAgent(
tools=[DuckDuckGoSearchTool(), save_markdown_report],
model=model,
max_steps=6,
)
result = agent.run(
"Research 3 recent open-source AI agent frameworks released or updated recently. "
"Compare their key strengths in a clean Markdown table and save it as 'agent_frameworks.md'."
)
print(result)
That’s the entire agent—39 lines including imports and whitespace.
Step 4: Run the Agent and Watch the Loop
Execute the script from your terminal:
python research_agent.py
In your console, CodeAgent prints each step of its reasoning loop:
- Step 1 (Search): The model generates Python code calling
web_search(query="open-source AI agent frameworks").
- Step 2 (Synthesize & Save): Using the search results stored in Python variables, the model formats a Markdown table and calls
save_markdown_report(filename="agent_frameworks.md", content=report).
- Step 3 (Finish): Once
save_markdown_report returns "Saved report to reports/agent_frameworks.md", the agent calls final_answer(...) and exits.
Check your project folder—you’ll find reports/agent_frameworks.md ready to read.
Step 5: Next Steps & Safety Best Practices
Once your first agent works, keep these guardrails in mind as you expand it:
- Cap execution steps: Always set
max_steps (e.g., 6–10) so a confused model can’t loop indefinitely and burn through API credits.
- Control imports:
CodeAgent blocks dangerous imports by default. Only whitelist extra libraries when needed via additional_authorized_imports=["json", "csv"].
- Sandbox untrusted tasks: If your agent processes untrusted user prompts or arbitrary web content, run execution inside an isolated container or remote sandbox (such as E2B or Docker) instead of your host machine.
- Read the companion overview: If you want to understand the architecture behind
CodeAgent and when to choose it over heavier frameworks.