# smolagents 1.26 in depth: code agents versus JSON tool calls, sandboxes and managed agents

smolagents is the smallest serious agent framework: agents write Python instead of JSON. This guide runs version 1.26 offline with a scripted model, counts model calls and prompt size, and shows where its interpreter stops code, and where it does not.

Most agent frameworks ask the model to emit a JSON object per tool call: one name, one set of arguments, one round trip. Hugging Face's smolagents takes the other road. Its default agent, `CodeAgent`, asks the model to write a short Python snippet. The snippet can call several tools, loop, do arithmetic and then call `final_answer`, all in one step. The framework runs the snippet in its own restricted interpreter and feeds the printed output back to the model.

That design changes three things you care about in production: how many model calls a task takes, how big each prompt is, and what can go wrong when the model's code runs. This article measures all three on smolagents 1.26.0, the current release on PyPI, using a scripted model so every run below is reproducible without an API key. It then covers the safety layers, final answer checks, step limits and managed agents, with the exact outputs.

## What happened

### smolagents 1.25.0 ships (14 May 2026)

PyPI lists smolagents 1.25.0 on 14 May 2026. It is the base for the current line.

### smolagents 1.26.0 removes the remote Wasm executor and adds Exa search (29 May 2026)

Version 1.26.0, released on 29 May 2026 according to PyPI, added Exa as a search engine option in `WebSearchTool` and removed the remote `WasmExecutor`. The 1.26 reference documentation now lists five values for `executor_type`: `"local"`, `"blaxel"`, `"e2b"`, `"modal"` and `"docker"`. As of 24 November 2026, 1.26.0 is still the latest version on PyPI, and the docs still describe smolagents as "an experimental API which is subject to change at any time."

Six months without a release is long in agent tooling. It also means the API below has been stable for half a year, which makes it a good reference point when you compare frameworks. For the wider landscape, see the site's comparison of [one agent in seven frameworks](/articles/one-agent-seven-frameworks-compared).

## How a code agent works

A JSON tool-calling agent is like ordering at a counter one item at a time: you ask for a coffee, wait, then ask for a pastry, wait again. A code agent hands over a written order: "two coffees, one pastry, and if the pastry is out, a muffin." One trip, with logic included.

smolagents implements both styles on one base class, `MultiStepAgent`, which runs the ReAct cycle: the model produces an action, the framework executes it and records an observation, and the loop repeats until a final answer or the step limit. The [ReAct loop](/tools/react-loop) page explains the cycle in general.

| Class | Action format | Who executes it | Typical steps for multi-tool work |
|---|---|---|---|
| `CodeAgent` (default) | Python snippet between code tags | smolagents' Python interpreter or a remote sandbox | Often one |
| `ToolCallingAgent` | JSON tool calls via the provider's tool-calling API | smolagents calls each tool | One per round of tool calls |

The idea comes from research. The CodeAct paper, "Executable Code Actions Elicit Better LLM Agents" (ICML 2024), reported that code actions outperformed widely used alternatives with "up to 20% higher success rate" across 17 models. That result is from 2024 models and benchmarks; treat it as motivation, not a guarantee for your task.

### A scripted model for offline runs

To run agents without an API, subclass smolagents' `Model` and return pre-written replies. `CodeAgent` reads text, `ToolCallingAgent` reads tool calls, so the script supports both.

```python
# scripted.py  (pip install "smolagents==1.26.0")
from smolagents.models import Model, ChatMessage, MessageRole, ChatMessageToolCall, ChatMessageToolCallFunction

class ScriptedModel(Model):
    """Returns pre-written replies in order and records what it was sent."""
    def __init__(self, replies):
        super().__init__(model_id="scripted")
        self.replies, self.calls = list(replies), []

    def generate(self, messages, stop_sequences=None, response_format=None,
                 tools_to_call_from=None, **kwargs):
        self.calls.append(messages)
        reply = self.replies.pop(0)
        if isinstance(reply, str):                       # CodeAgent: text with a code block
            return ChatMessage(role=MessageRole.ASSISTANT, content=reply)
        calls = [ChatMessageToolCall(id=f"t{i}", type="function",
                 function=ChatMessageToolCallFunction(name=n, arguments=a))
                 for i, (n, a) in enumerate(reply)]      # ToolCallingAgent: JSON tool calls
        return ChatMessage(role=MessageRole.ASSISTANT, content="", tool_calls=calls)
```

