Sandbox SDK と Claude で、AI によるコード実行システムを作ります。自然言語の質問を Python コードに変換し、安全に実行して結果を返します。
所要時間: 20 分
「フィボナッチ数列の 100 番目は?」のような質問を受け取り、Claude で Python コードを生成し、分離されたサンドボックスで実行して結果を返す API です。
- Cloudflare アカウント ↗ に登録します。
Node.js↗ をインストールします。
Node.js のバージョンマネージャー
権限の問題を避け、Node.js のバージョンを切り替えられるよう、Volta ↗ や nvm ↗ などの Node バージョンマネージャーを使います。このガイドの後半で説明する Wrangler には、Node バージョン 16.17.0 以降が必要です。
次のものも必要です。
- Claude 用の Anthropic API キー ↗
- ローカルで起動している Docker ↗
新しい Sandbox SDK プロジェクトを作成します。
npm create cloudflare@latest -- ai-code-executor --template=cloudflare/sandbox-sdk/examples/minimalyarn create cloudflare ai-code-executor --template=cloudflare/sandbox-sdk/examples/minimalpnpm create cloudflare@latest ai-code-executor --template=cloudflare/sandbox-sdk/examples/minimalcd ai-code-executorAnthropic SDK をインストールします。
npm i @anthropic-ai/sdkyarn add @anthropic-ai/sdkpnpm add @anthropic-ai/sdkbun add @anthropic-ai/sdksrc/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 }
);
}
},
};仕組み:
/executeへの POST で質問を受け取ります- Claude で Python コードを生成します
- サンドボックスの
/tmp/code.pyにコードを書き込みます sandbox.exec('python /tmp/code.py')で実行します- コードと実行結果の両方を返します
ローカル開発用に、プロジェクトルートへ .dev.vars ファイルを作成します。
echo "ANTHROPIC_API_KEY=your_api_key_here" > .dev.varsyour_api_key_here を、Anthropic Console ↗ で取得した実際の API キーに置き換えます。
開発サーバーを起動します。
npm run devcurl でテストします。
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": ""
}Worker をデプロイします。
npx wrangler deploy次に、Anthropic API キーを本番のシークレットとして設定します。
npx wrangler secret put ANTHROPIC_API_KEYプロンプトが表示されたら、Anthropic Console ↗ の API キーを貼り付けます。
さまざまな質問を試します。
# 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 コードを生成します
- 分離されたサンドボックスで安全に実行します
- エラー処理つきで結果を返します
- Workers AI を使ったコードインタープリター - Cloudflare のネイティブ AI モデルと公式パッケージを使う
- AI でデータを分析する - データ分析向けに pandas と matplotlib を追加する
- コードインタープリター API -
execの代わりに組み込みのコードインタープリターを使う - 出力のストリーミング - 実行の進捗をリアルタイムで表示する
- API リファレンス - 利用できるすべてのメソッドを確認する
- Anthropic Claude のドキュメント ↗
- Workers AI - Cloudflare 組み込みのモデルを使う
- workers-ai-provider パッケージ ↗ - 公式の Workers AI 連携