构建一个强大的代码解释器:让 Workers AI 上的 gpt-oss 模型 能够通过 Cloudflare Sandbox SDK 执行 Python 代码。
预计完成时间: 15 分钟
一个 Cloudflare Worker:接受自然语言提示,由 GPT-OSS 决定何时需要执行 Python 代码,在隔离沙箱中运行代码,并返回带 AI 解释的结果。
- 注册 Cloudflare 账户 ↗。
- 安装
Node.js↗。
Node.js 版本管理器
使用 Volta ↗ 或 nvm ↗ 等 Node 版本管理器,以避免权限问题并切换 Node.js 版本。本指南后续将介绍的 Wrangler 需要 Node 版本 16.17.0 或更高。
你还需要:
- 本地正在运行的 Docker ↗
创建新的 Sandbox SDK 项目:
npm create cloudflare@latest -- workers-ai-interpreter --template=cloudflare/sandbox-sdk/examples/code-interpreteryarn create cloudflare workers-ai-interpreter --template=cloudflare/sandbox-sdk/examples/code-interpreterpnpm create cloudflare@latest workers-ai-interpreter --template=cloudflare/sandbox-sdk/examples/code-interpretercd workers-ai-interpreter该模板包含采用最新最佳实践的完整实现。我们来看关键部分:
// src/index.ts
import { getSandbox } from "@cloudflare/sandbox";
import { generateText, stepCountIs, tool } from "ai";
import { createWorkersAI } from "workers-ai-provider";
import { z } from "zod";
const MODEL = "@cf/openai/gpt-oss-120b" as const;
async function handleAIRequest(input: string, env: Env): Promise<string> {
const workersai = createWorkersAI({ binding: env.AI });
const result = await generateText({
model: workersai(MODEL),
messages: [{ role: "user", content: input }],
tools: {
execute_python: tool({
description: "Execute Python code and return the output",
inputSchema: z.object({
code: z.string().describe("The Python code to execute"),
}),
execute: async ({ code }) => {
return executePythonCode(env, code);
},
}),
},
stopWhen: stepCountIs(5),
});
return result.text || "No response generated";
}相对直接 REST API 调用的主要改进:
- 官方软件包:使用
workers-ai-provider,而不是手动调用 API - Vercel AI SDK:使用
generateText()和tool()实现清晰的函数调用 - 无需 API key:使用原生 AI 绑定(binding),而不是环境变量
- 类型安全:完整的 TypeScript 支持和正确类型
该模板包含正确的 Wrangler 配置:
{
"name": "sandbox-code-interpreter-example",
"main": "src/index.ts",
// Set this to today's date
"compatibility_date": "2026-08-17",
"ai": {
"binding": "AI"
},
"containers": [
{
"class_name": "Sandbox",
"image": "./Dockerfile",
"name": "sandbox",
"max_instances": 1,
"instance_type": "basic"
}
],
"durable_objects": {
"bindings": [
{
"class_name": "Sandbox",
"name": "Sandbox"
}
]
}
}name = "sandbox-code-interpreter-example"
main = "src/index.ts"
# Set this to today's date
compatibility_date = "2026-08-17"
[ai]
binding = "AI"
[[containers]]
class_name = "Sandbox"
image = "./Dockerfile"
name = "sandbox"
max_instances = 1
instance_type = "basic"
[[durable_objects.bindings]]
class_name = "Sandbox"
name = "Sandbox"配置要点:
- AI 绑定(binding):可直接访问 Workers AI 模型
- Container 设置:使用 Dockerfile 配置沙箱 container
- Durable Objects:提供带状态管理的持久沙箱
启动开发服务器:
npm run dev使用 curl 测试:
# Simple calculation
curl -X POST http://localhost:8787/run \
-H "Content-Type: application/json" \
-d '{"input": "Calculate 5 factorial using Python"}'
# Complex operations
curl -X POST http://localhost:8787/run \
-H "Content-Type: application/json" \
-d '{"input": "Use Python to find all prime numbers under 20"}'
# Data analysis
curl -X POST http://localhost:8787/run \
-H "Content-Type: application/json" \
-d '{"input": "Create a list of the first 10 squares and calculate their sum"}'部署你的 Worker:
npx wrangler deploy尝试更复杂的查询:
# Data visualization preparation
curl -X POST https://workers-ai-interpreter.YOUR_SUBDOMAIN.workers.dev/run \
-H "Content-Type: application/json" \
-d '{"input": "Generate sample sales data for 12 months and calculate quarterly totals"}'
# Algorithm implementation
curl -X POST https://workers-ai-interpreter.YOUR_SUBDOMAIN.workers.dev/run \
-H "Content-Type: application/json" \
-d '{"input": "Implement a binary search function and test it with a sorted array"}'
# Mathematical computation
curl -X POST https://workers-ai-interpreter.YOUR_SUBDOMAIN.workers.dev/run \
-H "Content-Type: application/json" \
-d '{"input": "Calculate the standard deviation of [2, 4, 4, 4, 5, 5, 7, 9]"}'- 用户输入:向
/run端点发送自然语言提示 - AI 决策:GPT-OSS 收到提示,并可使用
execute_python工具 - 智能执行:模型决定是否需要执行 Python 代码
- 沙箱隔离:代码在隔离的 Cloudflare Sandbox container 中运行
- AI 解释:结果被整合回 AI 的响应中,形成最终输出
你部署了一个功能完整的代码解释器,它具备:
- 原生 Workers AI 集成:使用官方
workers-ai-provider软件包实现无缝集成 - 函数调用:使用 Vercel AI SDK 清晰地定义和执行工具
- 安全执行:在隔离的沙箱 container 中运行 Python 代码
- 智能响应:将 AI 推理与代码执行结果结合
- 使用 AI 分析数据 - 添加 pandas 和 matplotlib 进行高级数据分析
- Code Interpreter API - 使用内置代码解释器获得结构化输出
- 流式输出 - 展示实时执行进度
- API 参考 - 浏览所有可用沙箱方法
- Workers AI - 了解 Cloudflare 的 AI 平台
- workers-ai-provider 软件包 ↗ - 官方 Workers AI 集成
- Vercel AI SDK ↗ - 面向 AI 应用的通用工具包
- GPT-OSS 模型文档 - 模型详情与能力