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 chartslogs: stdout and stderrerror: 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.
Run code, keep state, use contexts
Section titled “Run code, keep state, use contexts”from svm import Sandboxfrom 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")import { Sandbox } from "@svm/sandbox";
const sandbox = await Sandbox.create({ template: "code-interpreter-data", wait: true });try { await sandbox.runCode("counter = 41"); console.log((await sandbox.runCode("counter + 1")).text); // "42": state persists
const ctx = await sandbox.createCodeContext({ language: "python" }); await sandbox.runCode("counter = 0", { context: ctx }); // a separate kernel
const plot = await sandbox.runCode( "import matplotlib.pyplot as plt\nplt.plot([1, 2, 3], [1, 4, 9])\nplt.show()", ); for (const result of plot.results) { console.log(result.formats()); // e.g. ["text", "png"] if (result.png) console.log("png bytes (base64):", result.png.length); }
const failed = await sandbox.runCode("1 / 0"); if (failed.error) { console.log(failed.error.name, failed.error.value); console.log(failed.error.traceback); }} finally { await sandbox.kill();}sandbox, err := client.CreateSandbox(ctx, svm.CreateSandboxOptions{Template: svm.CodeInterpreterTemplate})if err != nil { return err}defer sandbox.Kill(ctx)if _, err := sandbox.RunCode(ctx, "x = 41"); err != nil { return err}execution, err := sandbox.RunCode(ctx, "x + 1") // the kernel keeps x between callsif err != nil { return err}fmt.Println(execution.Text()) // 42
separate, err := sandbox.CreateCodeContext(ctx, "python", "/tmp")if err != nil { return err}execution, err = sandbox.RunCode(ctx, "'x' in globals()", svm.RunCodeOptions{Context: separate.ID})if err != nil { return err}fmt.Println("x in the new context:", execution.Text()) // False
execution, err = sandbox.RunCode(ctx, "1 / 0")if err != nil { return err // the call failed; an error in the code is in execution.Error}if execution.Error != nil { fmt.Println(execution.Error.Name, execution.Error.Value)}
// Charts need numpy, pandas and matplotlib: the code-interpreter-data template has them.data, err := client.CreateSandbox(ctx, svm.CreateSandboxOptions{Template: "code-interpreter-data"})if err != nil { return err}defer data.Kill(ctx)plot := "import matplotlib.pyplot as plt\nplt.plot([1, 4, 9])\nplt.show()"execution, err = data.RunCode(ctx, plot)if err != nil { return err}for _, result := range execution.Results { fmt.Println("formats:", result.Formats()) // e.g. [png chart]}require "svm"
box = SVM::Sandbox.create(template: "code-interpreter-all")begin box.run_code("counter = 1") puts box.run_code("counter += 1\ncounter").text # 2: state persists between calls
context = box.create_code_context(language: "python") box.run_code("counter = 100", context: context) # a separate kernel
failed = box.run_code("1 / 0") puts "#{failed.error.name}: #{failed.error.value}" if failed.errorensure box.killend
# numpy, pandas and matplotlib come with the "code-interpreter-data" template.charts = SVM::Sandbox.create(template: "code-interpreter-data")begin plot = charts.run_code("import matplotlib.pyplot as plt\nplt.plot([1, 2, 3], [1, 4, 9])\nplt.show()") plot.results.each { |r| puts "result formats: #{r.formats.join(', ')}" } # e.g. png image = plot.results.find(&:png) File.binwrite("plot.png", image.png.unpack1("m")) if image # png is base64ensure charts.killendimport dev.svm.sandbox.Client;import dev.svm.sandbox.Context;import dev.svm.sandbox.Execution;import dev.svm.sandbox.Result;import dev.svm.sandbox.Sandbox;
public class CodeInterpreterExample { public static void main(String[] args) { Client client = Client.fromEnvironment(); try (Sandbox sandbox = Sandbox.create(client, "code-interpreter-all")) { sandbox.runCode("x = 41"); System.out.println("x + 1 = " + sandbox.runCode("x + 1").text()); // state persists
Context ctx = sandbox.createCodeContext(null, "python"); System.out.println("in a new context: " + sandbox.runCode("'x' in globals()", ctx).text());
Execution failed = sandbox.runCode("1 / 0"); if (failed.error != null) System.out.println(failed.error.name + ": " + failed.error.value); }
// numpy, pandas and matplotlib come with "code-interpreter-data". try (Sandbox data = Sandbox.create(client, "code-interpreter-data")) { Execution plot = data.runCode( "import matplotlib.pyplot as plt\nplt.plot([1, 2, 3], [1, 4, 9])\nplt.show()"); for (Result r : plot.results) System.out.println("result formats: " + r.formats()); // e.g. [png] } }}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.
Charts as data
Section titled “Charts as data”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 |