使用 Sandbox SDK 和 Claude 构建 AI 驱动的代码执行系统。将自然语言问题转为 Python 代码,安全执行并返回结果。
预计完成时间: 20 分钟
一个 API:接受类似「第 100 个斐波那契数是多少?」的问题,使用 Claude 生成 Python 代码,在隔离沙箱中执行,并返回结果。
- 注册 Cloudflare 账户 ↗。
- 安装
Node.js↗。
Node.js 版本管理器
使用 Volta ↗ 或 nvm ↗ 等 Node 版本管理器,以避免权限问题并切换 Node.js 版本。本指南后续将介绍的 Wrangler 需要 Node 版本 16.17.0 或更高。
你还需要:
- 用于 Claude 的 Anthropic API key ↗
- 本地正在运行的 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-executor安装 Anthropic SDK:
npm i @anthropic-ai/sdkyarn add @anthropic-ai/sdkpnpm add @anthropic-ai/sdkbun add @anthropic-ai/sdk替换 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 }
);
}
},
};工作原理:
- 通过 POST 到
/execute接收问题 - 使用 Claude 生成 Python 代码
- 将代码写入沙箱中的
/tmp/code.py - 使用
sandbox.exec('python /tmp/code.py')执行 - 同时返回代码和执行结果
在项目根目录创建 .dev.vars 文件,用于本地开发:
echo "ANTHROPIC_API_KEY=your_api_key_here" > .dev.vars将 your_api_key_here 替换为你在 Anthropic Console ↗ 中的实际 API key。
启动开发服务器:
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": ""
}部署你的 Worker:
npx wrangler deploy然后将 Anthropic API key 设为生产环境 secret:
npx wrangler secret put ANTHROPIC_API_KEY出现提示时,粘贴来自 Anthropic Console ↗ 的 API key。
尝试不同问题:
# 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 进行数据分析
- Code Interpreter API - 使用内置代码解释器,而不是 exec
- 流式输出 - 展示实时执行进度
- API 参考 - 浏览所有可用方法
- Anthropic Claude 文档 ↗
- Workers AI - 使用 Cloudflare 内置模型
- workers-ai-provider 软件包 ↗ - 官方 Workers AI 集成