跳转到内容
搜索文档

使用 Workers AI 的代码解释器

最后更新 查看 MarkdownAgent 设置

构建一个强大的代码解释器:让 Workers AI 上的 gpt-oss 模型 能够通过 Cloudflare Sandbox SDK 执行 Python 代码。

预计完成时间: 15 分钟

你将构建的内容

一个 Cloudflare Worker:接受自然语言提示,由 GPT-OSS 决定何时需要执行 Python 代码,在隔离沙箱中运行代码,并返回带 AI 解释的结果。

前提条件

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

Node.js 版本管理器

使用 Voltanvm 等 Node 版本管理器,以避免权限问题并切换 Node.js 版本。本指南后续将介绍的 Wrangler 需要 Node 版本 16.17.0 或更高。

你还需要:

1. 创建项目

创建新的 Sandbox SDK 项目:

npm create cloudflare@latest -- workers-ai-interpreter --template=cloudflare/sandbox-sdk/examples/code-interpreter
cd workers-ai-interpreter

2. 查看实现

该模板包含采用最新最佳实践的完整实现。我们来看关键部分:

// 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 支持和正确类型

3. 检查配置

该模板包含正确的 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:提供带状态管理的持久沙箱

4. 本地测试

启动开发服务器:

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"}'

5. 部署

部署你的 Worker:

npx wrangler deploy

6. 测试部署

尝试更复杂的查询:

# 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]"}'

工作原理

  1. 用户输入:向 /run 端点发送自然语言提示
  2. AI 决策:GPT-OSS 收到提示,并可使用 execute_python 工具
  3. 智能执行:模型决定是否需要执行 Python 代码
  4. 沙箱隔离:代码在隔离的 Cloudflare Sandbox container 中运行
  5. AI 解释:结果被整合回 AI 的响应中,形成最终输出

你构建了什么

你部署了一个功能完整的代码解释器,它具备:

  • 原生 Workers AI 集成:使用官方 workers-ai-provider 软件包实现无缝集成
  • 函数调用:使用 Vercel AI SDK 清晰地定义和执行工具
  • 安全执行:在隔离的沙箱 container 中运行 Python 代码
  • 智能响应:将 AI 推理与代码执行结果结合

后续步骤

相关资源

这篇文档对您有帮助吗?