Code interpreter API: 7 ways to let an LLM run code safely
A code interpreter API lets a language model write code, run it on an isolated machine and read the result back. There are two kinds. The built-in tools from model providers (OpenAI Code Interpreter, Claude code execution, Gemini code execution) take one line in the request and fit short Python analysis on preinstalled libraries. Sandbox APIs (Amazon Bedrock AgentCore Code Interpreter, E2B, Modal, Lizard) work with any model and fit jobs that need your own packages, network access, other languages or more than a few minutes.
I work on Lizard, so weigh the comparison with that in mind. On Lizard the sandbox API is the interpreter template: lizard sandbox create -t interpreter -s small starts a Firecracker microVM with Python 3.11, pandas and matplotlib for $0.0162 an hour, billed per second. I ran every Lizard command in this article on 22 November 2026 and printed the output below. The other six are described from their vendors' documentation, read the same day.
What is a code interpreter API?
A code interpreter API is a hosted service that runs code written by a language model and returns the output: printed text, the value of the last expression, files and charts. The code runs in a container or a virtual machine away from your servers. Most of these APIs keep the Python process alive between calls, so a variable set in one call is still there in the next.
How do the 7 code interpreter APIs compare?
The three built-in tools are cheaper to wire up and stricter on limits; the four sandbox APIs give you a machine you configure and bill for its time. Every limit and price in the table was read from the linked vendor page on 22 November 2026.
| Option | Languages | Internet | Session limit | Packages | Price of the machine | Source |
|---|---|---|---|---|---|---|
| OpenAI Code Interpreter | Python | Off by default; domain allowlist per container | Container expires after 20 minutes without use | Preinstalled | $0.03 per container per 20-minute session at 1 GB; $0.12 at 4 GB | guide, pricing |
| Claude code execution tool | Python 3.11, Bash | None | Container kept for 30 days; 1 CPU, 5 GiB RAM | Preinstalled only | 1,550 hours a month at no charge, then $0.05 per container-hour | docs |
| Gemini code execution | Python | Not stated | 30 seconds per run | Fixed list, no installs | No charge beyond tokens | docs |
| AgentCore Code Interpreter | Python, JavaScript, TypeScript | Three modes: Sandbox (AWS services only), Public, VPC | 15 minutes by default, up to 8 hours | Preinstalled for Python and Node.js | $0.0895 per vCPU-hour and $0.00945 per GB-hour, on what the session consumes | docs, pricing |
| E2B Code Interpreter | Python, JavaScript, TypeScript, R, Java, Bash | On by default; allow and deny lists | 1 hour on Hobby, 24 hours on Pro | pip at runtime or a custom template | $0.000014 per vCPU-second and $0.0000045 per GiB-second | docs, pricing |
| Modal Sandboxes | Anything in your container image | On by default; full block or allowlists | 5 minutes by default, up to 24 hours | Your own image | $0.00003942 per physical core-second (1 core = 2 vCPU) and $0.00000667 per GiB-second | docs, pricing |
Lizard interpreter template | Python with kept state; JavaScript and Bash per call | On by default; --no-internet or --allow-host | 5 minutes by default, up to 596 hours on a paid plan, 1 hour on the trial | pip at runtime | $0.0162 an hour for Small (2 vCPU, 4 GB), $0.0081 for Mini | docs, pricing |
OpenAI's guide says a container is "a fully sandboxed virtual machine" with 1, 4, 16 or 64 GB of memory. Its shell guide says hosted containers have no outbound network until an admin sets an organization allow list and the request sets a network_policy. Modal has no interpreter protocol of its own: its code interpreter example has you write a small driver program that reads code from stdin. AgentCore's docs give file limits that the others leave out: up to 100 MB inline and up to 5 GB through Amazon S3.
When is a model's built-in code interpreter enough?
A built-in code interpreter is enough when the job is short Python on common libraries and you already use that provider's model. You add one entry to tools and the provider runs the loop: the model writes code, the provider executes it and the model reads the output, all inside one API call.
{ "type": "code_interpreter", "container": { "type": "auto" } }
{ "type": "code_execution_20260521", "name": "code_execution" }
{ "type": "code_execution" }Those are the tool entries for OpenAI, Claude and Gemini, copied from each vendor's documentation. The limits decide whether one fits. Gemini stops each run at 30 seconds and its docs say "You can't install your own libraries." Claude's container has no internet access, 1 CPU and 5 GiB of RAM, so a package missing from the preinstalled list cannot be added. OpenAI discards a container after 20 minutes without use, and its guide recommends storing anything you need on your own systems.
For a chat feature that totals a CSV or draws a chart, these limits rarely matter and the price is low. Gemini charges nothing beyond tokens. Anthropic's pricing page gives each organization 1,550 hours of code execution a month at no charge, and charges nothing for it in requests that also include the web_search_20260209 or web_fetch_20260209 tool or a later version.
When do you need your own sandbox for LLM code?
You need your own sandbox when the model's code has to do something the built-in container forbids. I count five cases.
- The code needs a package outside the preinstalled set, such as a private wheel. E2B and Lizard let you run
pip installin a running sandbox, and E2B and Modal build custom images. - The code calls your API, a database or a public dataset. Claude's container has no network at all, and OpenAI's needs an organization allow list plus a network policy in each request.
- The job outlasts the limit: 30 seconds on Gemini, 8 hours on AgentCore, 24 hours on E2B Pro and Modal. Lizard runs a sandbox for up to 596 hours on a paid plan; on the 7-day trial every sandbox is deleted after 1 hour at the latest.
- The model writes something other than Python. AgentCore covers JavaScript and TypeScript, E2B adds R and Java, and Modal runs whatever is in your image.
- You want one execution layer under several models, or under an open-weight model that has no built-in tool. A sandbox API takes code as a string, whichever model wrote it.
With a sandbox API you also pick the machine size and the library versions, and the same machine can hold a git checkout or a test database next to the interpreter. I cover the wider category in what an AI sandbox is. You pay for that control with more code on your side: you define a run_python tool, pass each tool call to the sandbox and send the output back to the model.
How do you run LLM-generated Python in a sandbox?
You create a sandbox, pass the model's code to it as a string, and return the output to the model as the tool result. Here is the whole path on Lizard, first from the terminal. The task: load a CSV, draw a chart, get the PNG back.
lizard sandbox create -t interpreter -s small --timeout 10m --json
lizard sandbox files put <id> sales.csv /workspace/sales.csv
lizard sandbox files put <id> chart.py /workspace/chart.py
lizard sandbox exec <id> -- python3 /workspace/chart.py
lizard sandbox files get <id> /workspace/chart.png chart.png
lizard sandbox rm <id><id> is the id that create prints. In my run the create call returned in 1.9 seconds with "size": "small", "cpus": 2, "memoryMb": 4096 and "pricePerHour": 0.0162. chart.py reads a six-row CSV of monthly revenue with pandas and saves a bar chart with matplotlib. It printed:
rows=6 total=85450 growth=36.9%files get then downloaded a 25 KB PNG. The template had Python 3.11.17, pandas 3.0.6, NumPy 2.4.6, matplotlib 3.11.2 and Node 22 installed. Pass -s small explicitly: outside the trial a create with no size starts a Medium sandbox at $0.0324 an hour.
In an application you use Lizard SDK instead, because its CodeSandbox class keeps a Jupyter kernel running between calls. This is the script I ran with @lizard-build/sdk on Node 22, with LIZARD_API_KEY set. The Python strings stand in for what a model would send as the code argument of your tool.
import { readFileSync, writeFileSync } from 'node:fs'
import { CodeSandbox } from '@lizard-build/sdk'
const sandbox = await CodeSandbox.create({ project: 'my-project', size: 'small', timeoutMs: 300_000 })
try {
await sandbox.fs.write('/workspace/sales.csv', readFileSync('sales.csv', 'utf8'))
const first = await sandbox.runCode(`
import pandas as pd
df = pd.read_csv("/workspace/sales.csv")
print(len(df), "rows, total", df.revenue.sum())
`)
console.log(first.stdout.trim())
// Second call: df is still in memory
const second = await sandbox.runCode(`
import matplotlib.pyplot as plt
df.plot(x="month", y="revenue", kind="bar", legend=False)
plt.show()
`)
const png = second.results.find((r) => r.mime === 'image/png')
writeFileSync('chart.png', Buffer.from(png.data, 'base64'))
const bad = await sandbox.runCode('df.revenu.sum()')
console.log(bad.error?.name, '-', bad.error?.message)
} finally {
await sandbox.kill()
}6 rows, total 85450
AttributeError - 'DataFrame' object has no attribute 'revenu'The chart arrived as base64 in results. The typo came back as an error object with a name and a message, and my own process raised nothing. That matters for an agent: you send the error text to the model and it fixes its own code. A 5-second sleep with a 2-second timeoutMs returned TimeoutError, and df was still in memory on the next call. The Python SDK (lizard-sdk) has the same class with run_code; I did not run that version. The full reference is in the Lizard code interpreter docs.
E2B's SDK also returns the chart as base64 in a list of results. Here is the same step from its documentation (I did not run this one):
import base64
from e2b_code_interpreter import Sandbox
sandbox = Sandbox.create()
execution = sandbox.run_code(code_to_run)
first_result = execution.results[0]
if first_result.png:
with open('chart.png', 'wb') as f:
f.write(base64.b64decode(first_result.png))How do you keep a code interpreter safe?
Treat every line the model writes as untrusted and control four things: isolation, network, time and secrets.
Isolation comes first: the code must run on a machine that is not yours. Lizard Sandboxes are Firecracker microVMs, each with its own kernel. AgentCore's docs say its Code Interpreter runs in an isolated container environment. Modal's docs name two runtimes: gVisor, and a VM with its own Linux kernel. Running model output with exec() in your backend process is the thing to avoid; run untrusted code in Node.js and Python explains why.
An open network lets injected code send your data anywhere, so close it unless the task needs it. I created a Lizard sandbox with --allow-host pypi.org --allow-host '*.pythonhosted.org': curl https://example.com failed with exit code 35 and pip install polars still worked. With --no-internet alone, curl https://pypi.org timed out and Python still ran. E2B has allow_internet_access=False, Modal has block_network=True, and AgentCore's Sandbox mode reaches AWS services only.
Set a lifetime on the sandbox and a timeout on each call, so a loop that never ends costs seconds of compute. A Lizard sandbox lives 5 minutes unless you pass --timeout, and the docs give runCode a 60-second default per call.
Last, put nothing in the sandbox's environment that the code should not read. If generated code needs an API, give it a key scoped to that one job.
What does a code interpreter cost per 1,000 sessions?
For 1,000 sessions of 10 minutes each, the machine costs from $0 to about $40 across the seven options, or $120 if you give OpenAI's container 4 GB. The table uses list prices in US dollars read on 22 November 2026, with 2 vCPU and 4 GB where the size is configurable. It leaves out model tokens, storage, data transfer and tax. These are calculations, not measured bills.
| Option | Calculation | 1,000 sessions | Plan fee |
|---|---|---|---|
| Gemini code execution | No charge for the tool; each run is capped at 30 seconds | $0 | None |
| Claude code execution tool | 167 hours, inside the 1,550 hours a month at no charge; $0.05 an hour beyond that | $0 ($8.33 past the allowance) | None |
| Lizard, Small | 600 s × $0.0162 / 3,600 = $0.0027 | $2.70 | Lizard Pro, $19 a month with $19 of usage included |
| E2B, 2 vCPU and 4 GiB | 600 s × ($0.000028 + $0.000018) = $0.0276 | $27.60 | Hobby $0, Pro $150 a month |
| OpenAI Code Interpreter | $0.03 per container session at 1 GB; $0.12 at 4 GB | $30 ($120 at 4 GB) | None |
| AgentCore Code Interpreter | 600 s × 2 vCPU × $0.0895 / 3,600 + 600 s × 4 GB × $0.00945 / 3,600 = $0.0361 | $36.13 | None |
| Modal Sandboxes | 600 s × 1 core × $0.00003942 + 600 s × 4 GiB × $0.00000667 = $0.0397 | $39.66 | Starter $0, Team $250 a month |
The billing rules differ. AgentCore bills what the session uses, so its figure assumes both vCPUs are busy for the full 10 minutes. Modal bills the larger of what you request and what the session uses, and one Modal core is 2 vCPU, so its figure is 1 core and 4 GiB held for 10 minutes. With the 60% I/O wait that AWS uses in its own pricing example, the AgentCore figure falls to $18.23. Lizard and E2B bill a flat rate for the size while the sandbox runs, idle time included. OpenAI's pricing page also says eligible container sessions are billed by the minute with a 5-minute minimum, which would halve its figure for a 10-minute session. Claude's $0 buys 1 CPU, and Gemini's buys 30 seconds per run.
On Lizard the $2.70 comes out of the $19 of usage that Lizard Pro includes each month, and Pro runs up to 40 vCPU at once, which is 20 Small sandboxes. A new account starts with a 7-day trial that needs a card and includes $5 of usage. For AWS, the session math is in AgentCore pricing; hourly rates for more vendors are in sandbox pricing per hour.
FAQ
Is the OpenAI Code Interpreter available through the API? Yes. Add {"type": "code_interpreter", "container": {"type": "auto"}} to tools in a Responses API request. OpenAI's pricing page lists $0.03 per container per 20-minute session at the default 1 GB of memory.
What are the alternatives to AgentCore Code Interpreter? E2B Code Interpreter, Modal Sandboxes and the Lizard interpreter template are sandbox APIs that work with any model and outside AWS. AgentCore's own strengths are VPC networking, sessions of up to 8 hours and files up to 5 GB through Amazon S3.
Can I run LLM-generated Python without a sandbox? You can, with exec() or a subprocess, but the code then has your server's files, network and environment variables. A sandbox API puts it on a separate machine with its own kernel or container, a lifetime and a network policy. On Lizard that is one command: lizard sandbox create -t interpreter -s small --no-internet.
Build with AI. Ship with Lizard
You don't need a platform team to go live. Your whole cloud, one CLI command away.
- Services
- —
- Add-ons
- —
- Deployments
- —
- Sandbox starts
- —