How to Run AI-Generated Code Safely with the E2B Sandbox

November 9, 2026

E2B is a cloud sandbox for AI agents: each session is a Firecracker microVM that boots in under 200 milliseconds, runs the code your model wrote, and disappears when you are done.

That is the short answer. The longer version is that E2B solves a problem most agent builders hit within a week: the model writes Python, you need to execute it, and executing it on your own server means one bad import os plus shutil.rmtree and your filesystem is gone.

This guide sets up E2B from a blank folder to a working sandbox call, then covers the settings that actually matter in production. Last updated November 2026, against the current e2b-code-interpreter Python SDK.

What problem does E2B actually solve?

The gap between “the model wrote code” and “the code ran” is where agents go wrong. Without a sandbox you have three bad options: run it locally (dangerous), run it in a container you babysit (slow to start, still shared), or skip execution and hope the code was right (useless).

E2B sits in the middle. You get a Linux machine on demand, with an SDK that is roughly ten lines of Python. The microVM is isolated at the kernel level with Firecracker, the same virtualization layer AWS Lambda uses, so a runaway process inside cannot see your host.

Who this is for: teams building coding agents, data-analysis chat products, or anything that lets a user (or a model) execute untrusted code. Who it is not for: single-user scripts you run yourself, or workloads that need a persistent multi-day server with a GPU. E2B sessions are meant to be short-lived, and GPU sandboxes cost extra.

How do you get an API key and install the SDK?

Sign up at e2b.dev, open the dashboard, and copy the API key from the Team settings page. The free Hobby tier gives you $100 of one-time credit and runs sandboxes on 2 vCPU / 512 MB by default.

Install the SDK:

pip install e2b-code-interpreter

Then export the key. Do not hardcode it, because the SDK reads this variable automatically:

export E2B_API_KEY="e2b_..."

Pin the SDK version in requirements.txt. The Python SDK moved from e2b to e2b-code-interpreter when code execution was split out, and old tutorials that still call Sandbox() from the bare e2b package will throw import errors.

How do you run your first piece of generated code?

The minimum working script creates a sandbox, runs Python, and kills the sandbox. Save this as run.py:

from e2b_code_interpreter import Sandbox

with Sandbox.create() as sbx:
    result = sbx.run_code("print(sum(range(10)))")
    print(result.logs.stdout)
    print(result.error)

Sandbox.create() blocks for roughly 150–200 ms on a warm node. The with block guarantees the VM is destroyed even if your code raises, which matters more than it sounds: leaked sandboxes keep billing until they hit the default 5-minute timeout.

Run it. You should see 45 printed from inside the sandbox, and None for the error field.

Why does the sandbox need to outlive a single call?

Because most agent tasks are multi-step. A model that loads a CSV, computes a summary, then plots it needs the file to persist across calls. E2B keeps the filesystem alive for the life of the sandbox, so state carries naturally between run_code calls.

How do you pass real data into the sandbox?

Two ways, and the choice matters. For small inputs, write a file directly:

sbx.filesystem.write("/home/user/data.csv", csv_text)

For anything over a few megabytes, upload the file with sbx.filesystem.write on a bytes object, or mount data through the dashboard’s storage API. Chunked uploads above 50 MB will time out on the default connection if you do not use the streamed write path.

A common mistake is dumping the dataset into the run_code string as a Python literal. That works for 100 rows and breaks at 100,000. Write the file, then let the model reference the path.

How do you control what the code is allowed to touch?

This is the part most tutorials skip, and it is the part that keeps you out of trouble. E2B sandboxes have no access to your machine, but they do have outbound internet by default.

  • Block the network when the task does not need it. Set allow_internet_access=False in the sandbox config. Fetched data from an untrusted model is a prompt-injection vector, not just a security hole.
  • Cap the timeout. The default is 300 seconds. Most analysis tasks finish in 20. Set timeout=60 and handle the timeout error explicitly.
  • Watch memory. The default 512 MB is fine for pandas on a few thousand rows and dies on a 500 MB parquet file. Bump to 2 GB or more for data work; each step up in resources costs proportionally.
  • Do not install packages at runtime on every run. Installing pandas and matplotlib adds 15–30 seconds per cold start. Build a custom sandbox template that already has them.

How do you make repeated runs fast with a custom template?

The stock template has Python but not much else. A custom template is a Dockerfile that E2B builds ahead of time, so packages are pre-baked.

Create e2b.Dockerfile:

FROM e2bdev/code-interpreter:latest
RUN pip install pandas==2.2.3 matplotlib==3.9.2 scipy==1.14.1

Then build and reference it with Sandbox.create("my-analyst"). First build takes a couple of minutes; after that, every cold start restores the template snapshot and lands near 300 ms instead of 30 seconds.

What does it cost, and where do costs run away?

E2B bills by vCPU-second and GiB-second while a sandbox is running. On the Pro plan, 2 vCPU / 1 GiB works out to well under a cent per 30-second run, so a thousand daily runs is a few dollars, not a few hundred.

The cost trap is idle sandboxes. An agent that creates a sandbox, runs one check, then waits for a user’s next message holds the VM open the whole time. Either kill it after each turn, or use the 300-second default timeout as a hard ceiling and accept the cold start on the next message.

Quick Summary

  • E2B runs AI-written code inside isolated Firecracker microVMs that start in under 200 ms and are billed per vCPU-second.
  • Install with pip install e2b-code-interpreter and set E2B_API_KEY; the older e2b package alone no longer runs code.
  • Use with Sandbox.create() so the VM is destroyed on exceptions, and set timeout=60 rather than relying on the 5-minute default.
  • Turn off internet access unless the task needs it, and pre-bake packages into a custom template instead of installing at runtime.
  • The Hobby tier includes $100 of one-time credit; idle sandboxes, not compute, are what inflate the bill.
Tags: