|
| 1 | +--- |
| 2 | +pcx_content_type: tutorial |
| 3 | +title: Build an AI code executor |
| 4 | +difficulty: Beginner |
| 5 | +products: |
| 6 | + - Workers |
| 7 | + - Sandbox |
| 8 | +tags: |
| 9 | + - AI |
| 10 | + - Python |
| 11 | + - Security |
| 12 | +sidebar: |
| 13 | + order: 1 |
| 14 | +description: Build an AI code execution system that safely runs Python code generated by Claude. |
| 15 | +--- |
| 16 | + |
| 17 | +import { Render, PackageManagers } from "~/components"; |
| 18 | + |
| 19 | +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. |
| 20 | + |
| 21 | +**Time to complete:** 20 minutes |
| 22 | + |
| 23 | +## What you'll build |
| 24 | + |
| 25 | +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. |
| 26 | + |
| 27 | +## Prerequisites |
| 28 | + |
| 29 | +<Render file="prereqs" product="workers" /> |
| 30 | + |
| 31 | +You'll also need: |
| 32 | +- An [Anthropic API key](https://console.anthropic.com/) for Claude |
| 33 | +- [Docker](https://www.docker.com/) running locally |
| 34 | + |
| 35 | +## 1. Create your project |
| 36 | + |
| 37 | +Create a new Sandbox SDK project: |
| 38 | + |
| 39 | +<PackageManagers |
| 40 | + type="create" |
| 41 | + pkg="cloudflare@latest" |
| 42 | + args={"ai-code-executor --template=cloudflare/sandbox-sdk/examples/minimal"} |
| 43 | +/> |
| 44 | + |
| 45 | +```sh |
| 46 | +cd ai-code-executor |
| 47 | +``` |
| 48 | + |
| 49 | +## 2. Install dependencies |
| 50 | + |
| 51 | +Install the Anthropic SDK: |
| 52 | + |
| 53 | +<PackageManagers pkg="@anthropic-ai/sdk" /> |
| 54 | + |
| 55 | +## 3. Build your code executor |
| 56 | + |
| 57 | +Replace the contents of `src/index.ts`: |
| 58 | + |
| 59 | +```typescript |
| 60 | +import { getSandbox, type Sandbox } from '@cloudflare/sandbox'; |
| 61 | +import Anthropic from '@anthropic-ai/sdk'; |
| 62 | + |
| 63 | +export { Sandbox } from '@cloudflare/sandbox'; |
| 64 | + |
| 65 | +interface Env { |
| 66 | + Sandbox: DurableObjectNamespace<Sandbox>; |
| 67 | + ANTHROPIC_API_KEY: string; |
| 68 | +} |
| 69 | + |
| 70 | +export default { |
| 71 | + async fetch(request: Request, env: Env): Promise<Response> { |
| 72 | + if (request.method !== 'POST' || new URL(request.url).pathname !== '/execute') { |
| 73 | + return new Response('POST /execute with { "question": "your question" }'); |
| 74 | + } |
| 75 | + |
| 76 | + try { |
| 77 | + const { question } = await request.json(); |
| 78 | + |
| 79 | + if (!question) { |
| 80 | + return Response.json({ error: 'Question is required' }, { status: 400 }); |
| 81 | + } |
| 82 | + |
| 83 | + // Use Claude to generate Python code |
| 84 | + const anthropic = new Anthropic({ apiKey: env.ANTHROPIC_API_KEY }); |
| 85 | + const codeGeneration = await anthropic.messages.create({ |
| 86 | + model: 'claude-sonnet-4-5', |
| 87 | + max_tokens: 1024, |
| 88 | + messages: [{ |
| 89 | + role: 'user', |
| 90 | + content: `Generate Python code to answer: "${question}" |
| 91 | +
|
| 92 | +Requirements: |
| 93 | +- Use only Python standard library |
| 94 | +- Print the result using print() |
| 95 | +- Keep code simple and safe |
| 96 | +
|
| 97 | +Return ONLY the code, no explanations.` |
| 98 | + }], |
| 99 | + }); |
| 100 | + |
| 101 | + const generatedCode = codeGeneration.content[0]?.type === 'text' |
| 102 | + ? codeGeneration.content[0].text |
| 103 | + : ''; |
| 104 | + |
| 105 | + if (!generatedCode) { |
| 106 | + return Response.json({ error: 'Failed to generate code' }, { status: 500 }); |
| 107 | + } |
| 108 | + |
| 109 | + // Execute the code in a sandbox |
| 110 | + const sandbox = getSandbox(env.Sandbox, 'demo-user'); |
| 111 | + await sandbox.writeFile('/tmp/code.py', generatedCode); |
| 112 | + const result = await sandbox.exec('python /tmp/code.py'); |
| 113 | + |
| 114 | + return Response.json({ |
| 115 | + success: result.success, |
| 116 | + question, |
| 117 | + code: generatedCode, |
| 118 | + output: result.stdout, |
| 119 | + error: result.stderr |
| 120 | + }); |
| 121 | + |
| 122 | + } catch (error: any) { |
| 123 | + return Response.json( |
| 124 | + { error: 'Internal server error', message: error.message }, |
| 125 | + { status: 500 } |
| 126 | + ); |
| 127 | + } |
| 128 | + }, |
| 129 | +}; |
| 130 | +``` |
| 131 | + |
| 132 | +**How it works:** |
| 133 | +1. Receives a question via POST to `/execute` |
| 134 | +2. Uses Claude to generate Python code |
| 135 | +3. Writes code to `/tmp/code.py` in the sandbox |
| 136 | +4. Executes with `sandbox.exec('python /tmp/code.py')` |
| 137 | +5. Returns both the code and execution results |
| 138 | + |
| 139 | +## 4. Set your Anthropic API key |
| 140 | + |
| 141 | +Store your Anthropic API key as a secret: |
| 142 | + |
| 143 | +```sh |
| 144 | +npx wrangler secret put ANTHROPIC_API_KEY |
| 145 | +``` |
| 146 | + |
| 147 | +Paste your API key from the [Anthropic Console](https://console.anthropic.com/) when prompted. |
| 148 | + |
| 149 | +## 5. Test locally |
| 150 | + |
| 151 | +Start the development server: |
| 152 | + |
| 153 | +```sh |
| 154 | +npm run dev |
| 155 | +``` |
| 156 | + |
| 157 | +:::note |
| 158 | +First run builds the Docker container (2-3 minutes). Subsequent runs are much faster. |
| 159 | +::: |
| 160 | + |
| 161 | +Test with curl: |
| 162 | + |
| 163 | +```sh |
| 164 | +curl -X POST http://localhost:8787/execute \ |
| 165 | + -H "Content-Type: application/json" \ |
| 166 | + -d '{"question": "What is the 10th Fibonacci number?"}' |
| 167 | +``` |
| 168 | + |
| 169 | +Response: |
| 170 | + |
| 171 | +```json |
| 172 | +{ |
| 173 | + "success": true, |
| 174 | + "question": "What is the 10th Fibonacci number?", |
| 175 | + "code": "def fibonacci(n):\n if n <= 1:\n return n\n return fibonacci(n-1) + fibonacci(n-2)\n\nprint(fibonacci(10))", |
| 176 | + "output": "55\n", |
| 177 | + "error": "" |
| 178 | +} |
| 179 | +``` |
| 180 | + |
| 181 | +## 6. Deploy |
| 182 | + |
| 183 | +Deploy your Worker: |
| 184 | + |
| 185 | +```sh |
| 186 | +npx wrangler deploy |
| 187 | +``` |
| 188 | + |
| 189 | +:::caution |
| 190 | +After first deployment, wait 2-3 minutes for container provisioning. Check status with `npx wrangler containers list`. |
| 191 | +::: |
| 192 | + |
| 193 | +## 7. Test your deployment |
| 194 | + |
| 195 | +Try different questions: |
| 196 | + |
| 197 | +```sh |
| 198 | +# Factorial |
| 199 | +curl -X POST https://ai-code-executor.YOUR_SUBDOMAIN.workers.dev/execute \ |
| 200 | + -H "Content-Type: application/json" \ |
| 201 | + -d '{"question": "Calculate the factorial of 5"}' |
| 202 | + |
| 203 | +# Statistics |
| 204 | +curl -X POST https://ai-code-executor.YOUR_SUBDOMAIN.workers.dev/execute \ |
| 205 | + -H "Content-Type: application/json" \ |
| 206 | + -d '{"question": "What is the mean of [10, 20, 30, 40, 50]?"}' |
| 207 | + |
| 208 | +# String manipulation |
| 209 | +curl -X POST https://ai-code-executor.YOUR_SUBDOMAIN.workers.dev/execute \ |
| 210 | + -H "Content-Type: application/json" \ |
| 211 | + -d '{"question": "Reverse the string \"Hello World\""}' |
| 212 | +``` |
| 213 | + |
| 214 | +## What you built |
| 215 | + |
| 216 | +You created an AI code execution system that: |
| 217 | +- Accepts natural language questions |
| 218 | +- Generates Python code with Claude |
| 219 | +- Executes code securely in isolated sandboxes |
| 220 | +- Returns results with error handling |
| 221 | + |
| 222 | +## Next steps |
| 223 | + |
| 224 | +- [Analyze data with AI](/sandbox/tutorials/analyze-data-with-ai/) - Add pandas and matplotlib for data analysis |
| 225 | +- [Code Interpreter API](/sandbox/api/interpreter/) - Use the built-in code interpreter instead of exec |
| 226 | +- [Streaming output](/sandbox/guides/streaming-output/) - Show real-time execution progress |
| 227 | +- [API reference](/sandbox/api/) - Explore all available methods |
| 228 | + |
| 229 | +## Related resources |
| 230 | + |
| 231 | +- [Anthropic Claude documentation](https://docs.anthropic.com/) |
| 232 | +- [Workers AI](/workers-ai/) - Use Cloudflare's built-in models |
0 commit comments