Code Interpreter
Execute code inside a running sandbox. The interpreter keeps a persistent REPL process alive so that variables, imports, and working directory survive across calls. Send code, get back stdout, stderr, rich results (text, images, HTML, JSON), and structured errors. For a full endpoint reference, see the Code Interpreter API.
Two runtimes are available:
| Alias | Runtime | Notes |
|---|---|---|
python, py, python3 | Python 3.12 | 50+ pre-installed data-science packages. Matplotlib charts auto-captured as PNG and SVG. |
typescript, ts, javascript, js, bun, node | Bun v1.3.10 (TypeScript) | Last expression is returned as a result. State accumulates across calls. |
Code interpreter endpoints are served inside the sandbox. Reach them through the sandbox invoke URL, not the management API. See Invoke a sandbox for background.
Contexts
Section titled “Contexts”A context is a session that owns one REPL process per language. State (variables, imports, cwd) lives for the lifetime of the context.
- Omit
context_idwhen executing to get an auto-created context. - Pass a
context_idto accumulate state across multiple execute calls. - A context is locked to the language of its first execution. Sending a different language returns a
400error. - Deleting a context kills the underlying REPL processes immediately.
Create a context
Section titled “Create a context”from leap0 import DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME, Leap0Client
client = Leap0Client()sandbox = client.sandboxes.create(template_name=DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME)context = sandbox.code_interpreter.create_context( language="python", cwd="/home/user",)
print(context.id, context.language)const domain = "sandbox.leap0.dev"const apiKey = "<your-api-key>"const sandboxId = "<sandbox_id>"
const res = await fetch(`https://${sandboxId}.${domain}/contexts`, {method: "POST",headers: { authorization: apiKey, "Content-Type": "application/json",},body: JSON.stringify({ language: "python", cwd: "/home/user" }),})
const ctx = await res.json()console.log(ctx.id, ctx.language)client.sandboxes.create(template_name=...) requires leap0 Python SDK v0.2.0+.
| Field | Type | Required | Description |
|---|---|---|---|
language | string | Yes | One of the supported language aliases. |
cwd | string | No | Initial working directory. Defaults to /home/user. |
List contexts
Section titled “List contexts”from leap0 import DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME, Leap0Client
client = Leap0Client()sandbox = client.sandboxes.create(template_name=DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME)for context in sandbox.code_interpreter.list_contexts(): print(context.id, context.language, context.cwd)const domain = "sandbox.leap0.dev"const apiKey = "<your-api-key>"const sandboxId = "<sandbox_id>"
const res = await fetch(`https://${sandboxId}.${domain}/contexts`, {headers: { authorization: apiKey },})
const { items } = await res.json()items.forEach((ctx) => console.log(ctx.id, ctx.language, ctx.cwd))client.sandboxes.create(template_name=...) requires leap0 Python SDK v0.2.0+.
Get a context
Section titled “Get a context”from leap0 import DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME, Leap0Client
client = Leap0Client()sandbox = client.sandboxes.create(template_name=DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME)context = sandbox.code_interpreter.get_context("<context_id>")print(context)const domain = "sandbox.leap0.dev"const apiKey = "<your-api-key>"const sandboxId = "<sandbox_id>"const contextId = "<context_id>"
const res = await fetch(`https://${sandboxId}.${domain}/contexts/${contextId}`, {headers: { authorization: apiKey },})
console.log(await res.json())client.sandboxes.create(template_name=...) requires leap0 Python SDK v0.2.0+.
Delete a context
Section titled “Delete a context”from leap0 import DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME, Leap0Client
client = Leap0Client()sandbox = client.sandboxes.create(template_name=DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME)sandbox.code_interpreter.delete_context("<context_id>")const domain = "sandbox.leap0.dev"const apiKey = "<your-api-key>"const sandboxId = "<sandbox_id>"const contextId = "<context_id>"
const res = await fetch(`https://${sandboxId}.${domain}/contexts/${contextId}`, {method: "DELETE",headers: { authorization: apiKey },})
console.log(res.status) // 204client.sandboxes.create(template_name=...) requires leap0 Python SDK v0.2.0+.
Execute code
Section titled “Execute code”Run code synchronously. The sandbox waits for the code to finish and returns the full result in one response.
from leap0 import DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME, Leap0Client
client = Leap0Client()sandbox = client.sandboxes.create(template_name=DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME)
first = sandbox.code_interpreter.execute( code="prices = [10, 20, 30, 40, 50]", language="python",)
second = sandbox.code_interpreter.execute( code="sum(prices) / len(prices)", language="python", context_id=first.context_id,)
for item in second.items: if item.text: print(item.text)const domain = "sandbox.leap0.dev"const apiKey = "<your-api-key>"const sandboxId = "<sandbox_id>"
// First call - define a variableconst first = await fetch(`https://${sandboxId}.${domain}/execute`, {method: "POST",headers: { authorization: apiKey, "Content-Type": "application/json",},body: JSON.stringify({ code: "prices = [10, 20, 30, 40, 50]", language: "python",}),})
const { context_id: contextId } = await first.json()
// Second call - reuse state from the first callconst second = await fetch(`https://${sandboxId}.${domain}/execute`, {method: "POST",headers: { authorization: apiKey, "Content-Type": "application/json",},body: JSON.stringify({ code: "sum(prices) / len(prices)", language: "python", context_id: contextId,}),})
const data = await second.json()data.items.forEach((r) => console.log(r.text)) // 30.0client.sandboxes.create(template_name=...) requires leap0 Python SDK v0.2.0+.
Request fields
Section titled “Request fields”| Field | Type | Required | Default | Description |
|---|---|---|---|---|
code | string | Yes | Source code to execute. | |
language | string | No | python | Any supported alias. |
context_id | string | No | auto-generated | Reuse an existing session. |
timeout_ms | integer | No | 30000 | Max execution time in milliseconds. |
Response shape
Section titled “Response shape”{ "context_id": "V1StGXR8_Z5jdHi6B-myT", "items": [ { "is_primary": true, "text": "30.0" } ], "logs": { "stdout": ["some printed output"], "stderr": [] }, "error": null, "execution_count": 2}items - ordered list of rich outputs. The last expression in Python and TypeScript is automatically captured as a result with is_primary: true. Each result can carry any combination of the following fields:
| Field | Type | When present |
|---|---|---|
text | string | Always, for any non-null result. |
png | string | Base64-encoded PNG - matplotlib charts, PIL images. |
svg | string | SVG markup - matplotlib vector output, custom _repr_svg_(). |
html | string | Objects with _repr_html_() (pandas DataFrames, etc.). |
markdown | string | Objects with _repr_markdown_(). |
json | object | Objects with _repr_json_(). |
jpeg | string | Base64-encoded JPEG. |
pdf | string | Base64-encoded PDF. |
latex | string | LaTeX markup. |
javascript | string | JavaScript output. |
logs - arrays of stdout and stderr lines captured during execution.
error - null on success, otherwise:
{ "name": "ZeroDivisionError", "value": "division by zero", "traceback": "Traceback (most recent call last):\n File \"<code>\", line 1, in <module>\nZeroDivisionError: division by zero\n"}execution_count - increments with each call in the context. Useful for ordering outputs.
Stream execution
Section titled “Stream execution”Execute code and receive output line-by-line as Server-Sent Events. Use this for long-running scripts or anything where you want to show progress to the user before the process exits.
from leap0 import DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME, Leap0Client
client = Leap0Client()sandbox = client.sandboxes.create(template_name=DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME)for event in sandbox.code_interpreter.execute_stream( code="""import timefor i in range(5):print(f'Step {i}')time.sleep(1)""", language="python", timeout_ms=60000,): if event.type == "stdout": print(event.data) elif event.type == "exit": print(f"Done (exit code {event.code})")const domain = "sandbox.leap0.dev"const apiKey = "<your-api-key>"const sandboxId = "<sandbox_id>"
const res = await fetch(`https://${sandboxId}.${domain}/execute/async`, {method: "POST",headers: { authorization: apiKey, "Content-Type": "application/json",},body: JSON.stringify({ code: "import time\nfor i in range(5):\n print(f'Step {i}')\n time.sleep(1)", language: "python", timeout_ms: 60000,}),})
const reader = res.body.getReader()const decoder = new TextDecoder()let buffer = ""
while (true) {const { done, value } = await reader.read()if (done) breakbuffer += decoder.decode(value, { stream: true })const lines = buffer.split("\n\n")buffer = lines.pop()for (const line of lines) { const payload = line.replace("data: ", "") const event = JSON.parse(payload) if (event.type === "stdout") console.log(event.data) if (event.type === "exit") console.log("Done (exit code " + event.code + ")")}}client.sandboxes.create(template_name=...) requires leap0 Python SDK v0.2.0+.
Event types
Section titled “Event types”Each data: line in the SSE stream is a JSON object:
| Type | Fields | Meaning |
|---|---|---|
stdout | data | A line printed to standard output. |
stderr | data | A line printed to standard error. |
exit | code | Process finished. code is 0 on success. |
error | data | Interpreter-level failure (e.g. "timeout"). |
Example stream for print("hello"):
data: {"type":"stdout","data":"hello"}
data: {"type":"exit","code":0}Generating charts
Section titled “Generating charts”Python’s matplotlib is pre-installed and patched to automatically capture figures. Call plt.show() and the PNG and SVG representations appear in the items array - no file I/O required.
from leap0 import DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME, Leap0Client
client = Leap0Client()sandbox = client.sandboxes.create(template_name=DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME)result = sandbox.code_interpreter.execute( code="""import matplotlib.pyplot as pltimport numpy as np
x = np.linspace(0, 2 * np.pi, 100)plt.figure(figsize=(8, 4))plt.plot(x, np.sin(x), label='sin(x)')plt.plot(x, np.cos(x), label='cos(x)')plt.legend()plt.title('Trigonometric Functions')plt.show()""", language="python",)
for item in result.items: if item.png: print(f"PNG image: {len(item.png)} base64 chars") if item.svg: print(f"SVG image: {len(item.svg)} chars")const domain = "sandbox.leap0.dev"const apiKey = "<your-api-key>"const sandboxId = "<sandbox_id>"
const res = await fetch(`https://${sandboxId}.${domain}/execute`, {method: "POST",headers: { authorization: apiKey, "Content-Type": "application/json",},body: JSON.stringify({ code: `import matplotlib.pyplot as pltimport numpy as np
x = np.linspace(0, 2 * np.pi, 100)plt.figure(figsize=(8, 4))plt.plot(x, np.sin(x), label='sin(x)')plt.plot(x, np.cos(x), label='cos(x)')plt.legend()plt.title('Trigonometric Functions')plt.show()`, language: "python",}),})
const data = await res.json()for (const r of data.items) {if (r.png) console.log("PNG image:", r.png.length, "base64 chars")if (r.svg) console.log("SVG image:", r.svg.length, "chars")}client.sandboxes.create(template_name=...) requires leap0 Python SDK v0.2.0+.
Pre-installed Python packages
Section titled “Pre-installed Python packages”The Python runtime ships with these packages ready to import:
| Category | Packages |
|---|---|
| Data science | numpy, pandas, scipy, scikit-learn, sympy |
| Visualization | matplotlib, seaborn, plotly, bokeh, kaleido |
| Image processing | pillow, opencv-python, scikit-image, imageio |
| Audio | librosa, soundfile |
| HTTP / Web | requests, aiohttp, beautifulsoup4, urllib3 |
| Data formats | orjson, openpyxl, xlrd, python-docx |
| Scientific computing | numba, xarray |
| NLP | nltk, gensim, spacy, textblob |
| Utilities | pytz, joblib, pytest |
Language-specific behavior
Section titled “Language-specific behavior”Python
Section titled “Python”- The last expression in a code block is evaluated and returned as a result with
is_primary: true. print()output appears inlogs.stdout.- Objects that implement rich display methods (
_repr_html_,_repr_png_, etc.) produce rich results automatically. This includes pandas DataFrames, PIL images, and any custom class that defines these methods. - A
display()function is available globally for explicitly emitting rich results mid-execution.
TypeScript (Bun)
Section titled “TypeScript (Bun)”- Code is transpiled and executed via Bun v1.3.10 in a subprocess. Each execution writes to a temp file that includes all accumulated state from prior calls in the same context.
- The last expression is captured as a result when it is not a statement keyword (
const,let,if,for,function, etc.). console.log()writes to stdout.console.error()andconsole.warn()write to stderr.