---
title: "Building a Persistent Data Analyst Agent with Vercel AI SDK and E2B"
description: "Giving an LLM the ability to write code is dangerous. Learn how to securely connect the Vercel AI SDK to an E2B cloud sandbox so your agent can write Python, execute it on CSVs, and generate charts safely."
image: "https://foundrysoft.co/api/og?type=article&title=Building+a+Persistent+Data+Analyst+Agent+with+Vercel+AI+SDK+and+E2B&cat=Tutorial+%2F%2F+Data+%26+Security&rt=19+min+read&au=Varun+Raj+Manoharan&dt=2026-07-09"
url: "https://foundrysoft.co/blog/vercel-ai-sdk-e2b-data-analyst"
---

Tutorial // Data & Security 2026-07-09 19 min read

# Building a Persistent Data Analyst Agent with Vercel AI SDK and E2B

Giving an LLM the ability to write code is dangerous. Learn how to securely connect the Vercel AI SDK to an E2B cloud sandbox so your agent can write Python, execute it on CSVs, and generate charts safely.

![Varun Raj Manoharan](https://foundrysoft.co/images/about/founder.webp)

Varun Raj Manoharan

Vercel AI SDK E2B Data Analysis Python Security

## Summary

**TL;DR:** Running AI-generated code on your server is dangerous. This tutorial shows how to build a Data Analyst agent by connecting the Vercel AI SDK to E2B secure cloud sandboxes to safely execute Python data analysis on CSVs.

If you ask an LLM to "Calculate the standard deviation of revenue across these 50,000 rows of CSV data," it will fail. LLMs are next-token predictors, not calculators. They cannot perform complex math or sort large datasets reliably in their heads.

To solve this, we must give the LLM the ability to write a Python script (using libraries like `pandas` and `matplotlib`), execute that script, and read the results.

However, running AI-generated Python code directly on your Node.js server using `child_process.exec` is a massive security vulnerability. A hallucinated `os.system("rm -rf /")` could destroy your infrastructure.

In this tutorial, we will build a secure Data Analyst agent. We will use the **Vercel AI SDK** to generate the Python code, and we will execute that code securely in an **E2B (English2Bits)** cloud sandbox environment.

| Execution Method | Security | Maintenance Overhead | Scale |
| --- | --- | --- | --- |
| `child_process.exec` | Extremely Dangerous (RCE Risk) | Zero | Low |
| **Custom Docker Container** | Secure | Very High (Managing containers) | Medium |
| **E2B Cloud Sandboxes** | Enterprise Grade Secure | Zero (Serverless) | Massive |

### The Sandbox Architecture

E2B provides instant, long-running secure sandboxes specifically designed for AI agents.

The architecture works like this:

1.  The user uploads a CSV file.
2.  We spin up an E2B sandbox and upload the CSV into the secure environment.
3.  We prompt the Vercel AI SDK agent with the user's analytical question.
4.  The agent writes a Python script and calls an `execute_python` tool.
5.  Our tool executes the script inside the E2B sandbox, reads the `stdout` and any generated chart images, and returns them to the agent.
6.  The agent reviews the results and presents the final answer to the user.

### Step 1: Dependencies and Setup

Initialize your project and install the E2B SDK alongside the Vercel AI SDK.

Shell

Copy

```bash
mkdir data-analyst-agent
cd data-analyst-agent
npm init -y
npm install ai @ai-sdk/openai @e2b/code-interpreter dotenv
npm install -D typescript @types/node tsx
```

You will need an E2B API key (they offer a generous free tier).

ENV

Copy

```env
OPENAI_API_KEY=sk-your-openai-key
E2B_API_KEY=e2b_your_api_key
```

### Step 2: Spinning up the E2B Sandbox

E2B provides a specialized `Sandbox` object designed specifically for code interpretation. It comes pre-installed with common data science libraries like `pandas`, `numpy`, and `matplotlib`.

Create `agent.ts`.

TypeScript

Copy

```typescript
import { Sandbox } from '@e2b/code-interpreter';
import fs from 'fs';

async function initSandbox() {
  console.log("Spinning up secure E2B sandbox...");

  // This boots a secure microVM in the cloud in under 1 second
  const sandbox = await Sandbox.create();

  // Upload our mock dataset into the sandbox
  // (Assume we have a sales_data.csv locally)
  const csvBuffer = fs.readFileSync('./sales_data.csv');
  await sandbox.files.write('/home/user/sales_data.csv', csvBuffer);

  console.log("Dataset uploaded to sandbox.");
  return sandbox;
}
```

### Step 3: Defining the Secure Execution Tool

Now we need to provide the Vercel AI SDK with a tool that runs code inside this specific sandbox.

The E2B `sandbox.runCode` function executes Python and captures the standard output, standard error, and any rich visual artifacts (like PNG charts generated by `matplotlib.pyplot.show()`).

TypeScript

Copy

```typescript
import { tool } from 'ai';
import { z } from 'zod';

function createPythonTool(sandbox: Sandbox) {
  return tool({
    description: `Execute Python code securely to analyze the 'sales_data.csv' file located at '/home/user/sales_data.csv'.
                  Use pandas for analysis. Use matplotlib for charts and call plt.show() to render them.`,
    parameters: z.object({
      code: z.string().describe("The raw Python code to execute.")
    }),
    execute: async ({ code }) => {
      console.log(`\n[Agent executing Python]...\n${code}\n`);

      // Execute securely in E2B
      const execution = await sandbox.runCode(code);

      let result = `STDOUT:\n${execution.logs.stdout.join('\n')}\n`;
      if (execution.logs.stderr.length > 0) {
        result += `STDERR:\n${execution.logs.stderr.join('\n')}\n`;
      }

      // Handle generated charts (if the agent ran plt.show())
      if (execution.results.length > 0) {
        const firstResult = execution.results[0];
        if (firstResult.png) {
          // In a real web app, you would save this base64 string to S3 or serve it to the frontend
          fs.writeFileSync('./generated_chart.png', Buffer.from(firstResult.png, 'base64'));
          result += `\n[System]: Chart successfully generated and saved.`;
        }
      }

      return result;
    }
  });
}
```

This tool design is incredibly robust. If the agent writes broken Python syntax, the tool returns the `STDERR` traceback. Because we will use `maxSteps` in the AI SDK, the agent will see the error, rewrite its Python code, and try again autonomously without crashing your server.

### Step 4: Building the AI Loop

We wire the Vercel AI SDK to use our secure tool. We use a strong model (like `gpt-4o`) because generating syntactic Python requires high reasoning capabilities.

TypeScript

Copy

```typescript
import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';

async function runDataAnalyst(sandbox: Sandbox, userQuery: string) {
  console.log(`User: ${userQuery}`);

  const result = await generateText({
    model: openai('gpt-4o'),
    system: `You are an elite Data Scientist.
             You have access to a secure Python sandbox containing 'sales_data.csv'.
             Write and execute Python code to answer the user's questions.
             If you need to make a chart, generate it.
             Always review the execution output before giving your final answer.`,
    messages: [{ role: 'user', content: userQuery }],
    tools: {
      execute_python: createPythonTool(sandbox)
    },
    maxSteps: 5, // Allow the agent to fix its own bugs
  });

  console.log(`\n[Final Analyst Report]:\n${result.text}`);
}
```

### Step 5: Execution

Let's put it all together and ask a complex question.

TypeScript

Copy

```typescript
async function main() {
  const sandbox = await initSandbox();

  await runDataAnalyst(
    sandbox,
    "Read the CSV. Find the top 3 selling product categories, and generate a bar chart showing their total revenue."
  );

  // Always clean up cloud resources
  await sandbox.kill();
}

main();
```

When you run this script, you will see the LLM generate a block of pandas code. It will call the `execute_python` tool. The E2B sandbox will process the data instantly. If `matplotlib` was used correctly, the base64 PNG data will be captured by E2B, intercepted by our tool, and saved to your local disk as `generated_chart.png`.

The agent will then read the `stdout` (which might contain a `print()` statement of the top 3 categories) and summarize the findings beautifully for the user.

### Production Considerations

Building secure code-execution agents changes the type of applications you can build.

1.  **Durable State:** E2B sandboxes can be kept alive for up to 24 hours. You can assign a `sandboxId` to a specific user's web session. This means the agent can run code, store data in memory, and reference it 5 minutes later in a follow-up chat message.
2.  **Resource Limits:** Because execution happens on E2B's infrastructure, heavy pandas operations or machine learning model training inside the sandbox will not throttle your Next.js/Node.js web servers.
3.  **Frontend Rendering:** Using Vercel AI SDK's `streamUI` alongside E2B, you can stream the base64 images directly into a React Server Component, allowing the user to see charts generate in real-time in their browser.

By combining the Vercel AI SDK with E2B, you are no longer limited to generating text. You have given your agent hands, and a secure playground to use them.

### Frequently Asked Questions (FAQ)

**How do I safely execute AI-generated Python code?** Never use `child_process.exec` locally. Always use a secure, isolated microVM or Docker sandbox like E2B (English2Bits). This prevents malicious hallucinated code from accessing your host environment.

**Can Vercel AI SDK agents generate charts?** Yes. When the agent executes Python code (using `matplotlib`) inside an E2B sandbox, the sandbox captures the visual output as a base64 string. You can then use Vercel AI SDK's Generative UI (`streamUI`) to render the chart for the user.

**Are LLMs good at math and data analysis?** LLMs are terrible at raw calculation. However, they are excellent at _writing code_ that performs calculations. By giving them a Python interpreter tool, their data analysis accuracy jumps to near 100%.

#### Related reading

[Claude Opus 5 Batch API Tutorial: AI Contract Data Extraction at Scale, with Real Costs

A step-by-step tutorial for bulk AI document extraction with the Claude Opus 5 Batch API: structured outputs with JSON schemas, 50% batch pricing, the 300K output beta, and the real cost of processing 40,000 vendor contracts.

Claude Opus 5 Anthropic Batch API

](https://foundrysoft.co/blog/claude-opus-5-batch-api-contract-extraction)[Claude Opus 5 Effort Parameter Guide: How to Reduce Claude API Costs Without Switching Models

How to use the Claude Opus 5 effort parameter (low, medium, high, xhigh, max) to cut Claude API costs. Real per-request cost numbers, working Python code, and why we retired our Haiku/Sonnet/Opus routing layer.

Claude Opus 5 Anthropic Claude API

](https://foundrysoft.co/blog/claude-opus-5-effort-parameter-cost-routing)[How to Build a Long-Running AI Agent with the Claude Opus 5 API: An Overnight Build Log

A hands-on guide to building autonomous AI agents on the Claude Opus 5 API: the agent loop in Python, mid-conversation system messages, prompt caching costs, and what an overnight dependency-upgrade run actually cost.

Claude Opus 5 Anthropic Claude API

](https://foundrysoft.co/blog/claude-opus-5-overnight-long-horizon-agent)

#### Next Article

[

Building a Resilient Support Bot with Vercel AI SDK v7 Durable Workflows

](https://foundrysoft.co/blog/vercel-ai-sdk-v7-durable-workflows)

Available for new projects

## Let's build something great.

Have a project in mind? We are an elite software and AI development studio ready to bring your ideas to production. Let's talk about your roadmap.

Start a Project [See our work](https://foundrysoft.co/work)

```json
{
  "@context": "https://schema.org",
  "@type": "Organization",
  "name": "FoundrySoft",
  "url": "https://foundrysoft.co",
  "logo": "https://foundrysoft.co/logo.svg",
  "description": "FoundrySoft builds production-grade software and AI systems for US companies, from an India-based team of senior engineers.",
  "sameAs": [
    "https://github.com/foundrysofthq",
    "https://www.linkedin.com/company/foundrysoft",
    "https://www.instagram.com/foundrysoft/"
  ]
}
```

```json
{
  "@context": "https://schema.org",
  "@type": "WebSite",
  "name": "FoundrySoft",
  "url": "https://foundrysoft.co"
}
```

```json
{
  "@context": "https://schema.org",
  "@type": "TechArticle",
  "headline": "Building a Persistent Data Analyst Agent with Vercel AI SDK and E2B",
  "description": "Giving an LLM the ability to write code is dangerous. Learn how to securely connect the Vercel AI SDK to an E2B cloud sandbox so your agent can write Python, execute it on CSVs, and generate charts safely.",
  "url": "https://foundrysoft.co/blog/vercel-ai-sdk-e2b-data-analyst",
  "mainEntityOfPage": "https://foundrysoft.co/blog/vercel-ai-sdk-e2b-data-analyst",
  "image": [
    "https://foundrysoft.co/images/blog/e2b-data-agent.jpg"
  ],
  "datePublished": "2026-07-09",
  "dateModified": "2026-07-09",
  "keywords": "Vercel AI SDK, E2B, Data Analysis, Python, Security",
  "author": {
    "@type": "Person",
    "name": "Varun Raj Manoharan"
  },
  "publisher": {
    "@type": "Organization",
    "name": "FoundrySoft",
    "logo": {
      "@type": "ImageObject",
      "url": "https://foundrysoft.co/logo.svg"
    }
  }
}
```

```json
{
  "@context": "https://schema.org",
  "@type": "BreadcrumbList",
  "itemListElement": [
    {
      "@type": "ListItem",
      "position": 1,
      "name": "Home",
      "item": "https://foundrysoft.co/"
    },
    {
      "@type": "ListItem",
      "position": 2,
      "name": "Blog",
      "item": "https://foundrysoft.co/blog"
    },
    {
      "@type": "ListItem",
      "position": 3,
      "name": "Building a Persistent Data Analyst Agent with Vercel AI SDK and E2B",
      "item": "https://foundrysoft.co/blog/vercel-ai-sdk-e2b-data-analyst"
    }
  ]
}
```

```json
{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {
      "@type": "Question",
      "name": "How do I safely execute AI-generated Python code?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Never use child_process.exec locally. Always use a secure, isolated microVM or Docker sandbox like E2B (English2Bits). This prevents malicious hallucinated code from accessing your host environment."
      }
    },
    {
      "@type": "Question",
      "name": "Can Vercel AI SDK agents generate charts?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Yes. When the agent executes Python code (using matplotlib) inside an E2B sandbox, the sandbox captures the visual output as a base64 string. You can then use Vercel AI SDK's Generative UI (streamUI) to render the chart for the user."
      }
    },
    {
      "@type": "Question",
      "name": "Are LLMs good at math and data analysis?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "LLMs are terrible at raw calculation. However, they are excellent at writing code that performs calculations. By giving them a Python interpreter tool, their data analysis accuracy jumps to near 100%."
      }
    }
  ]
}
```
