Skip to content

Code interpreter

run_code sends code to a kernel inside the sandbox and returns an execution:

  • results: rich outputs such as text, HTML, PNG, JSON and charts
  • logs: stdout and stderr
  • error: set when the code raised

Variables, imports and files persist between calls in the same context.

Use a sandbox from the code-interpreter-all template. Its kernels cover Python, JavaScript, TypeScript, R, Java and Bash. For numpy, pandas and matplotlib (charts and rich results), use code-interpreter-data.

from svm import Sandbox
from svm.code_interpreter import CODE_INTERPRETER_TEMPLATE # "code-interpreter-all"
with Sandbox.create(template=CODE_INTERPRETER_TEMPLATE) as sandbox:
sandbox.run_code("counter = 1")
print(sandbox.run_code("counter += 1\ncounter").text) # 2: state persists
context = sandbox.create_code_context()
print(sandbox.run_code("'counter' in globals()", context=context).text) # False
failed = sandbox.run_code("1 / 0")
if failed.error:
print(failed.error.name, failed.error.value) # ZeroDivisionError division by zero
# "code-interpreter-data" adds numpy, pandas and matplotlib for charts and rich results.
with Sandbox.create(template="code-interpreter-data") as sandbox:
plot = sandbox.run_code(
"import matplotlib.pyplot as plt\n"
"plt.plot([1, 3, 2])\n"
"plt.show()"
)
for result in plot.results:
print(result.formats()) # e.g. ['png', 'text']
if result.png:
print("png, base64:", len(result.png), "chars")

A context is an independent kernel with its own state and working directory. Create one per user, task or language. restart_code_context clears a context’s state, and remove_code_context ends it.

A Python cell that draws a matplotlib figure returns the picture (png) and the chart as data (chart). An agent can then read the numbers instead of looking at pixels.

Chart Elements
line, scatter series of {label, points: [(x, y)]} with axis labels, units, ticks and scale
bar {label, group, value}
pie {label, angle, radius}
box_and_whisker {label, min, first_quartile, median, third_quartile, max, outliers}
superchart one chart per axes of a multi-axes figure