Build an AI code executor

Last updated Oct 21, 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 an AI-powered code execution system using Sandbox SDK and Claude. Turn natural language questions into Python code, execute it securely, and return results.

Time to complete: 20 minutes

What you'll build

An API that accepts questions like "What's the 100th Fibonacci number?", uses Claude to generate Python code, executes it in an isolated sandbox, and returns the results.

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 -- ai-code-executor --template=cloudflare/sandbox-sdk/examples/minimal#v0
yarn create cloudflare ai-code-executor --template=cloudflare/sandbox-sdk/examples/minimal#v0
pnpm create cloudflare@latest ai-code-executor --template=cloudflare/sandbox-sdk/examples/minimal#v0
cd ai-code-executor

2. Install dependencies

Install the Anthropic SDK:

npmyarnpnpmbun

npm i @anthropic-ai/sdk
yarn add @anthropic-ai/sdk
pnpm add @anthropic-ai/sdk
bun add @anthropic-ai/sdk

3. Build your code executor

Replace the contents of 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 }
            );
        }
    },
};

How it works:

  1. Receives a question via POST to /execute
  2. Uses Claude to generate Python code
  3. Writes code to /tmp/code.py in the sandbox
  4. Executes with sandbox.exec('python /tmp/code.py')
  5. Returns both the code and execution results

4. Set up local environment variables

Create a .dev.vars file in your project root for local development:

echo "ANTHROPIC_API_KEY=your_api_key_here" > .dev.vars

Replace your_api_key_here with your actual API key from the Anthropic Console ↗︎.

Note

The .dev.vars file is automatically gitignored and only used during local development with npm run dev.

5. 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:

curl -X POST http://localhost:8787/execute \
  -H "Content-Type: application/json" \
  -d '{"question": "What is the 10th Fibonacci number?"}'

Response:

{
  "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. Deploy

Deploy your Worker:

npx wrangler deploy

Then set your Anthropic API key as a production secret:

npx wrangler secret put ANTHROPIC_API_KEY

Paste your API key from the Anthropic Console ↗︎ when prompted.

Caution

After first deployment, wait 2-3 minutes for container provisioning. Check status with npx wrangler containers list.

7. Test your deployment

Try different questions:

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

What you built

You created an AI code execution system that:

  • Accepts natural language questions
  • Generates Python code with Claude
  • Executes code securely in isolated sandboxes
  • Returns results with error handling

Next steps

Was this helpful?

YesNo

On this page

Build an AI code executor - 图1Docs

{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/sandbox/sdk/tutorials/ai-code-executor/#page","headline":"Build an AI code executor","description":"Use Claude to generate Python code from natural language and run it in Sandbox SDK 0.x sandboxes.","url":"https://developers.cloudflare.com/sandbox/sdk/tutorials/ai-code-executor/","inLanguage":"en","image":"https://developers.cloudflare.com/sandbox/sdk/tutorials/ai-code-executor/og.png?v=2376b752f8ce3735","dateModified":"2026-10-21","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: Upload CSV files, generate analysis code with Claude, and return visualizations with the Sandbox SDK 0.x. title: Analyze data with AI image: https://developers.cloudflare.com/sandbox/sdk/tutorials/analyze-data-with-ai/og.png?v=e08aad56cdaa5931


Skip to content

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