A tool is a plain function with type hints and a docstring that has an `Args:` section; the `@tool` decorator turns it into a schema.

```python
# fx.py
from smolagents import tool

RATES = {("USD", "EUR"): 0.92, ("USD", "TRY"): 34.5}

@tool
def fx_rate(base: str, quote: str) -> float:
    """Return the exchange rate from one currency to another.

    Args:
        base: Three-letter code of the currency you have, for example USD.
        quote: Three-letter code of the currency you want, for example EUR.
    """
    return RATES[(base, quote)]
```

## Measured: one task, two agent styles

The task: "I have 120, 80 and 45.5 USD. What is the total in EUR and in TRY?" By hand, 120 + 80 + 45.5 = 245.5 USD; 245.5 × 0.92 = 225.86 EUR; 245.5 × 34.5 = 8,469.75 TRY.

```python
# compare.py
from smolagents import CodeAgent, ToolCallingAgent
from scripted import ScriptedModel
from fx import fx_rate

TASK = "I have 120, 80 and 45.5 USD. What is the total in EUR and in TRY?"

code_reply = '''Thought: I can fetch both rates and do the arithmetic in one step.
<code>
total_usd = sum([120, 80, 45.5])
eur = round(total_usd * fx_rate(base="USD", quote="EUR"), 2)
try_ = round(total_usd * fx_rate(base="USD", quote="TRY"), 2)
final_answer(f"{total_usd} USD = {eur} EUR = {try_} TRY")
</code>'''

code_model = ScriptedModel([code_reply])
code_agent = CodeAgent(tools=[fx_rate], model=code_model, verbosity_level=0)
print("CodeAgent       :", code_agent.run(TASK), "| model calls:", len(code_model.calls))

json_model = ScriptedModel([
    [("fx_rate", {"base": "USD", "quote": "EUR"})],
    [("fx_rate", {"base": "USD", "quote": "TRY"})],
    [("final_answer", {"answer": "245.5 USD = 225.86 EUR = 8469.75 TRY"})],
])
json_agent = ToolCallingAgent(tools=[fx_rate], model=json_model, verbosity_level=0)
print("ToolCallingAgent:", json_agent.run(TASK), "| model calls:", len(json_model.calls))
```

```text
CodeAgent       : 245.5 USD = 225.86 EUR = 8469.75 TRY | model calls: 1
ToolCallingAgent: 245.5 USD = 225.86 EUR = 8469.75 TRY | model calls: 3
```

In 1.26 the default code tags are `<code>` and `</code>` (`agent.code_block_tags` returns `('<code>', '</code>')`); you can switch to Markdown fences with `code_block_tags="markdown"`.

Fewer calls is not the whole story. The scripted model records every prompt it receives, so we can measure input size. Counting characters of message content per call:

| Agent | Call 1 | Call 2 | Call 3 | Total input characters |
|---|---|---|---|---|
| `CodeAgent` | 8,840 (2 messages) | | | 8,840 |
| `ToolCallingAgent` | 3,562 (2 messages) | 3,707 (5 messages) | 3,852 (8 messages) | 11,121 |

The code agent's system prompt is about 2.5 times larger, because it teaches the model how to write code actions and lists the rules. The JSON agent starts small but grows with each round, because every tool call and observation is appended to the history. Here the code agent still wins on total input, 8,840 against 11,121 characters, and it waited for one model response instead of three. With a single tool call, the balance flips: one JSON round trip with a small prompt beats one code step with a big prompt. The [agent loop token cost simulation](/ai-simulations/agent-loop-token-cost) lets you vary the number of steps and see where the lines cross. Note the JSON agent could also batch both rate lookups into one turn if the model emits parallel tool calls; smolagents runs them in threads, controlled by `max_tool_threads`.

