Skip to main content

Using Code Interpreter Sandbox

Best practices for data-analysis agents: run model-generated analysis logic in an isolated sandbox, use a fixed script entry point, structured output, and dependencies baked into the template, returning explainable, downloadable, and auditable results.

Code Interpreter Sandbox is designed for agents that need to run Python/Node scripts, process files, or generate structured results and report artifacts. The core need of a data-analysis agent is to run model-generated analysis logic in an isolated environment over your data and return explainable, downloadable, and auditable results. Running external data and model-generated code directly in a business service turns dependency conflicts, leftover files, long-running computation, noisy logs, and data permissions into engineering problems. Sandbox can be used as a Code Interpreter Sandbox: the business system uploads data, generates or selects analysis scripts, and validates inputs and outputs; the sandbox runs scripts, handles temporary files, and returns structured results. This fits intelligent Q&A, operations analysis, report generation, and customer-service data diagnosis.

Use Cases

  • Upload a CSV, automatically compute metrics, and produce a summary.
  • Trigger ad-hoc analysis in natural language without landing data in the main service's working directory.
  • Run intermediate report computation in the sandbox and hand result files back to the business system.
  • Use an independent sandbox per analysis in multi-tenant scenarios, reducing the risk of data cross-contamination.
First create a template based on the Code Interpreter image (code-interpreter-v1) and obtain its templateCode—see Template Management. Then split the analysis task into four steps:
  1. Write the input data and analysis script.
  2. Execute the script through a fixed entry point, for example python3 analyze.py.
  3. Require the script to print a JSON summary and, if needed, produce file artifacts.
  4. Read the results and destroy the sandbox.

Interactive Code Execution

For a Notebook-style run_code experience, use the e2b-code-interpreter SDK to create an instance and call run_code directly:
from e2b_code_interpreter import Sandbox

ALIYUN_UID = "your aliyunUid"
BAILIAN_API_KEY = "sk-..."
BASE_URL = "https://{workspace_id}.cn-beijing.maas.aliyuncs.com/api/v1/agentstudio/sandbox"

sandbox = Sandbox.create(
    api_url=BASE_URL,
    api_key=f"e2b_{ALIYUN_UID}",
    headers={"Authorization": f"Bearer {BAILIAN_API_KEY}"},
    template="your template code",
)

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 better fits interactive tasks where the model iteratively generates and corrects code; a fixed script entry point better fits 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 in the sandbox and returns the total revenue, the top segment, and a summary:
Pin the Node.js SDK with npm install e2b@2.31.0. Newer SDK versions return 405 when creating a sandbox.
import { Sandbox } from "e2b";

const ALIYUN_UID = "your aliyunUid";
const BAILIAN_API_KEY = "sk-...";
const BASE_URL = "https://{workspace_id}.cn-beijing.maas.aliyuncs.com/api/v1/agentstudio/sandbox";

const sandbox = await Sandbox.create("your template code", {
  apiUrl: BASE_URL,
  apiKey: `e2b_${ALIYUN_UID}`,
  apiHeaders: { Authorization: `Bearer ${BAILIAN_API_KEY}` },
  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 Advice

  • Limit the size, type, and path of input files so a single task cannot exhaust memory or disk.
  • Prefer JSON summaries for output; write charts, tables, and report files to /tmp and download them afterwards.
  • Wrap stdout, stderr, the exit code, and result files uniformly, so upper-layer agents never parse unstructured logs directly.
  • Version the analysis code. Do not keep only the model's natural-language explanation in a production system.
  • Bake common dependencies such as pandas, openpyxl, plotting libraries, and business SDKs into the template.
  • Keep end-user-visible results separate from troubleshooting logs, and never return full stack traces or sensitive data directly.

Next Steps

Agent Context
Agent Governance & Evolution
Store
Application Marketplace