When you let AI models generate and execute code, you need a secure execution environment. The AI might produce code that consumes excessive resources, accesses sensitive files, makes unwanted network requests, or runs destructive commands.
Vercel Sandbox provides isolation, resource limits, and automatic timeouts that make it safe to run untrusted code. This guide shows you how to build an "AI code runner" that takes a task, generates code using the AI SDK with AI Gateway, and executes it in a sandbox.
Before you begin, make sure you have:
- Vercel CLI installed (
pnpm install -g vercel) - Node.js 22 or later
- A Vercel project to link your sandbox to and generate an OIDC token
Create a new directory and install dependencies:
Link your project to Vercel and pull the OIDC token. This token authenticates both Sandbox and AI Gateway:
Create a file called index.ts and add the code below. The script:
- Takes a task description from the command line
- Sends it to Claude via AI Gateway
- Writes the generated code to an isolated sandbox
- Executes it and captures the output
Run the script with a task description:
Expected output:
Try other tasks:
The script uses multiple safety layers to handle untrusted code:
Sandbox isolation: Each execution runs in a fresh microVM with limited resources and a short timeout. If the code hangs or tries to use too much memory, the sandbox terminates it.
Prompt constraints: The system prompt instructs Claude to avoid dangerous operations: no file system access, no network requests, no environment variables. While not foolproof, this reduces the likelihood of problematic code.
Error capture: The sandbox captures both stdout and stderr, so you can inspect failures without them affecting your host system.
- Add snapshots to speed up repeated executions
- Use Sandbox.get() to reuse sandboxes across requests
- Explore AI SDK features like streaming and tool calling
- Learn about AI Gateway model routing and fallbacks