## Where code runs, and what stops it

A code agent runs model-written code, so execution safety is the real design question. smolagents has two layers.

### Layer 1: the local interpreter

By default (`executor_type="local"`), smolagents does not call Python's `exec`. Its `LocalPythonExecutor` parses the snippet into a syntax tree and evaluates it node by node. The docs list its rules: imports are disallowed unless authorized, submodules need explicit authorization, the count of elementary operations is capped to stop infinite loops, and "any operation that has not been explicitly defined in our custom interpreter will raise an error."

Here a scripted model first tries to look at the file system, then recovers:

```python
# safety.py
from smolagents import CodeAgent
from scripted import ScriptedModel
from fx import fx_rate

bad = '''Thought: Let me look at the environment first.
<code>
import os
print(os.listdir("/"))
</code>'''
good = '''Thought: os is not allowed. I will just use the tool.
<code>
final_answer(round(245.5 * fx_rate(base="USD", quote="EUR"), 2))
</code>'''

model = ScriptedModel([bad, good])
agent = CodeAgent(tools=[fx_rate], model=model, verbosity_level=0, max_steps=4)
print("answer:", agent.run("Total of 245.5 USD in EUR?"))
```

```text
Code execution failed at line 'import os' due to: InterpreterError: Import of os
is not allowed. Authorized imports are: ['queue', 'random', 'time', 'itertools',
'collections', 'unicodedata', 'statistics', 'datetime', 'stat', 'math', 're']
answer: 225.86
```

The error does not crash the run. It is stored as the step's error in `agent.memory.steps`, shown to the model on the next call, and the model takes another path. The same interpreter also refuses built-ins it has not defined: while writing this article, a snippet using `repr()` failed with "Forbidden function evaluation: 'repr' is not among the explicitly allowed tools or defined/imported in the preceding code". Expect real models to hit such walls occasionally, and budget a step for it.

To allow more modules, pass `additional_authorized_imports=["pandas", "numpy"]`. The docs note that `"numpy.*"` authorizes a package and all its submodules.

### Layer 2: a remote sandbox

The docs are blunt: "no local python sandbox can ever be completely secure." They give examples: an innocent-looking module such as `random` can expose `random._os`, which the interpreter blocks at the submodule level, and an allowed image library could still be used to fill a disk. For untrusted inputs, the docs recommend remote execution with `executor_type="e2b"`, `"modal"`, `"docker"` or `"blaxel"`. Their Docker example drops all capabilities, sets a 512 MB memory limit and a process limit of 100, and runs as user `nobody`.

One limit matters for design: sandboxing only the code snippets "doesn't support multi-agents (managed agents)." To sandbox a manager with workers, the docs suggest running the whole agent system inside the sandbox, which may mean passing API keys into it. The [sandboxing](/tools/sandboxing) page covers the general trade-offs, and [prompt injection defense](/tools/prompt-injection-defense) explains why model-written code must be treated as untrusted even when the user is trusted.

## Final answer checks, step limits and managed agents

### Rejecting bad answers with final_answer_checks

`final_answer_checks` takes a list of functions. Each receives the final answer and the agent's memory (and, per the docs, the agent), and returns `True` to accept. A failed check becomes a step error, and the loop continues.

```python
def is_number(final_answer, memory, agent=None):
    """Reject answers that are not plain numbers."""
    return isinstance(final_answer, (int, float))

vague = '<code>\nfinal_answer("about 226 euros")\n</code>'
exact = '<code>\nfinal_answer(round(245.5 * fx_rate(base="USD", quote="EUR"), 2))\n</code>'
model = ScriptedModel([vague, exact])
agent = CodeAgent(tools=[fx_rate], model=model, verbosity_level=0, final_answer_checks=[is_number])
print("answer:", agent.run("Total of 245.5 USD in EUR, as a number?"), "| model calls:", len(model.calls))
```

```text
answer: 225.86 | model calls: 2
```

The first answer, "about 226 euros", failed the check and cost one extra model call. In 1.26 the error text the model sees is just "Check is_number failed with error:" with nothing after it, so the model is not told *why*. Put the reason in the check's name or docstring, or raise an exception with a message, so the model has something to act on.

