← Sandbox SDK / sandbox / api
Code interpreter
Выполняйте код на Python, JavaScript и TypeScript с поддержкой визуализации данных, таблиц и расширенных форматов вывода. Контексты сохраняют состояние (переменные, импорты, функции) между запусками.
Методы
createCodeContext()
Создаёт постоянный контекст выполнения для запуска кода.
const context = await sandbox.createCodeContext(options?: CreateContextOptions): Promise<CodeContext>Параметры:
options(необязательно):language-"python" | "javascript" | "typescript"(по умолчанию:"python")cwd- Рабочий каталог (по умолчанию:"/workspace")envVars- Переменные окруженияtimeout- Таймаут запроса в миллисекундах (по умолчанию: 30000)
Возвращает: Promise<CodeContext> с id, language, cwd, createdAt, lastUsed
const ctx = await sandbox.createCodeContext({
language: "python",
envVars: { API_KEY: env.API_KEY },
});const ctx = await sandbox.createCodeContext({
language: 'python',
envVars: { API_KEY: env.API_KEY }
});runCode()
Выполните код в контексте и получите полный результат.
const result = await sandbox.runCode(code: string, options?: RunCodeOptions): Promise<ExecutionResult>Параметры:
code- Код для выполнения (обязательно)options(необязательно):context- Контекст для запуска (рекомендуется, см. ниже)language-"python" | "javascript" | "typescript"(по умолчанию:"python")timeout- Тайм-аут выполнения в миллисекундах (по умолчанию: 60000)onStdout,onStderr,onResult,onError- Потоковые обратные вызовы
Возвращает: Promise<ExecutionResult> с:
code- Выполненный кодlogs-stdoutиstderrмассивыresults- Массив расширенных данных вывода (см. Расширенные форматы вывода)error- Ошибка выполнения, если она естьexecutionCount- Счётчик выполнений
Рекомендуемое использование: создание явного контекста:
const ctx = await sandbox.createCodeContext({ language: "python" });
await sandbox.runCode("import math; radius = 5", { context: ctx });
const result = await sandbox.runCode("math.pi * radius ** 2", { context: ctx });
console.log(result.results[0].text); // "78.53981633974483"const ctx = await sandbox.createCodeContext({ language: 'python' });
await sandbox.runCode('import math; radius = 5', { context: ctx });
const result = await sandbox.runCode('math.pi * radius ** 2', { context: ctx });
console.log(result.results[0].text); // "78.53981633974483"Обработка ошибок:
const result = await sandbox.runCode("x = 1 / 0", { language: "python" });
if (result.error) {
console.error(result.error.name); // "ZeroDivisionError"
console.error(result.error.value); // "division by zero"
console.error(result.error.traceback); // Stack trace array
}const result = await sandbox.runCode('x = 1 / 0', { language: 'python' });
if (result.error) {
console.error(result.error.name); // "ZeroDivisionError"
console.error(result.error.value); // "division by zero"
console.error(result.error.traceback); // Stack trace array
}Возможности JavaScript и TypeScript:
Выполнение кода на JavaScript и TypeScript поддерживает верхнеуровневый await и постоянные переменные между выполнениями в рамках одного контекста.
const ctx = await sandbox.createCodeContext({ language: "javascript" });
// Execution 1: Fetch data with top-level await
await sandbox.runCode(
`
const response = await fetch('https://api.example.com/data');
const data = await response.json();
`,
{ context: ctx },
);
// Execution 2: Use the data from previous execution
const result = await sandbox.runCode("console.log(data)", { context: ctx });
console.log(result.logs.stdout); // Data persists across executionsconst ctx = await sandbox.createCodeContext({ language: 'javascript' });
// Execution 1: Fetch data with top-level await
await sandbox.runCode(`
const response = await fetch('https://api.example.com/data');
const data = await response.json();
`, { context: ctx });
// Execution 2: Use the data from previous execution
const result = await sandbox.runCode('console.log(data)', { context: ctx });
console.log(result.logs.stdout); // Data persists across executionsПеременные, объявленные с помощью const, let, или var сохраняются между выполнениями, что позволяет реализовывать многошаговые сценарии:
const ctx = await sandbox.createCodeContext({ language: "javascript" });
await sandbox.runCode("const x = 10", { context: ctx });
await sandbox.runCode("let y = 20", { context: ctx });
const result = await sandbox.runCode("x + y", { context: ctx });
console.log(result.results[0].text); // "30"const ctx = await sandbox.createCodeContext({ language: 'javascript' });
await sandbox.runCode('const x = 10', { context: ctx });
await sandbox.runCode('let y = 20', { context: ctx });
const result = await sandbox.runCode('x + y', { context: ctx });
console.log(result.results[0].text); // "30"listCodeContexts()
Список всех активных контекстов выполнения кода.
const contexts = await sandbox.listCodeContexts(): Promise<CodeContext[]>const contexts = await sandbox.listCodeContexts();
console.log(`Found ${contexts.length} contexts`);const contexts = await sandbox.listCodeContexts();
console.log(`Found ${contexts.length} contexts`);deleteCodeContext()
Удалите контекст выполнения кода и освободите его ресурсы.
await sandbox.deleteCodeContext(contextId: string): Promise<void>const ctx = await sandbox.createCodeContext({ language: "python" });
await sandbox.runCode('print("Hello")', { context: ctx });
await sandbox.deleteCodeContext(ctx.id);const ctx = await sandbox.createCodeContext({ language: 'python' });
await sandbox.runCode('print("Hello")', { context: ctx });
await sandbox.deleteCodeContext(ctx.id);Расширенные форматы вывода
Результаты включают: text, html, png, jpeg, svg, latex, markdown, json, chart, data
Диаграммы (matplotlib):
const result = await sandbox.runCode(
`
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x))
plt.show()
`,
{ language: "python" },
);
if (result.results[0]?.png) {
const imageBuffer = Buffer.from(result.results[0].png, "base64");
return new Response(imageBuffer, {
headers: { "Content-Type": "image/png" },
});
}const result = await sandbox.runCode(`
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x))
plt.show()
`, { language: 'python' });
if (result.results[0]?.png) {
const imageBuffer = Buffer.from(result.results[0].png, 'base64');
return new Response(imageBuffer, {
headers: { 'Content-Type': 'image/png' }
});
}Таблицы (pandas):
const result = await sandbox.runCode(
`
import pandas as pd
df = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [25, 30]})
df
`,
{ language: "python" },
);
if (result.results[0]?.html) {
return new Response(result.results[0].html, {
headers: { "Content-Type": "text/html" },
});
}const result = await sandbox.runCode(`
import pandas as pd
df = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [25, 30]})
df
`, { language: 'python' });
if (result.results[0]?.html) {
return new Response(result.results[0].html, {
headers: { 'Content-Type': 'text/html' }
});
}Дополнительные материалы
- Создание ИИ-исполнителя кода - Полный учебник
- Commands API - Выполнение команд на более низком уровне
- Files API - Операции с файлами