Перейти к содержимому

Контексты выполнения

Контекст сохраняет переменные, импорты и функции между вызовами. Создайте несколько контекстов, если независимые задачи должны выполняться в одной песочнице без общего состояния.

Создание контекста

Передавайте созданный контекст во все вызовы, которым нужно его состояние.

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();
}

Список контекстов

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();
}

В список также входят стандартные контексты Code Interpreter.

Перезапуск контекста

Перезапуск очищает переменные и запускает новое ядро в том же контексте.

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();
}

Удаление контекста

Удаляйте ненужные контексты. Сама песочница продолжит работать.

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();
}