Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

コードインタープリターを使う

最終更新 Markdown で表示Agent セットアップ

このガイドでは、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);
    }
  }
);

AI 生成コードを実行する

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.successresult.error を確認します
  • 長い処理はストリーミングする - 2 秒を超えるコードではストリーミングを使います
  • AI コードを検証する - 実行前に生成コードを確認します

関連情報

役に立ちましたか?