---
title: Run research agents, data analysis, and evals on Vercel Sandbox
description: Give a research agent a Python execution tool, analyze datasets, fork parallel trials from one baseline, restrict network access, and resume a workspace across sessions.
keywords: ["Vercel Sandbox","Firecracker VM","Research agent","Python","Vercel Passport"]
url: "https://vercel.com/kb/guide/sandbox-research-workloads"
published: 2026-12-01
last_updated: 2026-12-01
authors: Ben Sabic
install_vercel_plugin: npx plugins add vercel/vercel-plugin
search_with_vercel_cli: npx vercel@latest kb search "<query>"
read_with_vercel_cli: "npx vercel@latest kb inspect sandbox-research-workloads"
---

[Vercel Sandbox](https://vercel.com/docs/sandbox) runs agent-written analysis scripts and eval trials in isolated Firecracker microVMs. Execution is separate from your application, with network policies to restrict outbound connections and credentials brokering to keep API keys outside the sandbox.

Research code often runs before anyone reviews it. Agents generate scripts and install dependencies that can access the data you give them. Use the SDK to supply a job's inputs, run its analysis, and retrieve results. Snapshots let you repeat experiments from the same filesystem state or resume a workspace later.

## How Vercel Sandbox supports research workloads

Each sandbox has its own kernel, filesystem, and network namespace. You can install compatible Linux packages and binaries with root access. The VM boundary separates processes and files; access to external services depends on the network policy and credentials you provide.

Every research run follows the same lifecycle:

1. Call `Sandbox.create()` to boot a microVM from an image or a snapshot. Pass a Git repository as `source` to clone the repository into the sandbox.
   
2. Write input files and install packages.
   
3. Run commands and read the exit code, stdout, and stderr.
   
4. Download result files such as charts, tables, and logs.
   
5. Call `sandbox.stop()` to end the session. Persistent sandboxes save their filesystem for the next session.
   

The following table maps research needs to Vercel Sandbox features and the SDK options that control them.

| Research need                          | Vercel Sandbox feature                                                                                                        | SDK method or option                   |
| -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | -------------------------------------- |
| Run untrusted code                     | Firecracker microVM with a dedicated kernel for each sandbox                                                                  | `Sandbox.create()`                     |
| Use the Python data stack              | [Managed images](https://vercel.com/docs/sandbox/concepts/images) with Python 3.14, `pip`, and `uv`, plus root access         | `image`, `runCommand({ sudo: true })`  |
| Start every trial from the same state  | [Snapshots](https://vercel.com/docs/sandbox/concepts/snapshots) and forks                                                     | `sandbox.snapshot()`, `Sandbox.fork()` |
| Restrict outbound network access       | [Firewall](https://vercel.com/docs/sandbox/concepts/firewall) with deny-all and allowlist policies                            | `networkPolicy`                        |
| Keep API keys away from generated code | Credentials brokering at the firewall                                                                                         | `networkPolicy` with `transform` rules |
| Continue work across days              | [Persistent sandboxes](https://vercel.com/docs/sandbox/concepts/persistent-sandboxes) that resume by name                     | `name`, `Sandbox.getOrCreate()`        |
| Share datasets across runs             | [Vercel Drives](https://vercel.com/docs/sandbox/concepts/drives) mounted as directories                                       | `mounts`                               |
| Run long computations                  | [Sessions](https://vercel.com/docs/sandbox/examples/execute-long-running-tasks) of up to 24 hours on Pro and Enterprise plans | `timeout`, `sandbox.extendTimeout()`   |

Vercel Sandbox fits CPU workloads that finish within a session limit. For the plan limits and the workloads that don't fit, see [Limits and when to use a different tool](#limits-and-when-to-use-a-different-tool).

## Prerequisites

Before you begin, make sure you have a [Vercel account](https://vercel.com/signup) ready. For local development, use Node.js 24+ with the latest [Vercel CLI](https://vercel.com/docs/cli).

## Set up the SDK and run a first sandbox

Create a project directory:

**pnpm**

```bash
mkdir sandbox-research && cd sandbox-research
pnpm init
```

**npm**

```bash
mkdir sandbox-research && cd sandbox-research
npm init -y
```

**yarn**

```bash
mkdir sandbox-research && cd sandbox-research
yarn init -y
```

**bun**

```bash
mkdir sandbox-research && cd sandbox-research
bun init -y
```

Install the Sandbox SDK:

**pnpm**

```bash
pnpm i @vercel/sandbox
```

**npm**

```bash
npm i @vercel/sandbox
```

**yarn**

```bash
yarn add @vercel/sandbox
```

**bun**

```bash
bun add @vercel/sandbox
```

Link the directory to a Vercel project:

```bash
vercel link
vercel env pull
```

When `vercel link` prompts you, create a project or select an existing one. No deployment is required. Run `vercel env pull` to save the development token as `VERCEL_OIDC_TOKEN` in `.env.local`; the Sandbox SDK uses it to authenticate.

The token expires after 12 hours. Run `vercel env pull` again to refresh it if authentication fails. You can also [authenticate with an access token](https://vercel.com/docs/sandbox/concepts/authentication).

Each example is a TypeScript file with an `.mts` extension. To confirm the setup, save the following code as `quickstart.mts`. The script creates a sandbox from the Python image, runs one command, and prints the result:

```typescript
import { Sandbox } from '@vercel/sandbox';

const sandbox = await Sandbox.create({
  image: 'vercel/sandbox/python:3.14',
  persistent: false,
});

try {
  const result = await sandbox.runCommand('python', [
    '-c',
    'import statistics; print(statistics.median([3, 1, 4, 1, 5, 9, 2, 6]))',
  ]);

  console.log(`exit code: ${result.exitCode}`);
  console.log((await result.stdout()).trim());
} finally {
  await sandbox.stop();
}
```

Run the script with Node.js and load the token from `.env.local`. If you use Yarn Plug'n'Play, replace `node` with `yarn node` so Node can find the installed packages:

```bash
node --env-file .env.local --experimental-strip-types quickstart.mts
```

The script prints the exit code and the command output:

```text
exit code: 0
3.5
```

Setting `persistent: false` discards the filesystem when the session stops, which avoids snapshot storage charges for one-off runs. Each session stops automatically after 5 minutes unless you set a longer `timeout`.

Run each executable `.mts` file with the same Node.js command, replacing `quickstart.mts` with its filename. The network policy file exports helpers to import into another script. These examples use the JavaScript SDK; the [Python SDK](https://vercel.com/docs/sandbox/sdk/python) supports the same workflows.

## Use cases for research workloads

The scripts run from your local project. For a deployed agent, add [durable orchestration](https://vercel.com/kb/guide/how-to-run-a-multi-step-research-agent-on-vercel) or use the [research workspace architecture](https://vercel.com/kb/guide/run-research-workspace-vercel).

### Give a research agent a code execution tool

Give the model an AI SDK tool that executes Python in a sandbox and returns the result. The model can use computed values in its answer and read error output to revise a failed script. You still need to check that the generated analysis uses the right data and method.

Install the AI SDK and Zod:

**pnpm**

```bash
pnpm i ai zod
```

**npm**

```bash
npm i ai zod
```

**yarn**

```bash
yarn add ai zod
```

**bun**

```bash
bun add ai zod
```

Save this as `research-agent.mts`. It sends model requests through [AI Gateway](https://vercel.com/docs/ai-gateway) using the same `VERCEL_OIDC_TOKEN` as the Sandbox SDK:

```typescript
import { randomUUID } from 'node:crypto';
import { Sandbox } from '@vercel/sandbox';
import { generateText, isStepCount, tool } from 'ai';
import { z } from 'zod';

const sandbox = await Sandbox.create({
  image: 'vercel/sandbox/python:3.14',
  persistent: false,
  timeout: 15 * 60 * 1000,
  networkPolicy: 'deny-all',
});

const runPython = tool({
  description:
    'Run Python code in an isolated sandbox. ' +
    'Only the Python standard library is available. ' +
    'Returns the exit code, stdout, and stderr.',
  inputSchema: z.object({
    code: z.string().describe('The Python source code to run.'),
  }),
  execute: async ({ code }) => {
    // A unique file name keeps parallel tool calls from overwriting each other.
    const file = `analysis-${randomUUID()}.py`;
    await sandbox.writeFiles([{ path: file, content: code }]);

    const result = await sandbox.runCommand({
      cmd: 'python',
      args: [file],
      timeoutMs: 60_000,
    });

    return {
      exitCode: result.exitCode,
      stdout: (await result.stdout()).slice(0, 10_000),
      stderr: (await result.stderr()).slice(0, 10_000),
    };
  },
});

try {
  const { text } = await generateText({
    model: 'anthropic/claude-sonnet-5.5',
    tools: { runPython },
    stopWhen: isStepCount(10),
    prompt:
      'Estimate pi with a Monte Carlo simulation of 1,000,000 points. ' +
      'Run the code, then report the estimate and its absolute error.',
  });

  console.log(text);
} finally {
  await sandbox.stop();
}
```

The `runPython` tool saves each script under a unique filename and gives it 60 seconds to run. It returns the exit code and output so the model can inspect results or correct a traceback. The network policy blocks outbound connections from the sandbox, but the tool still sends its output back to the model.

The step condition limits the tool loop to 10 steps. Each output string is trimmed to 10,000 characters before it is returned; this limits the tool result sent to the model, not the output generated by the process.

Expect an estimate close to 3.14, with results varying as the model generates different code. To change models, select a language model with tool-calling support from the [AI Gateway model list](https://vercel.com/ai-gateway/models) and replace the model ID.

#### Code execution resources

- Use a [prebuilt](https://ai-sdk.dev/resources/tools/code-execution) [`executeCode`](https://ai-sdk.dev/resources/tools/code-execution) [tool](https://ai-sdk.dev/resources/tools/code-execution) instead of writing your own tool
  
- See how [Interfaze runs model-written code in Vercel Sandbox](https://vercel.com/customers/how-interfaze-serves-50-million-requests-a-month-on-vercel)
  
- Learn [the layers and security practices behind code execution tools](https://vercel.com/i/code-interpreter)
  

### Analyze data and return charts

Upload a dataset with `sandbox.writeFiles()`, run the analysis inside the sandbox, and download result files with `sandbox.downloadFile()`. The analysis code and its dependencies never run on your own machine or server.

This example installs pandas and Matplotlib, calculates month-over-month growth, and saves a chart. Save the code as `analyze-data.mts`:

```typescript
import { Sandbox } from '@vercel/sandbox';

const dataset = `month,signups
2026-01,1180
2026-02,1245
2026-03,1410
2026-04,1385
2026-05,1620
2026-06,1890
`;

const analysis = `
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv("signups.csv")
df["growth_pct"] = (df["signups"].pct_change() * 100).round(1)
print(df.to_string(index=False))

ax = df.plot(x="month", y="signups", marker="o", legend=False)
ax.set_xlabel("Month")
ax.set_ylabel("Signups")
ax.set_title("Monthly signups")
plt.tight_layout()
plt.savefig("signups.png", dpi=150)
`;

const sandbox = await Sandbox.create({
  image: 'vercel/sandbox/python:3.14',
  persistent: false,
  timeout: 10 * 60 * 1000,
});

try {
  const install = await sandbox.runCommand({
    cmd: 'uv',
    args: ['pip', 'install', '--system', 'pandas', 'matplotlib'],
    sudo: true,
  });
  if (install.exitCode !== 0) {
    throw new Error(`Install failed: ${await install.stderr()}`);
  }

  await sandbox.writeFiles([
    { path: 'signups.csv', content: dataset },
    { path: 'analyze.py', content: analysis },
  ]);

  const run = await sandbox.runCommand('python', ['analyze.py']);
  if (run.exitCode !== 0) {
    throw new Error(`Analysis failed: ${await run.stderr()}`);
  }
  console.log(await run.stdout());

  const chartPath = await sandbox.downloadFile(
    { path: 'signups.png' },
    { path: 'signups.png' },
  );
  if (!chartPath) {
    throw new Error('signups.png was not found in the sandbox');
  }
  console.log(`Chart saved to ${chartPath}`);
} finally {
  await sandbox.stop();
}
```

The script prints the table that the analysis produced, followed by the local path of the downloaded chart, which depends on your project directory:

```text
month  signups  growth_pct
2026-01     1180         NaN
2026-02     1245         5.5
2026-03     1410        13.3
2026-04     1385        -1.8
2026-05     1620        17.0
2026-06     1890        16.7

Chart saved to /path/to/sandbox-research/signups.png
```

The install command uses `sudo: true` so `uv` can write to the system Python environment. Check the downloaded chart's path before using it: `sandbox.downloadFile()` returns `null` if the file is missing.

Inbound transfer is free, including package and dataset downloads.

#### Data analysis resources

- Run [SQL and Python against datasets with millions of rows](https://vercel.com/kb/guide/large-scale-data-analysis-vercel-sandbox-mcp) and keep the raw data out of the model's context
  
- [Upload input files and download output files](https://vercel.com/docs/sandbox/examples/prepare-files-and-download-artifacts)
  
- Generate and run chart code with the [Python charts example](https://github.com/vercel/sandbox/tree/main/examples/charts-python)
  
- See how [Vercel's internal data agent, d0](https://vercel.com/blog/anyone-can-build-agents-but-it-takes-a-platform-to-run-them), runs SQL and Python in Sandbox
  

### Run experiments and evals in parallel

Fork a prepared sandbox so each trial starts from the same filesystem. `Sandbox.fork()` uses the source sandbox's latest snapshot and copies its configuration, excluding drive mounts.

The following example saves a baseline, then runs four trials in parallel with a different random seed in each fork. Save the code as `experiments.mts`:

```typescript
import { Sandbox } from '@vercel/sandbox';

type Trial = { seed: number; mean: number; stdev: number };

const experiment = `
import json
import random
import statistics
import sys

seed = int(sys.argv[1])
random.seed(seed)
samples = [random.gauss(0, 1) for _ in range(100_000)]
print(json.dumps({
    "seed": seed,
    "mean": round(statistics.fmean(samples), 5),
    "stdev": round(statistics.stdev(samples), 4),
}))
`;

// Fork the baseline, run one trial, and delete the fork.
async function runTrial(sourceSandbox: string, seed: number): Promise<Trial> {
  const fork = await Sandbox.fork({
    sourceSandbox,
    persistent: false,
    networkPolicy: 'deny-all',
  });

  try {
    const run = await fork.runCommand('python', [
      'experiment.py',
      String(seed),
    ]);
    if (run.exitCode !== 0) {
      throw new Error(`Seed ${seed} failed: ${await run.stderr()}`);
    }
    return JSON.parse(await run.stdout()) as Trial;
  } finally {
    await fork.delete();
  }
}

const base = await Sandbox.create({
  image: 'vercel/sandbox/python:3.14',
  persistent: true,
});

try {
  // Build the baseline. Stopping the persistent sandbox
  // saves its filesystem as a snapshot.
  await base.writeFiles([{ path: 'experiment.py', content: experiment }]);
  await base.stop();

  // Wait for every trial to settle before deleting the baseline.
  const settled = await Promise.allSettled(
    [1, 2, 3, 4].map((seed) => runTrial(base.name, seed)),
  );

  const failure = settled.find(
    (trial): trial is PromiseRejectedResult => trial.status === 'rejected',
  );
  if (failure) {
    throw failure.reason;
  }

  console.table(
    settled.flatMap((trial) =>
      trial.status === 'fulfilled' ? [trial.value] : [],
    ),
  );
} finally {
  await base.delete({ deleteOrphanSnapshots: true });
}
```

The script prints one row for each trial:

```text
┌─────────┬──────┬──────────┬────────┐
│ (index) │ seed │ mean     │ stdev  │
├─────────┼──────┼──────────┼────────┤
│ 0       │ 1    │ 0.00311  │ 1.0003 │
│ 1       │ 2    │ 0.00003  │ 0.9987 │
│ 2       │ 3    │ -0.00186 │ 0.9996 │
│ 3       │ 4    │ 0.00495  │ 0.9958 │
└─────────┴──────┴──────────┴────────┘
```

Stopping the persistent baseline saves the snapshot used by every fork. Each trial disables persistence and blocks outbound traffic, so it creates no automatic snapshot. The `finally` blocks remove the forks, baseline, and unused snapshot.

Your plan limits how many trials run at the same time. Hobby plans run up to 10 concurrent sandboxes, and Pro and Enterprise plans run up to 10,000. Your plan also limits how fast you can start sandboxes. On Pro, a team that was idle can allocate 150 vCPUs in the first minute, which covers 75 sandboxes with 2 vCPUs each, so start large batches in stages.

Vercel Sandbox doesn't guarantee dedicated hardware, so timings from different sandboxes can vary. When an experiment measures performance, [run both variants inside one sandbox](https://vercel.com/blog/making-turborepo-ninety-six-percent-faster-with-agents-sandboxes-and-humans) and compare those results.

#### Experiment and eval resources

- Run [Terminal-Bench and other Harbor benchmarks](https://vercel.com/kb/guide/run-terminal-bench-harbor-benchmarks-vercel-sandbox) with each trial in its own microVM, and compare models through AI Gateway
  
- Build a [CLI agent eval with Harbor and Vercel Sandbox](https://vercel.com/blog/agent-evals)
  
- Run evaluations in [AgentEnv by Scale AI](https://vercel.com/docs/sandbox/ecosystem/agentenv) with separate sandboxes for the task environment and the agent
  
- Compare [sandbox providers for evals](https://vercel.com/i/best-sandboxes-agent-evals) and common validity risks
  
- Learn how [RL environments](https://vercel.com/i/what-are-rl-environments) use sandboxes for tasks and rewards
  
- [Create a snapshot manually and restore the snapshot by ID](https://vercel.com/docs/sandbox/examples/snapshot-and-restore)
  

### Run untrusted code with restricted network access

Apply `deny-all` before untrusted code runs to block outbound network traffic, including DNS. SDK calls can still retrieve files and command output.

`sandbox.update()` applies a new policy to the running session without a restart. This example installs a dependency while the network is open and then blocks the network. The untrusted code uses the dependency and tries to make a request. Save the code as `untrusted-code.mts`:

```typescript
import { Sandbox } from '@vercel/sandbox';

const untrustedCode = `
import urllib.request

import numpy as np

print("mean:", np.mean([1, 2, 3]))
try:
    urllib.request.urlopen("https://example.com", timeout=5)
    print("network: reachable")
except OSError:
    print("network: blocked")
`;

const sandbox = await Sandbox.create({
  image: 'vercel/sandbox/python:3.14',
  persistent: false,
});

try {
  // Install dependencies while the sandbox still has network access.
  const install = await sandbox.runCommand({
    cmd: 'uv',
    args: ['pip', 'install', '--system', 'numpy'],
    sudo: true,
  });
  if (install.exitCode !== 0) {
    throw new Error(`Install failed: ${await install.stderr()}`);
  }

  // Block all outbound traffic before the untrusted code runs.
  await sandbox.update({ networkPolicy: 'deny-all' });

  await sandbox.writeFiles([{ path: 'untrusted.py', content: untrustedCode }]);
  const result = await sandbox.runCommand({
    cmd: 'python',
    args: ['-u', 'untrusted.py'],
    timeoutMs: 60_000,
  });

  console.log((await result.stdout()).trim());
  console.log(`exit code: ${result.exitCode}`);
} finally {
  await sandbox.stop();
}
```

The installed package still works after the policy change, and the request fails:

```text
mean: 2.0
network: blocked
exit code: 0
```

When the code needs network access, use an allowlist and add credentials brokering for authenticated requests. Domain rules filter the hostname negotiated during the TLS handshake. Brokering adds credentials at the firewall so the secret stays outside the sandbox.

Save the following policies as `network-policies.mts` and import the policy that you need. `brokeredCredentials()` reads an AI Gateway API key from the `AI_GATEWAY_API_KEY` environment variable on your machine:

```typescript
import type { NetworkPolicy } from '@vercel/sandbox';

// Allow TLS connections to PyPI and one data source.
export const allowlist: NetworkPolicy = {
  allow: ['pypi.org', 'files.pythonhosted.org', 'api.example.com'],
};

// Add the API key at the network layer. Code in the sandbox never sees the key.
export function brokeredCredentials(): NetworkPolicy {
  const apiKey = process.env.AI_GATEWAY_API_KEY;
  if (!apiKey) {
    throw new Error('Set AI_GATEWAY_API_KEY before you create the policy.');
  }

  return {
    allow: {
      'ai-gateway.vercel.sh': [
        { transform: [{ headers: { authorization: `Bearer ${apiKey}` } }] },
      ],
    },
  };
}
```

Pass `allowlist` or the result of `brokeredCredentials()` as `networkPolicy` when creating or updating the sandbox. The brokered policy permits the TLS hostname `ai-gateway.vercel.sh`. Plain HTTP needs IP-based rules.

Domain filtering alone may allow access to another application on shared infrastructure if the server accepts a different HTTP `Host` header. For stricter request controls, [rewrite the Host header or use an enforcing proxy](https://vercel.com/docs/sandbox/concepts/firewall#http-and-https).

#### Network security resources

- Look up network policies, credentials brokering, request proxying, and live updates in the [Sandbox firewall documentation](https://vercel.com/docs/sandbox/concepts/firewall)
  
- Run Python submissions against tests with [network restrictions](https://vercel.com/kb/guide/python-and-vercel-sandbox)
  
- Read [why egress control belongs in the security boundary](https://vercel.com/blog/a-sandbox-without-a-network-boundary-is-only-half-a-sandbox)
  
- Review the results of public and third-party security testing in the [findings from the $1M Vercel Sandbox challenge](https://vercel.com/blog/findings-from-the-1-million-dollar-vercel-sandbox-challenge)
  
- See how [Notion isolates customer code](https://vercel.com/customers/notion-workers-vercel-sandbox) and controls credentials and egress
  
- Learn [why virtual environments and](https://vercel.com/i/run-untrusted-python-code) [`exec()`](https://vercel.com/i/run-untrusted-python-code) [don't isolate code](https://vercel.com/i/run-untrusted-python-code)
  

### Keep a research workspace across sessions

Use `Sandbox.getOrCreate()` with a stable name to reuse a workspace. Sandboxes are persistent by default and save their filesystem when a session stops. The SDK restores that state when an operation needs a running sandbox, such as `runCommand()` or `writeFiles()`.

This example appends a line to a log file in each session. Save the code as `workspace.mts` and run the script twice:

```typescript
import { Sandbox } from '@vercel/sandbox';

const sandbox = await Sandbox.getOrCreate({
  name: 'literature-review',
  image: 'vercel/sandbox/python:3.14',
  timeout: 30 * 60 * 1000,
  keepLastSnapshots: { count: 1 },
  // Runs when the sandbox is created, not when an existing sandbox resumes.
  onCreate: async (created) => {
    await created.runCommand('mkdir', ['-p', 'notes']);
  },
});

try {
  const append = await sandbox.runCommand('bash', [
    '-c',
    'echo "session at $(date -u +%FT%TZ)" >> notes/sessions.log',
  ]);
  if (append.exitCode !== 0) {
    throw new Error(`Append failed: ${await append.stderr()}`);
  }

  const log = await sandbox.runCommand('cat', ['notes/sessions.log']);
  console.log((await log.stdout()).trim());
} finally {
  // Stopping a persistent sandbox saves its filesystem for the next session.
  await sandbox.stop();
}
```

The second run prints both sessions with your own timestamps, which shows that `notes/sessions.log` survived the stop:

```text
session at 2026-11-30T09:15:02Z
session at 2026-11-30T14:41:37Z
```

`onCreate` runs only when a workspace is first created. Later calls to `Sandbox.getOrCreate()` return the existing workspace and ignore creation options. Each resumed session gets a fresh duration limit.

#### Manage snapshots and shared data

The workspace retains only its latest snapshot, which expires 30 days after its last use by default. To retain it longer, call `sandbox.update()` while the workspace is running and set `snapshotExpiration` to `0` for no expiration or a duration in milliseconds. Stop the workspace to save a snapshot with that setting.

Store datasets that several sandboxes share on [Vercel Drives](https://vercel.com/docs/sandbox/concepts/drives). Each sandbox mounts a drive as a directory, and many sandboxes can mount a read-only snapshot of the same drive.

#### Delete the workspace

> **Warning:**
>
> Deleting a workspace permanently removes the sandbox and its sessions. When the study ends, call `sandbox.delete()` with `deleteOrphanSnapshots` set to `true` to remove unused snapshots too. Snapshots still used by another sandbox are retained.

#### Persistent workspace resources

- Choose between [longer sessions, persistence, or both](https://vercel.com/kb/guide/vercel-sandbox-duration-and-persistence), and estimate the cost
  
- [Prepare a dataset once and analyze the dataset in many sandboxes](https://vercel.com/kb/guide/vercel-drives)
  
- Build a [research-notes agent that keeps its notes on a drive](https://vercel.com/kb/guide/persistent-storage-with-vercel-drives)
  
- Compare [the storage needs of data analysis agents and deep research agents](https://vercel.com/i/ai-agents-persistent-workspace)
  
- Read how [drives support shared datasets and parallel forks](https://vercel.com/blog/introducing-vercel-drives-persistent-storage-for-agents)
  
- [Stop a sandbox and resume the sandbox by name](https://vercel.com/docs/sandbox/examples/resume-a-long-lived-sandbox)
  

## Best practices for research workloads

Set execution limits and cleanup rules before running research jobs at scale.

- Pass `persistent: false` for one-off runs, when you don't need the files again. Persistent sandboxes create a snapshot on every stop, and Vercel bills snapshot storage separately from compute.
  
- Check `exitCode` before using a command's results. If it isn't `0`, inspect `stderr()` to understand the failure.
  
- Set a time limit on every run, with `timeout` for the session and `timeoutMs` for each command. These limits stop a loop in generated code before the loop reaches the plan limit.
  
- Restrict the network before untrusted code runs. Install packages and download data first, then apply `deny-all` or an allowlist with `sandbox.update()`.
  
- Use credentials brokering for API keys that generated code needs, so the keys stay out of the sandbox. Keep secrets out of command arguments too, because Vercel Sandbox can store arguments and return them in API responses.
  
- Pin the environment when results must be reproducible, because managed image tags receive nightly updates. Pin package versions, and reference the image by digest when a study must rerun on an identical environment.
  
- Print progress during long computations. An idle connection closes after 340 seconds even if the command is still running. Use [detached execution](https://vercel.com/docs/sandbox/examples/execute-long-running-tasks) when regular output isn't practical.
  
- Delete sandboxes and snapshots when a study ends, with `sandbox.delete({ deleteOrphanSnapshots: true })`. Snapshots survive deletion by default and incur storage charges until they expire.
  

## Run research workloads across an enterprise

An analyst might use an [enterprise AI agent](https://vercel.com/i/enterprise-ai-agents) to investigate changes in revenue or test a forecast against company data. Making that capability available across teams requires control over who can submit jobs and which data each job can use. Vercel Sandbox isolates code execution, while your research application manages employee permissions and records the work performed.

### Provide an approved research service

Give analysts and other [citizen developers](https://vercel.com/i/what-is-a-citizen-developer) an approved app or API for submitting research jobs. At [Klaviyo](https://vercel.com/customers/how-klaviyo-shipped-356-internal-apps-in-two-weeks-on-vercel), 512 employees shipped 356 internal apps in two weeks. As employee-built tools spread, [assign an owner and review data access](https://vercel.com/i/govern-employee-built-ai-apps-and-agents) to keep research tools from becoming [shadow AI](https://vercel.com/i/what-is-shadow-ai) outside company oversight.

The service's server should create a separate sandbox for each job and enforce the approved image, network policy, and brokered credentials. The `research-agent.mts` script authenticates AI Gateway requests with the project's Vercel OIDC token.

[Vercel Passport](https://vercel.com/docs/passport) protects internal web apps by requiring employees to sign in through your company's identity provider. This [Deployment Protection method](https://vercel.com/kb/guide/vercel-passport-vs-deployment-protection) controls access to the deployment, while your app must still check each employee's permissions for datasets and actions.

### Connect to internal data

Research jobs may need a warehouse replica or an API behind a company firewall. Enterprise teams can attach sandboxes to a [Secure Compute network](https://vercel.com/docs/sandbox/concepts/secure-compute) so public internet traffic leaves through its static IPs. Configure VPC peering separately to reach private resources in your AWS VPC. Ask your account team for pricing.

Find the network's ID under **Settings** > **Networking** in your team dashboard and pass it when creating the sandbox. Save the following code as `secure-compute.mts` and replace `your_network_id_here` with that ID:

```typescript
import { Sandbox } from '@vercel/sandbox';

const sandbox = await Sandbox.create({
  image: 'vercel/sandbox/python:3.14',
  persistent: false,
  networkId: 'your_network_id_here',
});

try {
  const result = await sandbox.runCommand({
    cmd: 'curl',
    args: [
      '--fail',
      '--silent',
      '--show-error',
      'https://checkip.amazonaws.com/',
    ],
  });

  if (result.exitCode !== 0) {
    throw new Error(`IP check failed: ${await result.stderr()}`);
  }

  // Prints one of the network's static IPs.
  console.log((await result.stdout()).trim());
} finally {
  await sandbox.stop();
}
```

The script prints the public IP that the request came from, which matches one of your network's static IPs. For a database or API that admits traffic by IP address, add those IPs to its allowlist.

### Install private dependencies

Research tools may need packages from your organization's private registry. [Sandbox credentials](https://vercel.com/docs/sandbox/concepts/credentials) are in beta and support private packages from the npm registry, GitHub Packages, and JFrog Artifactory. The firewall adds authentication to package-install requests so sandbox code cannot read the token.

Configure `NPM_TOKEN` or `NPM_RC` on the project or team. Request npm access with `credentials: { npm: true }` and allow the registry hosts in the network policy.

### Record and evaluate research runs

Use the [Sandbox CLI](https://vercel.com/docs/sandbox/sdk/cli) to inspect workspace sessions and the dashboard's [Observability tab](https://vercel.com/docs/sandbox#monitor-cpu-and-memory-usage) to check CPU and memory usage. The CLI uses saved Vercel credentials or prompts you to sign in. Run it through `npx` to list the `literature-review` sessions without a global installation:

```bash
npx sandbox@latest sessions list literature-review --all
```

[Record each tool call, approval, and result](https://vercel.com/i/how-to-audit-ai-agents) in your application so you can reconstruct what the agent did. Sandbox session records and resource metrics don't capture those decisions. For AI SDK applications, [evlog](https://vercel.com/kb/guide/ai-sdk-and-evlog) records token usage, tool calls, and cost estimates per request.

Before research results inform a business decision, [test the agent against labeled cases and a parallel pilot](https://vercel.com/i/testing-ai-decisions-enterprise-workflows). Use the fork pattern from the parallel experiments section to run each case in its own sandbox.

### Review compliance and data location

Vercel's infrastructure maintains SOC 2 Type II certification, and sandbox snapshots are encrypted at rest. Vercel also holds [ISO/IEC 42001:2023 certification](https://vercel.com/blog/vercel-completes-iso-iec-42001-2023-certification), which covers AI management systems. Review the [Sandbox security model](https://vercel.com/docs/sandbox/concepts/security) for details on isolation, resource limits, and data privacy.

Your research application still needs its own compliance review. Before choosing a [sandbox region](https://vercel.com/docs/sandbox/concepts/regions), check the workload's data residency requirements against your plan and your organization's obligations. You can set a region for each sandbox or use a project default to keep computation near the data.

## Limits and when to use a different tool

Your plan sets the size, duration, and number of research runs. The following table lists the Vercel Sandbox limits for each plan.

| Limit                           | Hobby                     | Pro                           | Enterprise                    |
| ------------------------------- | ------------------------- | ----------------------------- | ----------------------------- |
| Maximum vCPUs for each sandbox  | 4                         | 8                             | 32                            |
| Maximum memory for each sandbox | 8 GB                      | 16 GB                         | 64 GB                         |
| Maximum session duration        | 45 minutes                | 24 hours                      | 24 hours                      |
| Concurrent sandboxes            | 10                        | 10,000                        | 10,000                        |
| vCPU allocation rate            | 20 to 40 vCPUs per minute | 150 to 5,000 vCPUs per minute | 150 to 5,000 vCPUs per minute |
| Disk size for each sandbox      | 64 GB                     | 64 GB                         | 64 GB                         |

Each vCPU includes 2 GB of memory, and a new sandbox has 2 vCPUs unless you set `resources: { vcpus }`. Hobby plans include 5 hours of Active CPU and 5,000 sandbox creations each month, and sandbox creation pauses when a Hobby team exceeds the included usage. Enterprise teams can contact sales for higher concurrency and allocation quotas. See [Vercel Sandbox pricing and quotas](https://vercel.com/docs/sandbox/pricing) for current rates and quotas.

Some research workloads need a different tool or an extra step:

- Train or serve models that need a GPU on a platform that offers GPUs. Vercel Sandbox provisions CPU and memory only.
  
- Restart services after the sandbox resumes, because running processes end when a session stops. Snapshots save files and installed packages.
  
- Serve HTTP endpoints with [Vercel Functions](https://vercel.com/docs/functions). For continuous background workers, use [Vercel Daemons](https://vercel.com/docs/daemons), currently in public beta.
  
- Keep large or shared data on Vercel Drives, in a database, or in object storage. The sandbox filesystem isn't a database or an object store.
  

## Next steps

- Explore [examples for long tasks, artifacts, and snapshots](https://vercel.com/docs/sandbox/examples)
  
- Learn [what the sandbox boundary isolates](https://vercel.com/docs/sandbox/concepts/security)
  
- Browse the [guides filed under Vercel Sandbox](https://vercel.com/kb/vercel-sandbox) in the Knowledge Base
  
- Run [generated code from a Next.js route handler](https://vercel.com/kb/guide/running-ai-generated-code-sandbox)
  
- Build [code interpreters, persistent workspaces, and batch jobs](https://vercel.com/kb/guide/startups-on-vercel-sandbox)
  
- Explore the SDK, the CLI, and runnable examples in [vercel/sandbox on GitHub](https://github.com/vercel/sandbox)

## More Vercel Sandbox guides

- [Vercel Sandbox vs HubSpot Sandbox](/kb/guide/vercel-sandbox-vs-hubspot-sandbox): Compare Vercel Sandbox with HubSpot sandbox accounts, pick one for each marketing operations task, and run AI-generated scripts against HubSpot without exposing your API token.
- [Migrate from E2B to Vercel Sandbox](/kb/guide/migrate-from-e2b-to-vercel-sandbox): Move E2B sandbox code to Vercel Sandbox in TypeScript or Python, from templates and pauses to Volumes, network rules, Secrets, and a staged cutover.
- [Vercel Sandbox vs CodeSandbox](/kb/guide/vercel-sandbox-vs-codesandbox): Compare Vercel Sandbox and CodeSandbox as AI agent sandboxes, including isolation, persistence, network controls, SDKs, and workload fit.

## Reference Architecture

Choose a stack and work through the decisions behind it, with curated documentation, guides, templates, and courses to help you build.

- [Agent stack](/kb/architecture/agents): Build and operate agents with models, tools, and durable workflows.
- [Web applications](/kb/architecture/web): Choose rendering, data, authentication, and caching approaches.
- [Backends](/kb/architecture/backends): Choose a runtime, connect services, and run background work.

[Browse all stacks](/kb/architecture)

## Build with prompts

Build an app, extend an agent, or improve your project with ready-to-use prompts for your coding agent.

[Browse the prompt library](/kb/prompts) · [Read the Markdown index](/kb/prompts.md)

## Search guides from your terminal

Search the Knowledge Base and read guides as Markdown with the Vercel CLI. No login required.

```bash
# Find guides by keyword
npx vercel@latest kb search "rewrites and redirects"
npx vercel@latest kb search "AI SDK streaming"

# Show the latest guides
npx vercel@latest kb

# Print a guide as Markdown, by slug or URL
npx vercel@latest kb inspect <guide>
```
