Code Agents with Hugging Face smolagents in Python (2026) — agents that write Python to call tools, instead of only emitting JSON tool calls.
You already cover typed agents with Pydantic AI, handoffs with the OpenAI Agents SDK, and tools via FastMCP. smolagents is the lightweight HF path: CodeAgent + @tool.
TL;DR
CodeAgentgenerates Python snippets that call your tools- Define tools with
@tool(clear name + docstring) InferenceClientModel()hits Hugging Face Inference by default- Authorize extra imports carefully; prefer sandboxes for untrusted runs
Install
pip install smolagents
# optional toolkit extras for search helpers:
# pip install "smolagents[toolkit]"
export HF_TOKEN=hf_... # if using Inference API
Example 1 — @tool + CodeAgent
from smolagents import CodeAgent, InferenceClientModel, tool
@tool
def greet(name: str) -> str:
"""Return a short greeting.
Args:
name: Person to greet.
"""
return f"Hello, {name}!"
agent = CodeAgent(tools=[greet], model=InferenceClientModel())
print(agent.run("Greet Alice in one sentence using the greet tool."))
Example 2 — math without custom tools
from smolagents import CodeAgent, InferenceClientModel
agent = CodeAgent(tools=[], model=InferenceClientModel())
print(agent.run("What is 2 ** 10? Show the integer result."))
For multi-agent protocols, compare with Google A2A.
Production tips
- Keep tool docstrings precise — the model reads them
- Set
max_steps/ verbosity deliberately - Use
additional_authorized_importssparingly - Prefer Docker/E2B executors when code execution must be isolated
Wrap-up
In 2026, code-acting agents are a practical middle ground between brittle JSON tool calling and full frameworks. smolagents keeps that loop small and runnable.