EphemeralBox to run. The sandbox is isolated, disposable, and auto-expires when the session ends.
1. Installation
.env.local
2. Create the API route
Each time the model decides to run code, the tool spins up a freshEphemeralBox, 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 withuseChat 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.
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.