Skip to content

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

AI コード実行環境を作る

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

Sandbox SDK と Claude で、AI によるコード実行システムを作ります。自然言語の質問を Python コードに変換し、安全に実行して結果を返します。

所要時間: 20 分

作成するもの

「フィボナッチ数列の 100 番目は?」のような質問を受け取り、Claude で Python コードを生成し、分離されたサンドボックスで実行して結果を返す API です。

前提条件

  1. Cloudflare アカウント に登録します。
  2. Node.js をインストールします。

Node.js のバージョンマネージャー

権限の問題を避け、Node.js のバージョンを切り替えられるよう、Voltanvm などの Node バージョンマネージャーを使います。このガイドの後半で説明する Wrangler には、Node バージョン 16.17.0 以降が必要です。

次のものも必要です。

1. プロジェクトを作成する

新しい Sandbox SDK プロジェクトを作成します。

npm create cloudflare@latest -- ai-code-executor --template=cloudflare/sandbox-sdk/examples/minimal
cd ai-code-executor

2. 依存関係をインストールする

Anthropic SDK をインストールします。

npm i @anthropic-ai/sdk

3. コード実行処理を実装する

src/index.ts の内容を次に置き換えます。

import { getSandbox, type Sandbox } from '@cloudflare/sandbox';
import Anthropic from '@anthropic-ai/sdk';

export { Sandbox } from '@cloudflare/sandbox';

interface Env {
	Sandbox: DurableObjectNamespace<Sandbox>;
	ANTHROPIC_API_KEY: string;
}

export default {
	async fetch(request: Request, env: Env): Promise<Response> {
		if (request.method !== 'POST' || new URL(request.url).pathname !== '/execute') {
			return new Response('POST /execute with { "question": "your question" }');
		}

		try {
			const { question } = await request.json();

			if (!question) {
				return Response.json({ error: 'Question is required' }, { status: 400 });
			}

			// Use Claude to generate Python code
			const anthropic = new Anthropic({ apiKey: env.ANTHROPIC_API_KEY });
			const codeGeneration = await anthropic.messages.create({
				model: 'claude-sonnet-4-5',
				max_tokens: 1024,
				messages: [{
					role: 'user',
					content: `Generate Python code to answer: "${question}"

Requirements:
- Use only Python standard library
- Print the result using print()
- Keep code simple and safe

Return ONLY the code, no explanations.`
				}],
			});

			const generatedCode = codeGeneration.content[0]?.type === 'text'
				? codeGeneration.content[0].text
				: '';

			if (!generatedCode) {
				return Response.json({ error: 'Failed to generate code' }, { status: 500 });
			}

			// Strip markdown code fences if present
			const cleanCode = generatedCode
				.replace(/^```python?\n?/, '')
				.replace(/\n?```\s*$/, '')
				.trim();

			// Execute the code in a sandbox
			const sandbox = getSandbox(env.Sandbox, 'demo-user');
			await sandbox.writeFile('/tmp/code.py', cleanCode);
			const result = await sandbox.exec('python /tmp/code.py');

			return Response.json({
				success: result.success,
				question,
				code: generatedCode,
				output: result.stdout,
				error: result.stderr
			});

		} catch (error: any) {
			return Response.json(
				{ error: 'Internal server error', message: error.message },
				{ status: 500 }
			);
		}
	},
};

仕組み:

  1. /execute への POST で質問を受け取ります
  2. Claude で Python コードを生成します
  3. サンドボックスの /tmp/code.py にコードを書き込みます
  4. sandbox.exec('python /tmp/code.py') で実行します
  5. コードと実行結果の両方を返します

4. ローカルの環境変数を設定する

ローカル開発用に、プロジェクトルートへ .dev.vars ファイルを作成します。

echo "ANTHROPIC_API_KEY=your_api_key_here" > .dev.vars

your_api_key_here を、Anthropic Console で取得した実際の API キーに置き換えます。

5. ローカルでテストする

開発サーバーを起動します。

npm run dev

curl でテストします。

curl -X POST http://localhost:8787/execute \
  -H "Content-Type: application/json" \
  -d '{"question": "What is the 10th Fibonacci number?"}'

応答:

{
  "success": true,
  "question": "What is the 10th Fibonacci number?",
  "code": "def fibonacci(n):\n    if n <= 1:\n        return n\n    return fibonacci(n-1) + fibonacci(n-2)\n\nprint(fibonacci(10))",
  "output": "55\n",
  "error": ""
}

6. デプロイする

Worker をデプロイします。

npx wrangler deploy

次に、Anthropic API キーを本番のシークレットとして設定します。

npx wrangler secret put ANTHROPIC_API_KEY

プロンプトが表示されたら、Anthropic Console の API キーを貼り付けます。

7. デプロイをテストする

さまざまな質問を試します。

# Factorial
curl -X POST https://ai-code-executor.YOUR_SUBDOMAIN.workers.dev/execute \
  -H "Content-Type: application/json" \
  -d '{"question": "Calculate the factorial of 5"}'

# Statistics
curl -X POST https://ai-code-executor.YOUR_SUBDOMAIN.workers.dev/execute \
  -H "Content-Type: application/json" \
  -d '{"question": "What is the mean of [10, 20, 30, 40, 50]?"}'

# String manipulation
curl -X POST https://ai-code-executor.YOUR_SUBDOMAIN.workers.dev/execute \
  -H "Content-Type: application/json" \
  -d '{"question": "Reverse the string \"Hello World\""}'

作成したもの

次の機能を持つ AI コード実行システムです。

  • 自然言語の質問を受け取ります
  • Claude で Python コードを生成します
  • 分離されたサンドボックスで安全に実行します
  • エラー処理つきで結果を返します

次のステップ

関連情報

役に立ちましたか?