We’re examining how Hugging Face’s smolagents keeps different agent behaviors inside one execution model. Smolagents is an agent framework where models can act through named tools or generated Python. Its agents.py file centers that design on MultiStepAgent, the class that owns a run from task intake to final answer.
The interesting question is not whether tool calls and code execution differ—they clearly do—but how they can differ without each acquiring its own lifecycle, memory rules, and stopping logic. I’m Mahmoud Zalt, an AI solutions architect, and we’ll trace the answer through the shared loop, the protocol its subclasses return, and the boundaries that determine whether that loop remains reliable under real workloads. The primary lesson is this: agent flexibility comes from a stable orchestration contract, not from giving every agent type its own loop.
One Lifecycle Owner
An agent is not a model call. It is a lifecycle: accept a task, plan when appropriate, request an action, record its result, notify callbacks, and either continue or stop. In agents.py, MultiStepAgent owns those invariants through run() and _run_stream().
The subclasses own only the action mechanism. ToolCallingAgent parses and dispatches named tool calls; CodeAgent sends generated Python to a configurable executor. Their key extension point is _step_stream(), while initialize_system_prompt() lets each establish its own prompt setup.
MultiStepAgent.run()
└── _run_stream()
├── optional _generate_planning_step()
└── _step_stream() [subclass hook]
├── ToolCallingAgent → tool dispatch
└── CodeAgent → Python executorThis is the Template Method pattern used for a practical reason: lifecycle fixes happen once. Memory updates, timing, planning intervals, maximum-step handling, callbacks, streaming, and final-answer construction do not need separate implementations for each agent kind. AgentMemory retains task, planning, action, observation, error, and final-answer records; callbacks observe finalized steps without taking ownership of the loop.
A Terminal Contract
A shared loop needs more than shared control flow: it needs a common result shape. The base class should not need to understand tool-argument validation, execution logs, or the details of a Python backend. It needs an output and an unambiguous declaration of whether execution is complete.
@dataclass
class ActionOutput:
output: Any
is_final_answer: bool
@dataclass
class ToolOutput:
id: str
output: Any
is_final_answer: bool
observation: str
tool_call: ToolCallActionOutput is intentionally smaller than either action mechanism. It lets MultiStepAgent decide whether to continue without coupling the loop to tool dispatch or code execution. That small contract is what makes a new agent type plausible: if it can implement _step_stream() and return the established records, it should not need to alter _run_stream().
ToolCallingAgent makes termination an invariant rather than a convention. Its setup ensures a final_answer tool exists through setdefault(), even when callers provide no tools. The surrounding validation rejects a final answer combined with another tool call, or multiple final answers in the same response. An agent cannot coherently say both “the task is done” and “perform more work.”
| Layer | Owns | Does not own |
|---|---|---|
MultiStepAgent | Lifecycle, memory, callbacks, termination | Tool and executor details |
ToolCallingAgent | Named-call parsing and dispatch | Overall run control |
CodeAgent | Generated-Python parsing and execution | Overall run control |
ActionOutput | Output and terminal status | Protocol-specific internals |
Make Boundaries Fail Explicitly
The same contract-first discipline applies where orchestration crosses trust boundaries. Prompts become model input, serialized configuration selects runtime behavior, and execution history may become durable data. The file is strongest where it makes those transitions explicit rather than silently permissive.
Prompt rendering uses Jinja’s StrictUndefined, so a missing variable fails during template rendering instead of becoming empty text. That matters because prompts are executable configuration in an agent system: a missing task variable or tool description can alter behavior while leaving the Python process apparently healthy. Early failure turns an opaque model-quality issue into a concrete configuration error.
Deserialization similarly uses an allowlist for agent classes through AGENT_REGISTRY, rather than importing an arbitrary requested class. Only approved agent types can be reconstructed by from_dict() and from_folder(). Loading tools remains an execution boundary, which is why from_hub() requires trust_remote_code=True; that flag is informed consent, not a sandbox.
Memory and logs deserve the same care. Tasks, additional_args, tool arguments, observations, generated code, and model messages can all reach replayable history or logs. In sensitive deployments, redact data before it crosses those boundaries—not after it has reached a provider or durable record.
Operating the Loop Under Load
A clean abstraction does not make costs disappear. Because model messages can be rebuilt from retained AgentMemory entries at every step, linear history growth over K steps can yield approximately O(K²) cumulative history-processing work. Model and tool latency may dominate wall-clock time, but growing history still increases prompt size, token spend, serialization work, and memory pressure.
max_steps bounds iterations, not the size of observations, logs, images, or messages accumulated by each iteration. The non-streaming path also materializes every event with list(self._run_stream(...)) just to inspect the final one. Since AgentMemory already holds the durable record, consuming the stream while retaining only its latest event reduces temporary event storage from O(S) to O(1).
Parallel tool calls introduce a separate operational contract. Concurrency can move wall-clock time toward the slowest tool rather than the sum of tool latencies, but it does not reduce aggregate CPU or service consumption. Workers also use shared logging and may write media results into self.state; the orchestration alone therefore does not establish thread safety. The file also applies no explicit per-tool, model, executor, future, or Hub timeout, so a hung dependency can delay a run indefinitely from this layer’s perspective.
The primary lesson holds even under these pressures: stable protocol boundaries make agent variation manageable, but the shared owner must also own—or explicitly delegate—resource limits and state coordination. Three practical consequences follow:
- Centralize lifecycle invariants. Add agent types through narrow action hooks, not parallel run loops.
- Make completion and failure typed. Preserve a small terminal contract and reject ambiguous final states early.
- Bound external work explicitly. Limit retained context, avoid unnecessary event materialization, define deadlines, and give shared state one writer.
As agent capabilities grow, the next useful evolution is not another bespoke orchestration path. It is a stronger shared loop: one whose protocol remains small, whose boundaries fail clearly, and whose runtime costs are visible enough to control.
