Code interpreter with Workers AI

Last updated Oct 12, 2026 Note

This page documents Sandbox SDK 0.x for existing applications. For new applications, refer to Build an AI code interpreter. To move an existing application to @cloudflare/sandbox 1.0, refer to Migrate from Sandbox SDK 0.x.

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

What you'll build

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.

Prerequisites

  1. Sign up for a Cloudflare account ↗︎.
  2. Install Node.js ↗︎.

<details>

<summary>

Node.js version manager

</summary>

Use <a href="https://viteplus.dev/guide/env">Vite+ (<code>vp env</code>) ↗︎</a> to install and manage Node.js versions.

For supported Node.js versions, refer to the <a href="https://developers.cloudflare.com/workers/wrangler/install-and-update/#install-wrangler">Wrangler system requirements</a>.

</details>

You'll also need:

1. Create your project

Create a new Sandbox SDK project:

npmyarnpnpm

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

2. Review the implementation

The template includes a complete implementation using the latest best practices. Let's examine the key components:

// 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";
}

Key improvements over direct REST API calls:

  • Official packages: Uses workers-ai-provider instead of manual API calls
  • Vercel AI SDK: Leverages generateText() and tool() for clean function calling
  • No API keys: Uses native AI binding instead of environment variables
  • Type safety: Full TypeScript support with proper typing

3. Check your configuration

The template includes the proper Wrangler configuration:

{
  "name": "sandbox-code-interpreter-example",
  "main": "src/index.ts",
  "upload_source_maps": true,
  // Set this to today's date
  "compatibility_date": "2026-10-27",
  "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"
upload_source_maps = true
# Set this to today's date
compatibility_date = "2026-10-27"

[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"

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

4. Test locally

Start the development server:

npm run dev

Note

First run builds the Docker container (2-3 minutes). Subsequent runs are much faster.

Test with 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. Deploy

Deploy your Worker:

npx wrangler deploy

Caution

After first deployment, wait 2-3 minutes for container provisioning before making requests.

6. Test your deployment

Try more complex queries:

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

How it works

  1. User input: Send natural language prompts to the /run endpoint
  2. AI decision: GPT-OSS receives the prompt with an execute_python tool available
  3. Smart execution: Model decides whether Python code execution is needed
  4. Sandbox isolation: Code runs in isolated Cloudflare Sandbox containers
  5. AI explanation: Results are integrated back into the AI's response for final output

What you built

You deployed a sophisticated code interpreter that:

  • Native Workers AI integration: Uses the official workers-ai-provider package 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

Next steps

Was this helpful?

YesNo

On this page

Code interpreter with Workers AI - 图1Docs

{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/sandbox/sdk/tutorials/workers-ai-code-interpreter/#page","headline":"Code interpreter with Workers AI","description":"Build a Sandbox SDK 0.x code interpreter using the Workers AI GPT-OSS model and the workers-ai-provider package.","url":"https://developers.cloudflare.com/sandbox/sdk/tutorials/workers-ai-code-interpreter/","inLanguage":"en","image":"https://developers.cloudflare.com/sandbox/sdk/tutorials/workers-ai-code-interpreter/og.png?v=09a347cf9eb5745f","dateModified":"2026-10-12","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}


description: Serverless live and on-demand video streaming with adaptive bitrate encoding and global delivery. title: Cloudflare Stream image: https://developers.cloudflare.com/stream/og.png?v=0c352f7f2b0adf44


Skip to content

Documentation Index
Fetch the complete documentation index at: https://developers.cloudflare.com/stream/llms.txt
Use this file to discover all available pages before exploring further.