Use Code Interpreter Sandbox

Updated at:

Code Interpreter Sandbox is designed for Agents that need to run Python or Node.js scripts, process user files, and generate structured results or reports. The core requirement for data analysis Agents is to let model-generated logic process user data inside an isolated environment and return results that are explainable, downloadable, and auditable. Running user data and model-generated code directly inside the business service is high risk: dependency conflicts, leftover files, long-running computation, exception logs, and data access control all turn into engineering problems.

FC Agent Sandbox can be used as a Code Interpreter Sandbox. The business system is responsible for uploading data, generating or selecting analysis scripts, and validating inputs and outputs. FC Agent Sandbox is responsible for running scripts, handling temporary files, and returning structured results. This pattern works well for intelligent Q&A, operations analysis, report generation, customer service diagnostics, and similar scenarios.

Use cases

  • A user uploads a CSV file and the Agent automatically calculates metrics and returns a summary.

  • Operations staff trigger ad hoc analysis with natural language, without running data inside the main service workspace.

  • A reporting system offloads intermediate computation to the sandbox and then sends result files back to the business system.

  • In multi-tenant scenarios, each analysis runs in its own sandbox to reduce the risk of data leakage across tenants.

Recommended workflow

Split an analysis task into four steps:

  1. Write the input data and analysis script.

  2. Run the script through a fixed entry point such as python3 analyze.py.

  3. Require the script to output a JSON summary and generate result files only when needed.

  4. Read the result and destroy the sandbox.

If the business needs a Notebook-style run_code experience, use the e2b_code_interpreter SDK. At the best-practice level, a fixed script entry point is easier to audit and easier to control for timeouts and output validation.

Interactive code execution

For template parameters and capability differences between the two SDKs, see the Code Interpreter v1 Template. For Notebook-style interactive execution, use the e2b_code_interpreter SDK to create a Sandbox and call run_code directly.

import os
from e2b_code_interpreter import Sandbox

sandbox = Sandbox.create(
    api_key=os.environ["E2B_API_KEY"],
    api_url=os.environ["E2B_API_URL"],
    domain=os.environ["E2B_DOMAIN"],
)

try:
    execution = sandbox.run_code(
        """
import json

data = [
    {"segment": "enterprise", "revenue": 2600},
    {"segment": "startup", "revenue": 680},
]

total = sum(row["revenue"] for row in data)
top_segment = max(data, key=lambda row: row["revenue"])

print(json.dumps({
    "total_revenue": total,
    "top_segment": top_segment["segment"],
    "top_segment_revenue": top_segment["revenue"],
}, ensure_ascii=False))
"""
    )
    print("".join(execution.logs.stdout or []))
finally:
    sandbox.kill()

run_code is better suited for interactive tasks where the model incrementally generates and corrects code. A fixed script entry point is better suited for production pipelines because script versions, input directories, timeouts, and output formats are easier to pin down.

Example code

The following example analyzes revenue by segment inside the sandbox and returns total revenue, the top-contributing segment, and a summary.

import { Sandbox } from "e2b";

const sandbox = await Sandbox.create("code-interpreter-v1", {
  apiKey: process.env.E2B_API_KEY,
  apiUrl: process.env.E2B_API_URL,
  domain: process.env.E2B_DOMAIN,
  envs: { TASK_TYPE: "data-analysis" },
});

try {
  await sandbox.files.makeDir("/tmp/data-analysis");
  await sandbox.files.write(
    "/tmp/data-analysis/revenue.csv",
    `date,segment,revenue
2026-07-01,enterprise,1200
2026-07-01,startup,320
2026-07-02,enterprise,1400
2026-07-02,startup,360
`,
  );
  await sandbox.files.write(
    "/tmp/data-analysis/analyze.py",
    `import csv
import json
from collections import defaultdict

revenue_by_segment = defaultdict(int)
with open("revenue.csv", newline="") as f:
    for row in csv.DictReader(f):
        revenue_by_segment[row["segment"]] += int(row["revenue"])

total = sum(revenue_by_segment.values())
top_segment, top_revenue = max(revenue_by_segment.items(), key=lambda item: item[1])

print(json.dumps({
    "total_revenue": total,
    "top_segment": top_segment,
    "top_segment_revenue": top_revenue,
    "summary": f"{top_segment} contributes {round(top_revenue / total * 100, 1)}% of revenue."
}, ensure_ascii=False))
`,
  );

  const result = await sandbox.commands.run("python3 analyze.py", {
    cwd: "/tmp/data-analysis",
    timeoutMs: 30_000,
  });
  if (result.exitCode !== 0) {
    throw new Error(result.stderr || result.stdout);
  }

  console.log(JSON.parse(result.stdout));
} finally {
  await sandbox.kill();
}

Production recommendations

  • Limit input file size, type, and path to prevent a single task from consuming too much memory or disk.

  • Use JSON summaries as the primary output. Charts, tables, and report files can be written to /tmp and then downloaded.

  • Wrap stdout, stderr, exit codes, and result files in a unified format to prevent upstream Agents from parsing unstructured logs directly.

  • Version the analysis code. In production, do not keep only the model-generated natural-language explanation.

  • Put common dependencies such as pandas, openpyxl, charting libraries, and business SDKs into the template.

  • Separate user-facing results from troubleshooting logs so full stack traces or sensitive data are not returned directly.