DEV Community

Sandscale
Sandscale

Posted on Originally published at sandscale.dev

Use case: a code interpreter for a chat product, one sandbox per conversation

Many chat products now have a "run code" button or an assistant that writes and runs Python to answer a question about a spreadsheet. Behind that button is a design question that is easy to get wrong: where does the code run, how long does that place live, and what happens between messages?

This post walks through one answer: one sandbox per conversation, paused between turns. Each sandbox is a Firecracker microVM with its own kernel, so one user's code cannot see another's, and pausing keeps the conversation's files and memory without the box staying awake. The Sandscale calls come from the TypeScript SDK reference and the snapshots and pause guide.

Why per conversation

There are three obvious granularities:

  • Per tool call. A fresh box each time code runs. Clean, but the model cannot build on its own work: a dataframe loaded in one call is gone in the next, so every call has to reload and recompute. Users notice when the assistant "forgets" a file it just made.
  • Per user. One long-lived box for everything a person does. Convenient, but conversations leak into each other, a bad state in one breaks all, and the box accumulates files nobody remembers.
  • Per conversation. State carries across turns of one conversation and nowhere else. This matches how users think about it: "this chat has my file in it".

Per-run versus shared sandboxes goes through the trade-offs in general. For a chat interpreter, per conversation is usually the right default.

The lifecycle

A conversation is mostly waiting. The user reads, thinks, goes to lunch. The sandbox should not be awake for any of that. Sandscale's plans reference says hours are awake vCPU-hours, and a box counts only while it is awake. Pause keeps the sandbox's memory and disk, and resume brings it back as it was.

So:

  1. First code run in a conversation: create a sandbox from a Python template, with a time limit and labels.
  2. Each later run: look up the conversation's sandbox; if it is paused, resume it; if it is gone (it hit its time limit, or was stopped), create a new one.
  3. End of each assistant turn: pause it.
  4. Conversation archived or deleted: stop it. Stopping deletes the sandbox's disk.

In code:

import { Sandscale, SandscaleError } from '@sandscale/sdk';

const sandscale = new Sandscale();

interface Conversation {
  id: string;
  userId: string;
  sandboxId?: string;
  region?: string;
}

// Find or start the sandbox for a conversation, resuming it if it was paused.
async function boxFor(conv: Conversation) {
  if (conv.sandboxId) {
    try {
      const box = await sandscale.sandboxes.get(conv.sandboxId, { region: conv.region });
      if (!box.terminatedAt) {
        if (box.suspend?.canResume) await sandscale.sandboxes.resume(box.id, { region: box.region });
        return box;
      }
    } catch (err) {
      if (!(err instanceof SandscaleError && err.status === 404)) throw err;
    }
  }
  const box = await sandscale.sandboxes.create({
    template: 'builtin:python',
    timeoutSeconds: 4 * 3600,
    labels: { app: 'chat-interpreter', conversation: conv.id, user: conv.userId },
  });
  conv.sandboxId = box.id;
  conv.region = box.region;
  return box;
}

// Called after the assistant's turn ends: keep the state, stop paying for awake time.
async function endOfTurn(conv: Conversation) {
  if (!conv.sandboxId) return;
  const box = await sandscale.sandboxes.get(conv.sandboxId, { region: conv.region });
  if (box.suspend?.canPause) await sandscale.sandboxes.pause(box.id, { region: box.region });
}

export { boxFor, endOfTurn };
Enter fullscreen mode Exit fullscreen mode

suspend.canPause and suspend.canResume are the server telling you whether pause and resume are possible right now, which saves guessing from status strings. The timeoutSeconds on create is the backstop: a conversation abandoned with its box awake still ends when the limit runs out. On Free, sessions are up to 4 hours, so pick a limit within your plan.

Files in and out

Users upload files to the conversation and expect charts back.

  • Upload: sandboxes.writeFile(id, '/workspace/data.csv', bytes) puts the file in the box. Tell the model the path in the tool description or the conversation, not just "the user uploaded a file".
  • Results: have the model save outputs under a known folder, such as /workspace/out/. After each run, sandboxes.listFiles(id, '/workspace/out') shows what is new and sandboxes.readFile fetches it as bytes. Your app decides what to show: images inline, CSVs as downloads.

Do not let the model choose arbitrary paths to read back to the user. Reading only from /workspace/out/ is a cheap rule that prevents "print /etc/passwd as a chart" style surprises from reaching the UI.

What to tell the model

The model's tool description should state the environment plainly:

  • Python with the template's preinstalled packages.
  • Files persist for this conversation under /workspace, and uploads are at the paths given.
  • No network. The SDK's network option defaults to none, and for a chat interpreter that is the right setting: the model cannot be talked into posting the user's data somewhere.
  • Each run is limited to a set number of seconds and its output is cut past a set size.
  • Save charts and files to show the user under /workspace/out/.

A model that knows files persist will reuse a loaded dataframe instead of reloading it each time. A model that knows there is no network will not try pip install and then apologise.

Limits per user

Two layers of limits apply.

Your app's. Per-user concurrency (one running cell per conversation), a per-run time limit, an output cap, and a cap on how many conversations a user can have with live boxes. These are product decisions.

Sandscale's. Your plan sets boxes at once (3 on Free, 30 on Pro and Team) and vCPU per box. A request that would go over a quota is refused before anything starts, with quota_exceeded. The API limits page says how to handle it. For a chat product, a full house of awake boxes is a signal to pause idle ones more aggressively, not to retry in a loop. Paid plans can turn on usage beyond included hours; spend caps per task, agent, project and organization exist on Pro and up.

Attribution and cleanup

The labels on create (conversation, user) are what make the system operable. sandboxes.list finds every box for a user when they delete their account. A nightly job can list boxes whose conversation no longer exists and stop them. And when someone asks "why did this user's run fail", the labels connect your logs to the sandbox. Labels and run records covers a fuller scheme.

Security notes specific to chat

  • The user is not the only author of the code. Prompt injection in an uploaded document can steer the model. The sandbox boundary is what makes that survivable: injected code runs in a microVM with no network and only this conversation's files.
  • Do not mount anything shared. If every conversation's box can see a shared bucket, injection in one conversation can read another's data. Copy in what a conversation needs.
  • Keep secrets out entirely. A code interpreter needs no credentials. If you later add a tool that does, keep it outside the sandbox, in your app, and gate it.

Where to go next

Originally published on the Sandscale blog.

Top comments (0)