# A LlamaIndex.TS data agent that runs its Python in a Sandscale sandbox

> Source: <https://dev.to/sandscale/a-llamaindexts-data-agent-that-runs-its-python-in-a-sandscale-sandbox-4e4e>
> Published: 2026-11-27 04:40:03+00:00

**Recommendation:** Construct sandbox-scoped tools that close over a single sandbox ID instead of exposing it as a parameter, and stop the sandbox in a finally block after each run.
More in the playbook "Securing agents and AI tools": <https://wpnews.pro/playbooks/agent-security>

LlamaIndex is best known for retrieval, but its agent workflows are a good fit for a different kind of question: the ones you answer by computing, not by looking up. "Which region grew fastest last quarter?" over a few CSV files is a job for a short Python script. This guide builds a LlamaIndex.TS agent that writes that script and runs it in a [Sandscale sandbox](https://sandscale.dev/sandboxes), so code the model wrote never runs on your server.

Type-checked with `tsc --strict` against `llamaindex` 0.12, `@llamaindex/workflow` 1.1, `@llamaindex/openai` 0.4, `zod` 4 and `@sandscale/sdk` 1.0. The Sandscale calls are from the [TypeScript SDK reference](https://sandscale.dev/docs/sdks/typescript).

```
npm install llamaindex @llamaindex/workflow @llamaindex/openai zod @sandscale/sdk
export SANDSCALE_API_KEY=...
export OPENAI_API_KEY=...
js
import { tool } from 'llamaindex';
import { agent } from '@llamaindex/workflow';
import { openai } from '@llamaindex/openai';
import { z } from 'zod';
import { Sandscale } from '@sandscale/sdk';

const sandscale = new Sandscale(); // reads SANDSCALE_API_KEY

const clip = (s: string, n = 8_000) => (s.length > n ? s.slice(0, n) + `\n[cut ${s.length - n} chars]` : s);

// Tools are built per sandbox, so each agent run can only reach its own box.
function sandboxTools(sandboxId: string, region?: string) {
  const runPython = tool({
    name: 'run_python',
    description:
      'Run a Python 3 script in an isolated sandbox with the data files in /workspace/data. ' +
      'Print what you need to see. There is no network access. Output over 8,000 characters is cut.',
    parameters: z.object({
      code: z.string().max(20_000),
    }),
    execute: async ({ code }) => {
      await sandscale.sandboxes.writeFile(sandboxId, '/workspace/main.py', code, { region });
      const r = await sandscale.sandboxes.run(sandboxId, ['python3', '/workspace/main.py'], {
        region,
        workdir: '/workspace',
        timeoutSeconds: 120,
      });
      return {
        exit_code: r.exitCode,
        timed_out: r.timedOut,
        oom_killed: r.oomKilled,
        stdout: clip(r.stdout),
        stderr: clip(r.stderr, 4_000),
      };
    },
  });

  const listData = tool({
    name: 'list_data_files',
    description: 'List the data files available in /workspace/data.',
    parameters: z.object({}),
    execute: async () => {
      const entries = await sandscale.sandboxes.listFiles(sandboxId, '/workspace/data', { region });
      return entries.map((e) => e.name);
    },
  });

  return [runPython, listData];
}

export async function ask(question: string, files: Record<string, string>) {
  const sb = await sandscale.sandboxes.create({
    template: 'builtin:python',
    timeoutSeconds: 1800,
    labels: { app: 'llamaindex-analyst' },
  });
  try {
    await sandscale.sandboxes.run(sb.id, ['mkdir', '-p', '/workspace/data'], { region: sb.region });
    for (const [name, content] of Object.entries(files)) {
      await sandscale.sandboxes.writeFile(sb.id, `/workspace/data/${name}`, content, { region: sb.region });
    }
    const analyst = agent({
      llm: openai({ model: 'gpt-4.1' }),
      tools: sandboxTools(sb.id, sb.region),
      systemPrompt:
        'Answer questions about the files in /workspace/data by writing and running Python. ' +
        'Use only the standard library. Show the numbers your answer is based on.',
    });
    const result = await analyst.run(question);
    return result.data.result;
  } finally {
    await sandscale.sandboxes.stop(sb.id, { region: sb.region });
  }
}
```

**Tools are created per sandbox.** `sandboxTools(sandboxId, region)` closes over one sandbox id and returns tools that can only reach that box. There is no shared state for a concurrent request to trample, and no way for the model to pass a different sandbox id, because the id is not a tool parameter. The agent is built inside `ask` for the same reason.

**The data goes in before the agent starts.** `ask` creates the sandbox, makes `/workspace/data`, and writes each file with `writeFile`. The agent's first move is usually `list_data_files`, then a script that reads the headers. Everything it computes comes from files you put there.

**The script is a file, not an argument.** `run_python` writes the code to `/workspace/main.py` and runs `python3` on it. That avoids quoting problems with `python -c`, and leaves the last script in the box, which is handy if you keep the sandbox for debugging.

**Standard library only, no network.** The sandbox is created without `network`, which the SDK defaults to `none`, and the system prompt says to use only the standard library. `csv`, `statistics` and `collections` go a long way for questions over a few files. If you need pandas, build a template whose image includes it, or create the box with `network: 'allowlist'` where your plan includes it and let the agent install packages.

**Results the model can reason about.** The tool returns `exit_code`, `timed_out`, `oom_killed`, stdout and stderr. A traceback in stderr is the most common outcome on the first try, and the model fixes it on the next.

**A per-command limit.** Each run has `timeoutSeconds: 120`. A runaway loop ends there and the model sees `timed_out: true`. The sandbox itself has `timeoutSeconds: 1800` as a backstop, and `finally` stops it as soon as `ask` returns.

The natural LlamaIndex extension is to add a query engine tool alongside `run_python`: retrieval answers "what does the contract say about late fees?", the sandbox answers "how much did late fees total last year?" from the exported ledger. Keep the two tools' descriptions clear about which questions each one answers, and keep documents that only need reading out of the sandbox.

The sandbox is a separate microVM with no network, so the model's code cannot send the data anywhere. What the model sees is another matter: anything the script prints goes back into the conversation. If the files contain personal data, have the agent print aggregates rather than rows, and look at Sandscale's [DLP on prompts and tool calls](https://sandscale.dev/security), which is on every plan. [Safe data analysis with LLM-generated Python](https://sandscale.dev/blog/safe-data-analysis-with-llm-generated-python) covers the wider design.

Each `ask` call uses awake vCPU-hours while its sandbox runs: 100 a month on Free, 1,500 on Pro, 2,000 per member pooled on Team. A question that takes a few tool calls and then stops its box uses very little.

*Originally published on the [Sandscale blog](https://sandscale.dev/blog/llamaindex-ts-agent-with-sandscale).*
