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

> Use LlamaIndex.TS's agent workflow with tools that write and run Python in a Firecracker sandbox, built per sandbox so a run can only reach its own box. Upload data files, answer with the numbers, clean up. Type-checked.

Use LlamaIndex.TS's agent workflow with tools that write and run Python in a Firecracker sandbox, built per sandbox so a run can only reach its own box. Upload data files, answer with the numbers, clean up. Type-checked.

November 27, 2026 · 4 min read · The Sandscale team

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).

## Install

```bash
npm install llamaindex @llamaindex/workflow @llamaindex/openai zod @sandscale/sdk
export SANDSCALE_API_KEY=...
export OPENAI_API_KEY=...
```

## The code

```ts
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 });
  }
}
```

## Design choices

**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.

## Combining it with retrieval

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.

## When the data is sensitive

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.

## Cost

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.

**On this page**

1. Install
2. The code
3. Design choices
4. Combining it with retrieval
5. When the data is sensitive
6. Cost

**Run your agents in a box of their own**

Each sandbox is a Firecracker microVM. Free includes 100 awake vCPU-hours a month.

[Start free](https://cloud.sandscale.dev/auth/signup)

## Keep reading

- [November 27, 2026 · **Adding the Sandscale MCP server to Codex: config.toml, OAuth login and approval modes** · Configure the remote or local Sandscale MCP server in OpenAI Codex, sign in with codex mcp login, and use enabled_tools, approval modes and tool timeouts to match what each tool does.](https://sandscale.dev/blog/sandscale-mcp-server-in-codex)
- [November 27, 2026 · **Claude tool use with a Sandscale sandbox: the whole loop in one file** · A complete tool-use loop with the Anthropic TypeScript SDK where Claude's run_command and write_file calls execute in a Firecracker sandbox. Tool schemas, tool_result blocks with is_error, a turn limit and cleanup. Type-checked.](https://sandscale.dev/blog/claude-api-tool-use-with-sandscale)

---
Source: https://sandscale.dev/blog/llamaindex-ts-agent-with-sandscale
