How to Build Your First AI Agent With smolagents in 100 Lines of Python
AI Agent frameworks like LangChain and CrewAI are incredibly powerful, but their learning curves are steep. Enter smolagents by Hugging Face: a framework so lightweight you can build a fully autonomous AI agent in less than 100 lines of code.
The Framework Bloat Problem
When developers decide they want to build an AI agent, they usually Google "how to build AI agents" and immediately get funneled into massively complex frameworks.
Don't get me wrong, these frameworks are incredible for enterprise production. But if you just want to build a simple script where an LLM can search the web and save a file, using a massive framework feels like using a sledgehammer to crack a nut. You spend 5 hours reading documentation about abstractions, runnables, and memory classes before writing a single line of useful code.
This is exactly why Hugging Face released smolagents. It is a radically simple framework. It's roughly 1,000 lines of source code in total. There are no massive abstractions. It focuses on one thing: giving an LLM tools, and letting it write code to use them. Let's build one right now.
CodeAgents: The Magic of smolagents
Most AI agents work by outputting JSON to call tools. smolagents introduces a different concept: the CodeAgent.
Instead of asking the LLM to format a JSON object, smolagents tells the LLM: "Here are some Python functions. To solve the user's problem, write a snippet of Python code calling these functions." The framework then securely executes that Python snippet locally. This approach is drastically more accurate and reduces hallucination significantly.
Step 1: The Setup
First, create a new folder and install the library. We will use the Anthropic API for the brain of our agent, so we need that library too.
pip install smolagents anthropic python-dotenvCreate a .env file in your folder and add your API key:
ANTHROPIC_API_KEY=sk-ant-api03...Step 2: Writing the Agent
We are going to build a Research Agent. We will give it a built-in tool to search the web, and a custom tool to save text to a file.
Create a file called agent.py and drop in this code:
from smolagents import CodeAgent, DuckDuckGoSearchTool, LiteLLMModel, tool
import os
from dotenv import load_dotenv
load_dotenv()
# 1. Define the Brain (the LLM)
model = LiteLLMModel(
model_id="anthropic/claude-3-5-sonnet-20240620",
api_key=os.getenv("ANTHROPIC_API_KEY")
)
# 2. Create a Custom Tool
@tool
def save_to_file(content: str, filename: str) -> str:
"""Saves text content to a file.
Args:
content: The text to save
filename: The name of the file (e.g., research.txt)
"""
with open(filename, 'w') as f:
f.write(content)
return f"Successfully saved to {filename}"
# 3. Instantiate the Agent
agent = CodeAgent(
tools=[DuckDuckGoSearchTool(), save_to_file],
model=model,
additional_authorized_imports=["datetime"]
)
# 4. Give it a task!
agent.run("Search the web for the latest updates on the James Webb Space Telescope. Summarize the top 3 discoveries and save them to a file called jwst_news.txt")Step 3: Watching It Think
Run the script: python agent.py.
In your terminal, you will see something beautiful. The agent will output its "thought process".
First, it will write a snippet of Python to call the DuckDuckGoSearchTool. The framework executes it and returns the search results to the LLM.
Then, the LLM reads the results, formats a summary string, and writes a second Python snippet calling your custom save_to_file tool.
Look in your folder. A file called jwst_news.txt will have magically appeared with a perfect summary inside. You just built a fully autonomous agent in exactly 30 lines of code.
Why smolagents is the Perfect Starting Point
Notice what we didn't have to do. We didn't have to define complex Pydantic schemas for our tools—the @tool decorator read our Python docstring automatically. We didn't have to set up memory management or custom execution loops.
By relying on Python's native execution for tool calling, smolagents reduces the cognitive load on both the developer and the LLM.
If you want to transition from just "prompting" AI to actually building software with it, smolagents is the bridge. Take the script above, swap out the search tool for an API call to your company database, and see what you can automate by tomorrow.
FAQ
Is it safe to let the LLM write and execute Python code locally?
By default, smolagents is very restrictive. It uses a secure, sandboxed execution environment (a custom abstract syntax tree evaluator) that only allows basic Python operations and explicitly 'authorized imports' that you define. It cannot randomly import the 'os' module and delete your hard drive.
Can I use local models with smolagents?
Yes. You can swap the LiteLLMModel for a HuggingFace endpoint or connect it to an Ollama server to use local models like Llama 3 or Qwen.
Is smolagents ready for production?
For simple, linear workflows and utility scripts, absolutely. For highly complex, multi-agent enterprise systems requiring heavy human-in-the-loop approvals, frameworks like LangGraph are still the better choice.
Explore RuView on GitHub
Browse the Rust engine, ESP32 firmware and examples.