Sandbox Execution

Run code where it can't escape.

Model-generated or agent-selected code runs in an isolated environment — a container, a microVM (e.g. Firecracker), or a hosted code sandbox — with no access to the host filesystem, network, or credentials beyond what the task explicitly needs.

In practiceA data-analysis agent executes user-supplied Python snippets inside a gVisor container, so a malicious script cannot read the host filesystem.

Without itWithout a sandbox, model-generated code runs with the agent's full host permissions, turning a prompt-injection into an arbitrary code execution path. See the anti-pattern →

Level
04 · Production
Subdomain
Governance & Safety
Also known as
Isolated Execution, Code Sandbox, Secure Runtime
Trade-off
Secure execution is achieved against infrastructure and performance overhead.
Native in
OpenAI Agents SDK, AutoGen / AG2, Microsoft Agent Framework, LangGraph
The mechanism

How it works.

Code the model wrote runs in a separate, disposable environment. It gets the files the task needs and nothing else: no host filesystem, no credentials, and no network unless that is allowed explicitly.

1 · Prepare

  1. Start a fresh environmentA container or a microVM per run
  2. Copy in the inputsOnly the files of this task
  3. Set the limitsTime, memory, network off

2 · Run

  1. Execute the codeInside the environment
  2. Capture the outputPrinted text, files, exit code
  3. Destroy the environmentNothing survives the run
  4. Return the resultThe output goes back to the agent
Isolation boundary
What separates the code from the host. A container shares the host's kernel; a microVM brings its own.
Resource limits
Caps on time, memory and processes. They stop an endless loop as well as an attack.
Egress control
Whether the code may open network connections. Off by default; a list of allowed hosts when it has to be on.
Walk it through

A real run, step by step.

TaskA data-analysis agent runs four snippets in a sandbox with no network and a time limit of 30 seconds:
Illustrative run.
Code tries toIn the sandboxResult
Read the uploaded CSV and compute a meanThe file was copied inWorks
Read the SSH keys of the hostThat path does not exist hereFile not found
Send the data to an external serverThe network is offConnection refused
Loop foreverThe time limit appliesKilled after 30 seconds
What this shows: none of the three bad snippets was caught by reading the code first. The environment made them harmless. The same holds for honest mistakes, such as the endless loop. The price is the start-up time of an environment per run, the infrastructure behind it, and extra work for every task that really does need a package or a network address.
In code

The pattern in code.

Plain Pythonpython
import shutil, subprocess, tempfile

def run_in_sandbox(code: str, input_files: list[str], timeout=30):
    workdir = tempfile.mkdtemp()  # a fresh directory per run
    for path in input_files:
        shutil.copy(path, workdir)  # only the inputs of this task
    open(f"{workdir}/main.py", "w").write(code)
    try:
        done = subprocess.run(
            ["docker", "run", "--rm",
             "--network", "none",  # no outbound connections
             "--memory", "512m", "--cpus", "1", "--read-only",
             "-v", f"{workdir}:/work", "-w", "/work",
             "python:3.13-slim", "python", "main.py"],
            capture_output=True, text=True, timeout=timeout)
        return done.stdout or done.stderr
    except subprocess.TimeoutExpired:
        return "Killed: time limit reached"
    finally:
        shutil.rmtree(workdir)  # nothing survives the run
Fit

Use it, or not.

When to reach for it

  • Agents execute code, shell commands, or browser actions.
  • Untrusted inputs are processed.
  • Side effects must be contained.

When it backfires

  • No dynamic execution occurs.
  • Sandbox escapes cannot be controlled.
  • External actions are better handled via verified tools.
Pitfalls

Two ways this pattern will hurt you.

Sandbox escapes via side-channel tool calls

The sandbox blocks file access, but the generated code uses a web-request tool to exfiltrate data.

Countermeasure

Audit the tool set available inside the sandbox. Remove network-facing tools unless explicitly required and monitored.

Resource exhaustion

A runaway loop inside the sandbox consumes all CPU or memory. The host process degrades or crashes.

Countermeasure

Enforce cgroup limits on CPU, memory, and wall-clock time. Kill the sandbox when any limit is exceeded.

EU law

Regulation

Duties from EU law that this pattern helps meet, or that land on it. A reading aid, not legal advice.

  • EU AI Act Art. 15An appropriate level of accuracy, robustness and cybersecurity, held consistently over the lifecycle.Providers of high-risk systems · from 2 Dec 2027 (Annex III) or 2 Aug 2028 (Annex I products)
  • GDPR Art. 32Security appropriate to the risk, including pseudonymisation and encryption.Controllers and processors · since 25 May 2018
  • GDPR Art. 35Before processing that is likely to result in a high risk, in particular with new technologies, the controller assesses its impact on the protection of personal data.Controllers · since 25 May 2018Explained on the DPIA page

An engineer's reading aid, not legal advice. The legal texts and their interpretation are authoritative.

Framework support

Where Sandbox Execution is native.

OpenAI Agents SDKCode InterpreterNative
AutoGen / AG2Docker code executorNative
Microsoft Agent Frameworkhosted code interpreterNative
LangGraphsandboxed tool nodeNative

Search

Search patterns, frameworks, and pages.