Skip to content

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:

AliasRuntimeNotes
python, py, python3Python 3.1250+ pre-installed data-science packages. Matplotlib charts auto-captured as PNG and SVG.
typescript, ts, javascript, js, bun, nodeBun 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.

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_id when executing to get an auto-created context.
  • Pass a context_id to accumulate state across multiple execute calls.
  • A context is locked to the language of its first execution. Sending a different language returns a 400 error.
  • Deleting a context kills the underlying REPL processes immediately.
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)

client.sandboxes.create(template_name=...) requires leap0 Python SDK v0.2.0+.

FieldTypeRequiredDescription
languagestringYesOne of the supported language aliases.
cwdstringNoInitial working directory. Defaults to /home/user.
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)

client.sandboxes.create(template_name=...) requires leap0 Python SDK v0.2.0+.

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)

client.sandboxes.create(template_name=...) requires leap0 Python SDK v0.2.0+.

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>")

client.sandboxes.create(template_name=...) requires leap0 Python SDK v0.2.0+.

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)

client.sandboxes.create(template_name=...) requires leap0 Python SDK v0.2.0+.

FieldTypeRequiredDefaultDescription
codestringYesSource code to execute.
languagestringNopythonAny supported alias.
context_idstringNoauto-generatedReuse an existing session.
timeout_msintegerNo30000Max execution time in milliseconds.
{
"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:

FieldTypeWhen present
textstringAlways, for any non-null result.
pngstringBase64-encoded PNG - matplotlib charts, PIL images.
svgstringSVG markup - matplotlib vector output, custom _repr_svg_().
htmlstringObjects with _repr_html_() (pandas DataFrames, etc.).
markdownstringObjects with _repr_markdown_().
jsonobjectObjects with _repr_json_().
jpegstringBase64-encoded JPEG.
pdfstringBase64-encoded PDF.
latexstringLaTeX markup.
javascriptstringJavaScript 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.

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 time
for 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})")

client.sandboxes.create(template_name=...) requires leap0 Python SDK v0.2.0+.

Each data: line in the SSE stream is a JSON object:

TypeFieldsMeaning
stdoutdataA line printed to standard output.
stderrdataA line printed to standard error.
exitcodeProcess finished. code is 0 on success.
errordataInterpreter-level failure (e.g. "timeout").

Example stream for print("hello"):

data: {"type":"stdout","data":"hello"}
data: {"type":"exit","code":0}

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 plt
import 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")

client.sandboxes.create(template_name=...) requires leap0 Python SDK v0.2.0+.

The Python runtime ships with these packages ready to import:

CategoryPackages
Data sciencenumpy, pandas, scipy, scikit-learn, sympy
Visualizationmatplotlib, seaborn, plotly, bokeh, kaleido
Image processingpillow, opencv-python, scikit-image, imageio
Audiolibrosa, soundfile
HTTP / Webrequests, aiohttp, beautifulsoup4, urllib3
Data formatsorjson, openpyxl, xlrd, python-docx
Scientific computingnumba, xarray
NLPnltk, gensim, spacy, textblob
Utilitiespytz, joblib, pytest
  • The last expression in a code block is evaluated and returned as a result with is_primary: true.
  • print() output appears in logs.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.
  • 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() and console.warn() write to stderr.