
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.
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:
- The user uploads a CSV file.
- We spin up an E2B sandbox and upload the CSV into the secure environment.
- We prompt the Vercel AI SDK agent with the user's analytical question.
- The agent writes a Python script and calls an
execute_pythontool. - Our tool executes the script inside the E2B sandbox, reads the
stdoutand any generated chart images, and returns them to the agent. - 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.
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).
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.
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()).
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.
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.
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.
- Durable State: E2B sandboxes can be kept alive for up to 24 hours. You can assign a
sandboxIdto 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. - 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.
- Frontend Rendering: Using Vercel AI SDK's
streamUIalongside 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
Explore how the finance sector is leveraging custom AI agents for quantitative analysis, automated reporting, and secure data processing.
A technical guide to building secure, HIPAA-compliant AI agents in healthcare. Learn about self-hosted models, zero-retention policies, and sandboxing PHI.
An in-depth exploration of how Moonshot AI's Kimi K3 is transforming quantitative finance. Learn how hedge funds use its 1-million token context to analyze years of market data and generate complex trading algorithms.
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.