このガイドでは、Code Interpreter API を使って、豊富な出力形式で Python と JavaScript のコードを実行する方法を説明します。
セットアップを最小にして、シンプルにコードを実行する ときは、Code Interpreter API を使います。
- すばやく実行する - 環境構築なしで Python / JS コードを実行します
- 豊富な出力 - チャート、テーブル、画像、HTML を自動で取得します
- AI 生成コード - LLM が生成したコードを実行し、構造化された結果を得ます
- 状態の保持 - 同じコンテキスト内の実行では変数が残ります
高度またはカスタムなワークフロー では exec() を使います。
- システム操作 - パッケージのインストール、ファイル管理、ビルド実行
- カスタム環境 - 特定のバージョンや依存関係を設定します
- シェルコマンド - 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 秒を超えるコードではストリーミングを使います
- AI コードを検証する - 実行前に生成コードを確認します
- コードインタープリター API - API の全体ドキュメント
- AI コード実行環境のチュートリアル - AI 実行環境を一通り作る
- コマンド実行ガイド - より低レベルのコマンド実行