Code interpreter with Workers AI
Build a powerful code interpreter that gives the gpt-oss model on Workers AI the ability to execute Python code using the Cloudflare Sandbox SDK.
Time to complete: 15 minutes
A Cloudflare Worker that accepts natural language prompts, uses GPT-OSS to decide when Python code execution is needed, runs the code in isolated sandboxes, and returns results with AI-powered explanations.
- Sign up for a Cloudflare account ↗.
- Install
Node.js↗.
Node.js version manager
Use a Node version manager like Volta ↗ or nvm ↗ to avoid permission issues and change Node.js versions. Wrangler, discussed later in this guide, requires a Node version of 16.17.0 or later.
You'll also need:
- Docker ↗ running locally
Create a new Sandbox SDK project:
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-interpreterThe template includes a complete implementation using the latest best practices. Let's examine the key components:
// src/index.tsimport { 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";}Key improvements over direct REST API calls:
- Official packages: Uses
workers-ai-providerinstead of manual API calls - Vercel AI SDK: Leverages
generateText()andtool()for clean function calling - No API keys: Uses native AI binding instead of environment variables
- Type safety: Full TypeScript support with proper typing
The template includes the proper Wrangler configuration:
{ "name": "sandbox-code-interpreter-example", "main": "src/index.ts", "compatibility_date": "2025-05-06", "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"compatibility_date = "2025-05-06"
[ai]binding = "AI"
[[containers]]class_name = "Sandbox"image = "./Dockerfile"name = "sandbox"max_instances = 1instance_type = "basic"
[[durable_objects.bindings]]class_name = "Sandbox"name = "Sandbox"Configuration highlights:
- AI binding: Enables direct access to Workers AI models
- Container setup: Configures sandbox container with Dockerfile
- Durable Objects: Provides persistent sandboxes with state management
Start the development server:
npm run devTest with curl:
# Simple calculationcurl -X POST http://localhost:8787/run \ -H "Content-Type: application/json" \ -d '{"input": "Calculate 5 factorial using Python"}'
# Complex operationscurl -X POST http://localhost:8787/run \ -H "Content-Type: application/json" \ -d '{"input": "Use Python to find all prime numbers under 20"}'
# Data analysiscurl -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"}'Deploy your Worker:
npx wrangler deployTry more complex queries:
# Data visualization preparationcurl -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 implementationcurl -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 computationcurl -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]"}'- User input: Send natural language prompts to the
/runendpoint - AI decision: GPT-OSS receives the prompt with an
execute_pythontool available - Smart execution: Model decides whether Python code execution is needed
- Sandbox isolation: Code runs in isolated Cloudflare Sandbox containers
- AI explanation: Results are integrated back into the AI's response for final output
You deployed a sophisticated code interpreter that:
- Native Workers AI integration: Uses the official
workers-ai-providerpackage for seamless integration - Function calling: Leverages Vercel AI SDK for clean tool definitions and execution
- Secure execution: Runs Python code in isolated sandbox containers
- Intelligent responses: Combines AI reasoning with code execution results
- Analyze data with AI - Add pandas and matplotlib for advanced data analysis
- Code Interpreter API - Use the built-in code interpreter with structured outputs
- Streaming output - Show real-time execution progress
- API reference - Explore all available sandbox methods
- Workers AI - Learn about Cloudflare's AI platform
- workers-ai-provider package ↗ - Official Workers AI integration
- Vercel AI SDK ↗ - Universal toolkit for AI applications
- GPT-OSS model documentation - Model details and capabilities
Was this helpful?
- Resources
- API
- New to Cloudflare?
- Directory
- Sponsorships
- Open Source
- Support
- Help Center
- System Status
- Compliance
- GDPR
- Company
- cloudflare.com
- Our team
- Careers
- © 2026 Cloudflare, Inc.
- Privacy Policy
- Terms of Use
- Report Security Issues
- Trademark
-