Code Interpreter

Stateful Python, JavaScript and TypeScript execution with rich results for LLM tool calls, a thin layer over Sandal sandboxes.


Overview#

The code interpreter is not a separate product. It is the code namespace on a Sandal sandbox, tuned for LLM tool calling: short, stateful runs where variables and imports persist between calls, stdout streams back as it happens, and results (DataFrames, plots, JSON) come back as MIME bundles instead of scraped terminal text.

It runs inside a sandbox from the project default template (see Sandboxes for creating one). A run takes 0.6-0.8 s on the beta deployment. Use sandal capabilities to confirm code-interpreter is enabled for your project.

Why not just exec?#

processes.execAndWait(id, { command: ["python3", "script.py"], ... }) starts a fresh process every time: no shared variables, no shared imports. code.runAndWait runs in a persistent context, so each call sees what earlier calls defined.

import { randomUUID } from "node:crypto";
import { Sandal } from "@sandal-dev/sdk";

const sandal = new Sandal({
  baseUrl: "https://api.sandal.dev",
  apiToken: process.env.SANDAL_API_KEY!,
  // organizationId and projectId are optional: the key alone is enough.
  organizationId: process.env.SANDAL_ORGANIZATION_ID!,
  projectId: process.env.SANDAL_PROJECT_ID!,
});
const sandboxId = process.argv[2]; // a running enter-agent-linux sandbox

const first = await sandal.code.runAndWait(sandboxId, {
  idempotencyKey: randomUUID(),
  language: "python",
  code: "import math, sys\nprint('python', sys.version.split()[0])\n[math.sqrt(n) for n in range(4)]",
  onEvent: (event) => event.type === "stdout" && process.stdout.write(event.text ?? ""),
});
console.log(first.mainResult?.data["text/plain"]);

await sandal.code.runAndWait(sandboxId, { idempotencyKey: randomUUID(), language: "python", code: "x = 21" });
const second = await sandal.code.runAndWait(sandboxId, { idempotencyKey: randomUUID(), language: "python", code: "x * 2" });
console.log(second.mainResult?.data["text/plain"]); // "42"

x from the first call is still in scope for the second. An LLM iterating on an analysis does not have to reload its data every turn.

Contexts#

Each language has a default context (default-python, default-javascript, default-typescript) used when you pass only language. Create named contexts when you want independent state, their own working directory, or their own environment:

const { context: a } = await sandal.code.createContext(sandboxId, {
  idempotencyKey: randomUUID(),
  language: "python",
  cwd: "/workspace",
});
const { context: b } = await sandal.code.createContext(sandboxId, { idempotencyKey: randomUUID(), language: "python" });

await sandal.code.runAndWait(sandboxId, { idempotencyKey: randomUUID(), contextId: a.id, code: "x = 1" });
await sandal.code.runAndWait(sandboxId, { idempotencyKey: randomUUID(), contextId: b.id, code: "x = 2" });
const r = await sandal.code.runAndWait(sandboxId, { idempotencyKey: randomUUID(), contextId: a.id, code: "x" });
console.log(r.mainResult?.data["text/plain"]); // "1"

const { contexts } = await sandal.code.listContexts(sandboxId);
await sandal.code.restartContext(sandboxId, a.id, { idempotencyKey: randomUUID() }); // discard state, keep the sandbox
await sandal.code.deleteContext(sandboxId, b.id, { idempotencyKey: randomUUID() });

An execution is a sandbox process. sandal.code.interrupt(sandboxId, executionId, { idempotencyKey }) cancels a long run (KeyboardInterrupt / SIGINT) and the context survives; a kernel that ignores the interrupt is restarted.

Streaming output#

onEvent receives every event as it arrives. Event types are start, stdout, stderr, result, error and end:

