All Agent Engineering

Choosing an execution isolation for smolagents

Treat model-written Python as untrusted input, compare local interpreter and remote sandbox boundaries, then issue a selection record.

AINavWritten / Updated
On this page

At a glance

A smolagents CodeAgent runs model-written code in your environment by default, and the documentation calls this inherently risky. It names four routes by which harmful code arrives: plain model error, supply chain, prompt injection from a browsed page, and exploitation of an agent exposed to the public. This task does not chase absolute safety. It produces a reviewable record of where the code runs, what it can reach, and who cleans up afterwards. The docs also state that no solution is 100% safe, including the local Python executor.

Runtime and applicability

Article type
Engineering practice
Verified
Applies to
  • smolagents Choosing an execution isolation for smolagents

Execution locations and responsibilities

  • smolagents Python runtime Use the workflow below to distinguish responsibilities of the caller, runtime, and external actions.
Engineering workflow order
Engineering workflow order1. Step 1: Label the code's origin and trust level → 2. Step 2: Derive the imports that must be authorized → 3. Step 3: Estimate operation count and resource budget → 4. Step 4: Choose between the two sandbox approaches → 5. Step 5: Write the minimized permission and network config → 6. Step 6: Fix cleanup and failure handling → 7. Step 7: Sign the record and leave review points. Arrows show the order of checks in the guide. Follow each step’s prerequisites, branches and stop conditions; unexecuted steps are not completed work.1. Step 1: Label the code's origin and trust level2. Step 2: Derive the imports that must be authorized3. Step 3: Estimate operation count and resource budget4. Step 4: Choose between the two sandbox approaches5. Step 5: Write the minimized permission and networkconfig6. Step 6: Fix cleanup and failure handling7. Step 7: Sign the record and leave review points

Arrows show the order of checks in the guide. Follow each step’s prerequisites, branches and stop conditions; unexecuted steps are not completed work.

When to use

  • Establish the real execution point first. By default CodeAgent runs LLM-generated code in your environment, and execution is not handed to the vanilla Python interpreter but to a rebuilt LocalPythonExecutor that loads the abstract syntax tree and executes it operation by operation. The stated rules: imports are disallowed unless explicitly added to an authorization list; submodules are disabled by default and must each be authorized, though passing something like numpy.* opens a package and all its subpackages; the total count of elementary operations is capped to stop infinite loops and resource bloating; any operation not explicitly defined in the custom interpreter raises an error. Mapping these rules onto your task shows which imports need authorization and what surface each authorization opens.

When not to use

  • Not for treating the local interpreter as strong isolation: the docs state no local Python sandbox can ever be completely secure and that robust isolation needs remote execution options such as E2B or Docker.
  • A multi-agent requirement changes the answer: approach one is documented as not supporting managed agents, so the whole-system-in-sandbox route or a custom interpreter is required.
  • Do not read the four executor_type values as equivalent: the docs list them as options without comparing their security levels, so selection must come from your own permission needs.

Prerequisites and input

  • A real task sample the CodeAgent will run, plus the shape of code it tends to emit (imports, loops, file writes).
  • A host resource profile: writable paths, outbound network needs, available memory and CPU ceilings.
  • Someone accountable for the permission call, able to sign off on which code may stay local.

Engineering checks

Layer 1: Where the code runs, and the interpreter's rules — Establish the real execution point first. By default CodeAgent runs LLM-generated code in your environment, and execution is not handed to the vanilla Python interpreter but to a rebuilt LocalPythonExecutor that loads the abstract syntax tree and executes it operation by operation. The stated rules: imports are disallowed unless explicitly added to an authorization list; submodules are disabled by default and must each be authorized, though passing something like numpy.* opens a package and all its subpackages; the total count of elementary operations is capped to stop infinite loops and resource bloating; any operation not explicitly defined in the custom interpreter raises an error. Mapping these rules onto your task shows which imports need authorization and what surface each authorization opens.

Layer 2: What each sandbox approach moves inside — The docs describe two approaches, and the difference is what gets moved into the sandbox. Approach one executes only the agent-generated snippets in the sandbox while the rest of the agentic system stays local, reachable by setting executor_type to blaxel, e2b, modal or docker; it is simpler, keeps API keys out of the sandbox, but does not support multi-agents and still passes state between your environment and the sandbox. Approach two runs the entire agentic system, model and tools included, inside the sandbox: better isolation and multi-agent support, but more manual setup, possibly sending sensitive credentials such as API keys into the sandbox, and potentially higher latency. The record must name the chosen approach and what it gives up.

Layer 3: What the local interpreter still allows — Even with LocalPythonExecutor the risk is not zero. The documentation's example: authorize an image library like Pillow and the model can generate code creating thousands of large image files to fill your hard drive, and other escape techniques may exploit deeper vulnerabilities in authorized packages. So this layer assesses not whether a sandbox exists but what the authorized capability set can do at worst. Whenever the task requires file reads or writes, network calls, or processing untrusted binaries through an authorized package, the conclusion should move from the local interpreter to remote execution.This guide’s design policy prioritizes assessment of remote sandboxing for file reads or writes, network calls or untrusted binaries through authorized packages; this threshold is not a universal documentation requirement.

