Skip to main content
In this guide we’ll add a code interpreter tool to a Vercel AI SDK chat app. When a user asks a question that needs computation — math, data analysis, statistics — the model writes code and sends it to a fresh EphemeralBox to run. The sandbox is isolated, disposable, and auto-expires when the session ends.

1. Installation

Get a Box API key from the Upstash Console and add your environment variables:
.env.local

2. Create the API route

Each time the model decides to run code, the tool spins up a fresh EphemeralBox, executes the snippet, and deletes the box immediately after. Nothing persists between tool calls.
app/api/chat/route.ts
ttl: 120 means the box auto-deletes after 2 minutes even if the finally block is skipped. For longer-running scripts, increase this value.

3. Add a simple UI

Wire up a simple chat UI with useChat from the AI SDK. This UI also will display tool calls so that we can test the functionality.
app/page.tsx

4. Try it

Start your Next.js app and ask anything that needs real computation:
“What is the square root of 144 plus 25 factorial?”
The model writes a Python snippet, the executeSandboxCode tool fires, a fresh EphemeralBox boots, the code runs, and the result streams back — all within a single response turn.
Every tool call gets its own isolated box, so a crash in one never affects the others. The timeout: 10_000 on exec.code cuts off the HTTP call after 10 seconds — without it, an infinite loop would hang until the backend times out or the ttl deletes the box. Raise the timeout for long-running scripts, but always set one.