Skip to content

Code contexts

A context keeps variables, imports, and functions between calls. Create several contexts when independent tasks must run in the same sandbox without sharing state.

Create a context

Pass the returned context to every call that should use its state.

mjs
const sandbox = await Sandbox.create("code-interpreter");

try {
  const context = await sandbox.createCodeContext({ language: "python" });
  await sandbox.runCode("value = 21", { context });
  const execution = await sandbox.runCode("value * 2", { context });
  console.log(execution.text);
} finally {
  await sandbox.kill();
}

List contexts

mjs
const sandbox = await Sandbox.create("code-interpreter");

try {
  await sandbox.createCodeContext({ language: "python" });
  const contexts = await sandbox.listCodeContexts();
  console.log(contexts.map((context) => context.id));
} finally {
  await sandbox.kill();
}

The list also contains the default contexts managed by Code Interpreter.

Restart a context

Restarting clears variables and starts a fresh kernel under the same context.

mjs
const sandbox = await Sandbox.create("code-interpreter");

try {
  const context = await sandbox.createCodeContext({ language: "python" });
  await sandbox.runCode("value = 42", { context });
  await sandbox.restartCodeContext(context);

  const execution = await sandbox.runCode(
    "'reset' if 'value' not in globals() else 'kept'",
    { context },
  );
  console.log(execution.text);
} finally {
  await sandbox.kill();
}

Remove a context

Remove contexts you no longer need. The sandbox itself continues running.

mjs
const sandbox = await Sandbox.create("code-interpreter");

try {
  const context = await sandbox.createCodeContext({ language: "python" });
  await sandbox.removeCodeContext(context);

  const contexts = await sandbox.listCodeContexts();
  console.log(contexts.map((item) => item.id));
} finally {
  await sandbox.kill();
}