跳转到内容
搜索文档

构建 AI 代码执行器

最后更新 查看 MarkdownAgent 设置

使用 Sandbox SDK 和 Claude 构建 AI 驱动的代码执行系统。将自然语言问题转为 Python 代码,安全执行并返回结果。

预计完成时间: 20 分钟

你将构建的内容

一个 API:接受类似「第 100 个斐波那契数是多少?」的问题,使用 Claude 生成 Python 代码,在隔离沙箱中执行,并返回结果。

前提条件

  1. 注册 Cloudflare 账户
  2. 安装 Node.js

Node.js 版本管理器

使用 Voltanvm 等 Node 版本管理器,以避免权限问题并切换 Node.js 版本。本指南后续将介绍的 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. 通过 POST 到 /execute 接收问题
  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 key。

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 key 设为生产环境 secret:

npx wrangler secret put ANTHROPIC_API_KEY

出现提示时,粘贴来自 Anthropic Console 的 API key。

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 代码
  • 在隔离沙箱中安全执行代码
  • 返回带错误处理的结果

后续步骤

相关资源

这篇文档对您有帮助吗?