const outcome = await sandal.code.runAndWait(sandboxId, {
  idempotencyKey: randomUUID(),
  language: "python",
  code: "import time\nfor i in range(5):\n    print(i, flush=True)\n    time.sleep(1)",
  onEvent: (event) => {
    if (event.type === "stdout") process.stdout.write(event.text ?? "");
    if (event.type === "stderr") process.stderr.write(event.text ?? "");
  },
});

That is the shape you would forward to a chat UI while the model's tool call executes. If runAndWait hits its own timeoutMs first, the outcome has terminal: false; resume with sandal.code.streamEvents(sandboxId, outcome.execution.id, { afterSequence: outcome.nextSequence }).

Rich results#

Results are MIME bundles: text/plain, text/html, image/png (base64, matplotlib figures), application/json, and application/vnd.sandal.table+json for pandas DataFrames.

const outcome = await sandal.code.runAndWait(sandboxId, {
  idempotencyKey: randomUUID(),
  language: "python",
  code: "import matplotlib.pyplot as plt\nplt.plot([1, 2, 3], [4, 1, 2])\nplt.show()",
});

for (const result of outcome.results) {
  const png = result.data["image/png"];
  if (typeof png === "string") {
    // render as `data:image/png;base64,${png}`
  }
}

if (outcome.error) {
  console.log(outcome.error.name, outcome.error.value, outcome.error.traceback);
}

Errors are structured (name, value, traceback), so a supervising agent can decide whether to retry, patch the code, or surface the failure without parsing stderr. Code is limited to 64 KiB per run. Which Python libraries are preinstalled depends on the template; install what you need with pip through processes.execAndWait.

LLM tool-calling integration#

code.runAndWait fits behind a single tool definition: give the model a run_code tool, execute what it sends, return the result, repeat.

import Anthropic from "@anthropic-ai/sdk";
import { randomUUID } from "node:crypto";
import { Sandal } from "@sandal-dev/sdk";

const anthropic = new Anthropic();
const sandal = new Sandal({
  baseUrl: "https://api.sandal.dev",
  apiToken: process.env.SANDAL_API_KEY!,
  // organizationId and projectId are optional: the key alone is enough.
  organizationId: process.env.SANDAL_ORGANIZATION_ID!,
  projectId: process.env.SANDAL_PROJECT_ID!,
});
const sandboxId = process.argv[2];

const tools = [
  {
    name: "run_code",
    description: "Execute Python code in a persistent, stateful interpreter and return its output.",
    input_schema: { type: "object" as const, properties: { code: { type: "string" } }, required: ["code"] },
  },
];
const messages: Anthropic.MessageParam[] = [
  { role: "user", content: "Compute the first 20 Fibonacci numbers and their sum." },
];

while (true) {
  const response = await anthropic.messages.create({ model: "claude-sonnet-4-5", max_tokens: 1024, tools, messages });
  messages.push({ role: "assistant", content: response.content });
  const calls = response.content.filter((block) => block.type === "tool_use");
  if (calls.length === 0) break; // final answer

  const results: Anthropic.ToolResultBlockParam[] = [];
  for (const call of calls) {
    const outcome = await sandal.code.runAndWait(sandboxId, {
      idempotencyKey: randomUUID(),
      language: "python",
      code: (call.input as { code: string }).code,
    });
    const text = outcome.error
      ? `Error: ${outcome.error.name}: ${outcome.error.value}`
      : `${outcome.stdout}${String(outcome.mainResult?.data["text/plain"] ?? "")}`;
    results.push({ type: "tool_result", tool_use_id: call.id, content: text });
  }
  messages.push({ role: "user", content: results });
}

The sandbox side does not change when you switch model providers; any framework that expects a (name, args) => result tool works the same way.

Everything else is a sandbox#

Because code runs inside a sandbox, the rest of the sandbox API is available on the same instance: files.write to drop a CSV in place, processes.execAndWait to pip install a library, sandboxes.exposePort for a server the model started, sandboxes.stop between sessions. See Sandboxes for those calls; note that stop ends the interpreter processes, so context state does not survive a stop.

Next steps#