### What happens at max_steps

`max_steps` defaults to 20. When the limit is hit, smolagents does not simply stop: it makes one more model call asking for a final answer from what it has.

```python
loop = ['<code>\nprint("thinking...")\n</code>'] * 3 + ["The total is roughly 226 EUR."]
model2 = ScriptedModel(loop)
agent2 = CodeAgent(tools=[fx_rate], model=model2, verbosity_level=0, max_steps=3)
print("max_steps answer:", agent2.run("Total of 245.5 USD in EUR?"), "| model calls:", len(model2.calls))
```

```text
Reached max steps.
max_steps answer: The total is roughly 226 EUR. | model calls: 4
```

So `max_steps=3` meant four model calls, and the answer came back as an unchecked guess. If you need to know whether the agent finished properly, run with `return_full_result=True`: the returned `RunResult` has a `state` field, which read `max_steps_error` for a run like this one, rather than trusting the string.

### Managed agents

Any agent with a `name` and `description` can be passed in `managed_agents`. The manager then calls it like a function. Here a `CodeAgent` manager delegates the rate lookup to a `ToolCallingAgent` worker:

```python
worker_model = ScriptedModel([[("fx_rate", {"base": "USD", "quote": "TRY"})],
                              [("final_answer", {"answer": "34.5"})]])
worker = ToolCallingAgent(tools=[fx_rate], model=worker_model, verbosity_level=0,
                          name="fx_agent", description="Looks up exchange rates. Give it a currency pair.")
manager_model = ScriptedModel(['''<code>
report = fx_agent(task="What is the USD to TRY rate? Reply with the number only.")
print(report)
rate = float(report.splitlines()[-1])     # the report wraps the worker's answer
final_answer(round(245.5 * rate, 2))
</code>'''])
manager = CodeAgent(tools=[], model=manager_model, managed_agents=[worker], verbosity_level=0)
print("manager answer:", manager.run("Total of 245.5 USD in TRY?"),
      "| manager calls:", len(manager_model.calls), "| worker calls:", len(worker_model.calls))
```

```text
manager answer: 8469.75 | manager calls: 1 | worker calls: 2
```

The manager's execution log shows why the `splitlines()` is there:

```text
Here is the final answer from your managed agent 'fx_agent':
34.5
```

My first version called `float(fx_agent(...))` directly and failed with "could not convert string to float". The worker's answer comes back wrapped in a report, not as a bare value. A real model would usually read the error and adapt, but it costs a step. The general pattern, and its alternatives such as handoffs, is covered under [sub-agents](/tools/sub-agents) and [multi-agent systems](/tools/multi-agent-systems).

## What it means in practice

smolagents is a good fit when tasks need several tool calls with logic between them: data lookups followed by arithmetic, filtering or loops. One code step replaces several round trips, and the measurement above shows that can cut both latency and total input, despite a larger system prompt. It is also small enough to read: the core agent logic lives in one `agents.py` file, which helps when you need to know exactly what is sent to the model.

The cost is execution risk. A JSON agent can only call the tools you defined, with arguments you can validate. A code agent runs a program. The local interpreter is a strong first layer, but the docs say plainly that it is not a full sandbox. For anything touching untrusted input, use a remote executor and give it minimal privileges.

Compared with graph frameworks such as [LangGraph](/tools/langgraph), smolagents has no built-in checkpointing or human interrupts; it is a loop, not a workflow engine. Teams often use it for self-contained research or data tasks, and put it behind a larger orchestrator when they need durability. The [Hugging Face](/tools/hugging-face) ecosystem integration, such as sharing agents and tools on the Hub, is a plus if you already live there.

## What to do now

