← Sandbox SDK / sandbox / guides
Используйте интерпретатор кода
В этом руководстве показано, как выполнять код на Python и JavaScript с расширенным выводом с помощью API Code Interpreter.
Когда использовать интерпретатор кода
Используйте API Code Interpreter для простое, прямое выполнение кода с минимальной настройкой:
- Быстрое выполнение кода - Запуск кода Python/JS без настройки окружения
- Расширенные выводы - Автоматически получайте графики, таблицы, изображения, HTML
- Код, сгенерированный ИИ - Выполняйте код, сгенерированный LLM, со структурированными результатами
- Постоянное состояние - Переменные сохраняются между выполнениями в одном контексте
Используйте exec() для расширенные или пользовательские рабочие процессы:
- Системные операции - Устанавливайте пакеты, управляйте файлами, запускайте сборки
- Пользовательские окружения - Настройте конкретные версии, зависимости
- Команды shell - Git-операции, системные утилиты, сложные конвейеры
- Долго выполняющиеся процессы - Фоновые службы, серверы
Создайте контекст выполнения
Контексты кода сохраняют состояние между запусками:
import { getSandbox } from "@cloudflare/sandbox";
const sandbox = getSandbox(env.Sandbox, "my-sandbox");
// Create a Python context
const pythonContext = await sandbox.createCodeContext({
language: "python",
});
console.log("Context ID:", pythonContext.id);
console.log("Language:", pythonContext.language);
// Create a JavaScript context
const jsContext = await sandbox.createCodeContext({
language: "javascript",
});import { getSandbox } from '@cloudflare/sandbox';
const sandbox = getSandbox(env.Sandbox, 'my-sandbox');
// Create a Python context
const pythonContext = await sandbox.createCodeContext({
language: 'python'
});
console.log('Context ID:', pythonContext.id);
console.log('Language:', pythonContext.language);
// Create a JavaScript context
const jsContext = await sandbox.createCodeContext({
language: 'javascript'
});Выполнение кода
Простое выполнение
// Create context
const context = await sandbox.createCodeContext({
language: "python",
});
// Execute code
const result = await sandbox.runCode(
`
print("Hello from Code Interpreter!")
result = 2 + 2
print(f"2 + 2 = {result}")
`,
{ context: context.id },
);
console.log("Output:", result.output);
console.log("Success:", result.success);// Create context
const context = await sandbox.createCodeContext({
language: 'python'
});
// Execute code
const result = await sandbox.runCode(`
print("Hello from Code Interpreter!")
result = 2 + 2
print(f"2 + 2 = {result}")
`, { context: context.id });
console.log('Output:', result.output);
console.log('Success:', result.success);Состояние в рамках контекста
Переменные и импорты остаются доступными между запусками в рамках одного контекста, пока контейнер активен:
const context = await sandbox.createCodeContext({
language: "python",
});
// First execution - import and define variables
await sandbox.runCode(
`
import pandas as pd
import numpy as np
data = [1, 2, 3, 4, 5]
print("Data initialized")
`,
{ context: context.id },
);
// Second execution - use previously defined variables
const result = await sandbox.runCode(
`
mean = np.mean(data)
print(f"Mean: {mean}")
`,
{ context: context.id },
);
console.log(result.output); // "Mean: 3.0"const context = await sandbox.createCodeContext({
language: 'python'
});
// First execution - import and define variables
await sandbox.runCode(`
import pandas as pd
import numpy as np
data = [1, 2, 3, 4, 5]
print("Data initialized")
`, { context: context.id });
// Second execution - use previously defined variables
const result = await sandbox.runCode(`
mean = np.mean(data)
print(f"Mean: {mean}")
`, { context: context.id });
console.log(result.output); // "Mean: 3.0"Обработка расширенного вывода
Интерпретатор кода возвращает несколько форматов вывода:
const result = await sandbox.runCode(
`
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.title('Simple Chart')
plt.show()
`,
{ context: context.id },
);
// Check available formats
console.log("Formats:", result.formats); // ['text', 'png']
// Access outputs
if (result.outputs.png) {
// Return as image
return new Response(atob(result.outputs.png), {
headers: { "Content-Type": "image/png" },
});
}
if (result.outputs.html) {
// Return as HTML (pandas DataFrames)
return new Response(result.outputs.html, {
headers: { "Content-Type": "text/html" },
});
}
if (result.outputs.json) {
// Return as JSON
return Response.json(result.outputs.json);
}const result = await sandbox.runCode(`
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.title('Simple Chart')
plt.show()
`, { context: context.id });
// Check available formats
console.log('Formats:', result.formats); // ['text', 'png']
// Access outputs
if (result.outputs.png) {
// Return as image
return new Response(atob(result.outputs.png), {
headers: { 'Content-Type': 'image/png' }
});
}
if (result.outputs.html) {
// Return as HTML (pandas DataFrames)
return new Response(result.outputs.html, {
headers: { 'Content-Type': 'text/html' }
});
}
if (result.outputs.json) {
// Return as JSON
return Response.json(result.outputs.json);
}Потоковый вывод выполнения
Для долго выполняющегося кода передавайте вывод в реальном времени:
const context = await sandbox.createCodeContext({
language: "python",
});
const result = await sandbox.runCode(
`
import time
for i in range(10):
print(f"Processing item {i+1}/10...")
time.sleep(0.5)
print("Done!")
`,
{
context: context.id,
stream: true,
onOutput: (data) => {
console.log("Output:", data);
},
onResult: (result) => {
console.log("Result:", result);
},
onError: (error) => {
console.error("Error:", error);
},
},
);const context = await sandbox.createCodeContext({
language: 'python'
});
const result = await sandbox.runCode(
`
import time
for i in range(10):
print(f"Processing item {i+1}/10...")
time.sleep(0.5)
print("Done!")
`,
{
context: context.id,
stream: true,
onOutput: (data) => {
console.log('Output:', data);
},
onResult: (result) => {
console.log('Result:', result);
},
onError: (error) => {
console.error('Error:', error);
}
}
);Выполнение кода, сгенерированного ИИ
Безопасное выполнение сгенерированного LLM кода в песочнице:
// 1. Generate code with Claude
const response = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": env.ANTHROPIC_API_KEY,
"anthropic-version": "2023-06-01",
},
body: JSON.stringify({
model: "claude-3-5-sonnet-20241022",
max_tokens: 1024,
messages: [
{
role: "user",
content: "Write Python code to calculate fibonacci sequence up to 100",
},
],
}),
});
const { content } = await response.json();
const code = content[0].text;
// 2. Execute in sandbox
const context = await sandbox.createCodeContext({ language: "python" });
const result = await sandbox.runCode(code, { context: context.id });
console.log("Generated code:", code);
console.log("Output:", result.output);
console.log("Success:", result.success);// 1. Generate code with Claude
const response = await fetch('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': env.ANTHROPIC_API_KEY,
'anthropic-version': '2023-06-01'
},
body: JSON.stringify({
model: 'claude-3-5-sonnet-20241022',
max_tokens: 1024,
messages: [{
role: 'user',
content: 'Write Python code to calculate fibonacci sequence up to 100'
}]
})
});
const { content } = await response.json();
const code = content[0].text;
// 2. Execute in sandbox
const context = await sandbox.createCodeContext({ language: 'python' });
const result = await sandbox.runCode(code, { context: context.id });
console.log('Generated code:', code);
console.log('Output:', result.output);
console.log('Success:', result.success);Управление контекстами
Список всех контекстов
const contexts = await sandbox.listCodeContexts();
console.log(`${contexts.length} active contexts:`);
for (const ctx of contexts) {
console.log(` ${ctx.id} (${ctx.language})`);
}const contexts = await sandbox.listCodeContexts();
console.log(`${contexts.length} active contexts:`);
for (const ctx of contexts) {
console.log(` ${ctx.id} (${ctx.language})`);
}Удаление контекстов
// Delete specific context
await sandbox.deleteCodeContext(context.id);
console.log("Context deleted");
// Clean up all contexts
const contexts = await sandbox.listCodeContexts();
for (const ctx of contexts) {
await sandbox.deleteCodeContext(ctx.id);
}
console.log("All contexts deleted");// Delete specific context
await sandbox.deleteCodeContext(context.id);
console.log('Context deleted');
// Clean up all contexts
const contexts = await sandbox.listCodeContexts();
for (const ctx of contexts) {
await sandbox.deleteCodeContext(ctx.id);
}
console.log('All contexts deleted');Рекомендации
- Очистка контекстов - Удаляйте контексты после использования, чтобы освободить ресурсы
- Обработка ошибок - Всегда проверяйте
result.successиresult.error - Потоковая передача длительных операций - Используйте потоковую передачу для кода, выполнение которого занимает более 2 секунд
- Проверка кода, сгенерированного ИИ - Проверяйте сгенерированный код перед выполнением
Дополнительные материалы
- Справочник по Code Interpreter API - Полная документация по API
- Учебник по исполнителю кода на базе ИИ - Создайте полноценный исполнитель кода на базе ИИ
- Руководство по выполнению команд - Выполнение команд на более низком уровне