Running LLM-Generated Code Safely in an E2B Sandbox
The moment your app asks a model to write code and then runs it, you've handed a stranger a shell. The model usually means well. But it can import something you didn't expect, write to disk, loop forever, or follow instructions hidden in a document a user uploaded. Running that with exec() in your web server's process is the wrong place for it.
E2B gives you a disposable cloud sandbox per session: you create one, send it code, read back the output, and kill it. This post walks through doing that from Python and from TypeScript, with the timeouts and cleanup that keep the bill and the blast radius small. Code comes from the E2B docs as of November 2026.
Pick the right package
E2B ships two SDKs, and it's easy to install the wrong one. The docs home lists both:
| You want to | Python | TypeScript |
|---|---|---|
| Run shell commands, manage files | pip install e2b | npm i e2b |
| Run code cells with kept state and rich results | pip install e2b-code-interpreter | npm i @e2b/code-interpreter |
For LLM-generated code you almost always want the Code Interpreter SDK. It adds run_code() (runCode() in JS), which runs code in a session that keeps variables between calls and returns results such as charts, much like a notebook. The base SDK gives you sandbox.commands.run(...) for shell commands.
Both read your key from the E2B_API_KEY environment variable.
The minimal round trip
Here's the quickstart in Python:
from dotenv import load_dotenv
load_dotenv()
from e2b_code_interpreter import Sandbox
sbx = Sandbox.create()
execution = sbx.run_code("print('Hello from E2B Sandbox!')")
print(execution.logs)
files = sbx.files.list("/")
print(files)
sbx.kill()
And the same in TypeScript:
import 'dotenv/config'
import { Sandbox } from '@e2b/code-interpreter'
const sbx = await Sandbox.create()
const execution = await sbx.runCode('print("Hello from E2B Sandbox!")')
console.log(execution.logs)
const files = await sbx.files.list('/')
console.log(files)
await sbx.kill()
Note what the TypeScript version runs: Python. The code you send goes to the interpreter inside the sandbox, not to Node, so your backend language and the generated code's language are independent.
The comment in the docs on kill() is the line to remember: without it the sandbox keeps running until its timeout, which is 5 minutes by default.
Wire it to a model
Now the actual task. Ask a model for code, run it, and hand the output back. I'll use the OpenAI Python SDK here because most readers have it; any provider works, since the sandbox doesn't care where the string came from.
import os
from openai import OpenAI
from e2b_code_interpreter import Sandbox
client = OpenAI()
SYSTEM = (
"You write Python to answer data questions. "
"Reply with only a Python code block, no prose."
)
def extract_code(text: str) -> str:
if "```" not in text:
return text
body = text.split("```", 2)[1]
return body.removeprefix("python").strip()
def answer(question: str) -> str:
reply = client.chat.completions.create(
model=os.environ["MODEL"],
messages=[
{"role": "system", "content": SYSTEM},
{"role": "user", "content": question},
],
)
code = extract_code(reply.choices[0].message.content)
sbx = Sandbox.create(timeout=60)
try:
execution = sbx.run_code(code)
return str(execution.logs)
finally:
sbx.kill()
Three choices in there are deliberate.
timeout=60. The sandbox lifecycle page shows that Python's timeout is in seconds and the JS option timeoutMs is in milliseconds. That unit mismatch is the easiest bug to ship: timeoutMs: 60 in TypeScript is sixty milliseconds. For a one-shot answer, a short timeout means a runaway loop costs you a minute at most.
try/finally with kill(). If the model's code raises, or your own code does, the sandbox still goes away. Don't rely on the timeout as cleanup.
One sandbox per request. For a stateless "answer this question" endpoint that's the simplest safe default. Nothing one user's code leaves behind is visible to the next request.
The TypeScript equivalent of the creation line:
const sbx = await Sandbox.create({ timeoutMs: 60_000 })
try {
const execution = await sbx.runCode(code)
console.log(execution.logs)
} finally {
await sbx.kill()
}
When you want state across turns
A data-analysis chat is different: the user uploads a CSV, the model loads it into a dataframe, and three questions later it still needs that dataframe. That's where the Code Interpreter's kept state earns its place. Keep one sandbox per conversation, call run_code() for each turn, and extend its life as the user keeps talking.
The lifecycle page shows set_timeout(30) in Python and setTimeout(30_000) in JS. The new value counts from now, so calling it on each turn works like a sliding idle window. The same page gives hard ceilings: sandboxes can run continuously for up to 24 hours on Pro or 1 hour on Hobby, as of November 2026. For longer work, the docs recommend pause and resume, since pausing resets the runtime window.
Store the sandbox ID next to your conversation record, and kill it when the conversation ends or the user leaves. A sandbox you forgot about is still a sandbox you pay for until its timeout.
What the sandbox does and doesn't protect
A sandbox moves the risk; it doesn't remove it. Things it handles: the generated code can't touch your server's filesystem, environment variables or process memory, and a crash or infinite loop stays inside the VM until the timeout.
Things you still own:
- Secrets you pass in. If you upload a file or set credentials inside the sandbox so the code can reach a database, the model's code can read them too. Give it the narrowest credential possible, or none.
- What you do with the output. The output is untrusted text. Don't render it as HTML unescaped, don't feed it into another shell, and treat any instructions in it as data.
- Network egress. Generated code may try to call out. Check the current E2B docs for network controls before you rely on any particular setting; I'm not going to describe one I didn't verify.
- Cost. Every request that creates a sandbox is billable compute. Rate-limit the endpoint like any other expensive one.
Our post on running AI coding agents safely covers the same trade-offs from the coding-agent side: permission modes, containers and egress rules. And if you're choosing a model to generate the code in the first place, LLM API pricing compared and the OpenAI API page are good starting points.
Debugging the loop
When the answer comes back empty, look at the pieces in order:
- Print the raw model reply before you extract code. Models wrap code in prose or extra fences more often than you'd like, and
extract_codeabove is deliberately simple. - Check
execution.logs. Print statements land there, so a script that computes a value but never prints it returns nothing useful. - Check whether the timeout fired. A data load that takes longer than your
timeoutlooks like silence. - Run the same code locally in a throwaway environment to see whether the bug is the code or the plumbing.
A good next step is to feed errors back to the model: if the run fails, send the traceback in the next message and ask for a fix, with a cap of two or three attempts. That loop, model writes, sandbox runs, model reads the error, is the core of most code-interpreter features, and the sandbox is what makes it reasonable to run unattended.
Written by AIDToolStack Editorial
Researched from official documentation, specifications and vendor pages, listed under Sources below. Last checked November 2026.