1. **Pin the version.** Install `smolagents==1.26.0` and re-check the release notes before upgrading; the API is labelled experimental.
2. **Test with a scripted model.** Subclass `Model` as shown, replay realistic replies, and assert on answers, step errors and call counts.
3. **Measure prompt size, not just steps.** Record the messages sent per call and compare `CodeAgent` and `ToolCallingAgent` on your own tasks.
4. **Keep authorized imports minimal.** Add modules one at a time with `additional_authorized_imports`, and avoid broad patterns unless you need them.
5. **Use a remote executor for untrusted input.** Choose E2B, Modal, Docker or Blaxel, and apply the docs' Docker limits as a baseline.
6. **Write informative final answer checks.** Make the failure reason visible to the model, or it will guess what went wrong.
7. **Treat max_steps answers as unverified.** Use `return_full_result=True` and flag runs that ended at the limit.
8. **Parse managed agent reports explicitly.** Expect a wrapped report from workers, and tell the manager the format in its instructions.

## Risks and open questions

**The interpreter is not a security boundary.** The docs warn that "a determined attacker or a fine-tuned malicious LLM" may find vulnerabilities. Treat local execution as a convenience for trusted inputs.

**Remote sandboxes and managed agents do not mix easily.** Sandboxing only snippets does not support managed agents, and sandboxing the whole system may require putting API keys inside the sandbox.

**Release cadence is slow.** With no release since 29 May 2026, fixes for new model behaviours or provider APIs may lag. Check open issues for your model provider before committing.

**Code steps are harder to review.** A JSON tool call is easy to approve or deny. A code snippet with loops is not, which makes human approval of individual actions harder.

**Watch next:** whether a 1.27 release arrives with changes to executors or the experimental API label, and whether the CodeAct advantage holds on current agent benchmarks with today's models.

## Frequently asked questions

### What is the difference between CodeAgent and ToolCallingAgent?

`CodeAgent` asks the model to write a Python snippet that calls tools, which smolagents then executes. `ToolCallingAgent` uses the provider's JSON tool-calling API, one round of tool calls per step. Code agents often need fewer steps for multi-tool tasks, while JSON agents are easier to validate.

### Is the smolagents local executor safe?

It is safer than plain `exec`: it blocks unauthorized imports, undefined operations and very long loops. The docs say no local Python sandbox can be completely secure, so use a remote executor such as E2B, Modal, Docker or Blaxel for untrusted inputs.

### How do I test a smolagents agent without an API key?

Subclass `smolagents.models.Model` and implement `generate` to return pre-written `ChatMessage` objects, as in this article. Return text with a code block for `CodeAgent`, or `ChatMessageToolCall` objects for `ToolCallingAgent`.

### What happens when an agent reaches max_steps?

smolagents makes one extra model call asking for a final answer based on the memory so far. With `max_steps=3` that is four model calls, and the answer is not checked, so flag such runs.

### Can smolagents agents call other agents?

Yes. Give an agent a `name` and `description` and pass it in `managed_agents`. The manager calls it like a function and receives a report that wraps the worker's final answer.

## Summary

smolagents 1.26.0, released on 29 May 2026 and still current, implements code agents: the model writes Python that calls tools, and smolagents runs it. In a scripted, offline comparison, `CodeAgent` finished a two-rate currency task in one model call and 8,840 input characters, against three calls and 11,121 characters for `ToolCallingAgent`, despite a system prompt about 2.5 times larger. Its local interpreter blocked `import os` and `repr()` and fed the errors back for recovery, but the docs say only a remote executor gives robust isolation. Final answer checks, the extra call at `max_steps` and the wrapped reports from managed agents are the details that decide whether an agent built on it behaves predictably.

## Sources

- [Hugging Face: smolagents agents reference (v1.26.0)](https://huggingface.co/docs/smolagents/reference/agents)
- [Hugging Face: smolagents secure code execution](https://huggingface.co/docs/smolagents/tutorials/secure_code_execution)
- [PyPI: smolagents](https://pypi.org/project/smolagents/)
- [NewReleases: smolagents v1.26.0 changes](https://newreleases.io/project/github/huggingface/smolagents/release/v1.26.0)
- [GitHub: huggingface/smolagents](https://github.com/huggingface/smolagents)
- [arXiv: Executable Code Actions Elicit Better LLM Agents](https://arxiv.org/abs/2402.01030)