1. Step 1: Label the code's origin and trust level

Where: host trust assessment. Input: code, model/inference provenance, external pages and public inputs. Record evidence for model errors, supply-chain risks, prompt injection and public inputs. Unknown provenance excludes local execution but still proceeds through steps 2 and 3 to assess imports, resources and credentials before choosing a sandbox in step 4. Completion: trust decisions and unknowns are evidenced without skipped intermediate assessments. Stop execution if no acceptable route exists; do not fall back to unreviewed local execution.

2. Step 2: Derive the imports that must be authorized

Where: the CodeAgent import authorization list. Input: every import and submodule access in the task sample. Action: decide each one; for packages that are genuinely needed, note whether a wildcard form such as numpy.* is used to open subpackages and what capability that adds — the docs show that even an innocuous-looking package like random can reach something like random._os, which is refused. Completion check: each entry answers why it is required and what new capability it grants. Stop condition: any entry needing os, system calls, or arbitrary file writes ends the local route.

3. Step 3: Estimate operation count and resource budget

Where: the interpreter cap and host quotas. Input: the task's loop structure and data volume. Action: judge whether the elementary-operation cap is too tight or too loose for this task, and reason through worst-case file, memory and CPU consumption; the docs recommend memory and CPU limits, execution timeouts, and resource monitoring on the sandbox side. Completion check: the operation cap, timeout and resource ceilings each have a stated basis. Stop condition: long-running work or heavy disk writes rule out the local interpreter.

4. Step 4: Choose between the two sandbox approaches

Where: the decision sheet and initialization. Input: the import, provenance and resource assessments. First choose local or sandbox. Use local only when the assessment accepts host residual risks and resources are controllable; record host limits and mark sandbox-only parameters not applicable. This is a local decision rule, not a safety certification. For isolation choose snippet-only or whole-system sandboxing: assess blaxel/e2b/modal/docker executor_type for snippets, and a whole system or custom interpreter for managed agents. Completion: record the single chosen branch, permission owners and tradeoffs. Stop with an undecided outcome when no option meets resource and credential requirements instead of falling back to unknown local risks.

5. Step 5: Write the minimized permission and network config

Where: the chosen runtime configuration. Input: local/sandbox branch and dependencies. For local record authorized imports and ownership of host files, networking, CPU and memory; the interpreter operation cap is not an OS resource limit, and sandbox-container parameters are not applicable. For sandbox implement actual-service least privilege, necessary networking, environment-variable credentials, pinned dependencies and image maintenance. The Docker example’s memory, CPU, process, no-new-privileges and capability controls apply only to its container branch. Completion: each configuration matches the selected branch without invented local container limits. Stop to reconsider the executor when required limits cannot be implemented or capabilities reduced, retaining residual risks.

6. Step 6: Fix cleanup and failure handling

Where: lifecycle management for the chosen branch. Input: the runtime and owned resources. In local mode the host application releases the handles, temporary resources and external connections it owns; it does not need nonexistent container cleanup. For supported CodeAgent remote executors use with or cleanup(); for a whole-system custom sandbox clean up the container/session you actually created. Completion: normal, error and timeout paths have applicable owners, with sandbox-only items not applicable to local mode. Stop with unconfirmed cleanup if underlying release is unknown rather than treating a method name as a guarantee covering all resources.

7. Step 7: Sign the record and leave review points

Where: the delivered document. Input: the preceding six steps. Action: consolidate into seven columns — task, code origin, execution point, authorized capabilities, resource ceilings, cleanup, residual risk — each with a conclusion and its basis. Completion check: someone reading only this record could reproduce the same configuration and could point out which conclusions are expectations rather than observed results. Stop condition: any required column left empty blocks signing.

Task example

Unexecuted walkthrough: a CSV summary needs assessed numeric dependencies and no networking. If the resource inventory and residual host risks are accepted, choose local at step 4. Step 5 records host limits with container parameters not applicable; step 6 assigns cleanup of host-owned resources, and step 7 delivers the decision sheet with execution still unverified. If the task adds external-image downloads and compression, reassess imports, networking and disk risk and choose a sandbox with service, permissions, resources and cleanup requirements. If snippet execution cannot support required managed agents, assess a whole-system route. No actual account, credential or result is supplied.

Completion checks

  • Every authorized import carries both "why required" and "what capability it adds".
  • The execution point names exactly one real runtime — the host interpreter or a specific sandbox — with no ambiguous partial split.
  • Record applicable resource limits and evidence by branch; local mode does not invent container CPU/process limits, and interpreter-operation limits stay separate from host-resource limits.
  • Cleanup is described for normal completion, exceptions and timeouts.
  • Residual risk has its own column and contains no claim of complete isolation, which the docs contradict.

Verification scope

Based on the smolagents "Secure code execution" tutorial page. The documentation was read; smolagents was not installed, no sandbox account was signed into, no container was created, and no generated code was executed, so configurations and expected observations here are inferences from the docs, not test results.

Sources

All links are official pages; verification dates are listed per source, and links point to the version checked.

  1. smolagents · smolagents documentation: hf-secure

Found an error? Tell us →