DEV Community

Sandscale
Sandscale

Posted on Originally published at sandscale.dev

Letting an LLM analyze a CSV without running its code on your server

"Upload a spreadsheet and ask a question about it" is one of the most useful things to build with a language model, and one of the easiest to build badly. Models are poor at arithmetic over thousands of rows in their context window, so the reliable approach is to have the model write a short program and run it. That program is untrusted code. And its output, if you are not careful, is untrusted free text that you then show to a user as fact.

This post builds the pattern end to end in TypeScript: the data and the model's script go into a sandbox, the script must print one JSON object in a fixed shape, the host validates that object, and failures go back to the model as feedback for a small, fixed number of retries.

The shape of the loop

  1. Start one sandbox for the whole question, with a hard lifetime.
  2. Write the CSV into it once.
  3. Ask the model for a script, giving it the header row, the question and the output contract.
  4. Run the script with a command timeout.
  5. If it timed out, ran out of memory, crashed or printed the wrong thing, tell the model what happened and try again, up to a limit.
  6. Return the validated result, and always stop the sandbox.

Two decisions shape the rest.

The model sees the header, not the data. Sending only the header row keeps the prompt small and keeps the rows out of the model's context. The script reads the full file inside the sandbox.

The output is a contract, not prose. The script must print exactly one JSON object with an answer string and a values map of named numbers. Your UI can show the numbers in a table and the answer as a caption, and you can check that every number is actually a number before anyone sees it.

The code

This uses @sandscale/sdk 1.0.0. writeScript is your model call: any function that takes the instructions and returns Python source. Keeping it a parameter keeps the sandbox logic independent of which model or framework you use.

import { Sandscale } from '@sandscale/sdk';

const sandscale = new Sandscale({ apiKey: process.env.SANDSCALE_API_KEY });

// Your model call: takes the instructions and returns Python source.
type WriteScript = (prompt: string) => Promise<string>;

const MAX_OUTPUT = 64 * 1024;
const MAX_ATTEMPTS = 3;

interface Analysis {
  answer: string;
  values: Record<string, number>;
}

function parseAnalysis(stdout: string): Analysis {
  if (stdout.length > MAX_OUTPUT) throw new Error(`output too large: ${stdout.length} characters`);
  const parsed: unknown = JSON.parse(stdout);
  if (typeof parsed !== 'object' || parsed === null) throw new Error('output is not a JSON object');
  const { answer, values } = parsed as { answer?: unknown; values?: unknown };
  if (typeof answer !== 'string') throw new Error('"answer" must be a string');
  if (typeof values !== 'object' || values === null) throw new Error('"values" must be an object');
  for (const [k, v] of Object.entries(values)) {
    if (typeof v !== 'number' || !Number.isFinite(v)) throw new Error(`values.${k} must be a finite number`);
  }
  return { answer, values: values as Record<string, number> };
}

export async function analyzeCsv(csv: string, question: string, writeScript: WriteScript): Promise<Analysis> {
  const box = await sandscale.sandboxes.create({ template: 'builtin:python', timeoutSeconds: 600 });
  const where = { region: box.region };
  try {
    await sandscale.sandboxes.writeFile(box.id, '/workspace/data.csv', csv, where);

    const header = csv.split('\n', 1)[0];
    let feedback = '';
    for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
      const prompt = [
        'Write a Python 3 script that answers the question below about /workspace/data.csv.',
        `The CSV header is: ${header}`,
        'Use only the standard library (csv, statistics, json, math, datetime).',
        'Print exactly one JSON object to stdout: {"answer": string, "values": {name: number}}.',
        'Print nothing else to stdout. Exit with a non-zero status if the data cannot answer the question.',
        `Question: ${question}`,
        feedback,
      ].join('\n');

      const script = await writeScript(prompt);
      await sandscale.sandboxes.writeFile(box.id, '/workspace/analysis.py', script, where);
      const run = await sandscale.sandboxes.run(box.id, ['python3', 'analysis.py'], { ...where, timeoutSeconds: 60 });

      if (run.timedOut) {
        feedback = 'Your previous script ran out of time. Read the file once and avoid nested loops over all rows.';
        continue;
      }
      if (run.oomKilled) {
        feedback = 'Your previous script ran out of memory. Stream rows with csv.reader instead of loading everything.';
        continue;
      }
      if (run.exitCode !== 0) {
        feedback = `Your previous script exited with ${run.exitCode}. The end of stderr was:\n${run.stderr.slice(-2000)}`;
        continue;
      }
      try {
        return parseAnalysis(run.stdout.trim());
      } catch (err) {
        feedback = `Your previous output was rejected: ${(err as Error).message}. Print only the JSON object.`;
      }
    }
    throw new Error(`no valid analysis after ${MAX_ATTEMPTS} attempts`);
  } finally {
    await sandscale.sandboxes.stop(box.id, where);
  }
}
Enter fullscreen mode Exit fullscreen mode

Why each piece is there

One sandbox per question, with a lifetime

The sandbox lives for the whole retry loop, so the CSV is written once and each attempt only replaces analysis.py. timeoutSeconds: 600 on create is the backstop: if your process dies before the finally block runs, the sandbox still stops on its own. Our post on the three timeouts goes into how the sandbox lifetime, command timeout and HTTP timeout relate.

We do not set network, and the SDK documents none as its default, so the script cannot send the data anywhere. Analysis scripts that use the standard library need no network at all.

Standard library only

The prompt tells the model to use only csv, statistics, json, math and datetime. That avoids two problems: depending on what a template happens to have installed, and the model trying to install packages mid-run, which brings its own risks covered in what happens when agents install packages. If you need a dataframe library, build a template with it preinstalled and say so in the prompt.

Specific feedback for each failure

run returns timedOut, oomKilled, exitCode, stdout and stderr, and each failure gets its own message. A timeout and an out-of-memory kill usually mean the same algorithmic mistake, loading or looping over everything, so the feedback says how to fix it. A crash sends back the end of stderr, where Python puts the traceback, truncated to 2,000 characters so a runaway error cannot flood the next prompt.

Validation before display

parseAnalysis rejects output that is too long, not JSON, missing a field, or contains a value that is not a finite number. JSON.parse already rejects the NaN that Python's json.dumps prints by default, but a script can still print a string where you wanted a number, or an empty object. Rejecting it and asking again is cheaper than showing a user "the average is undefined".

Validation checks the shape, not the truth. A script can compute the wrong thing and print a well-formed answer. For questions where it matters, show the script next to the answer, so a person can read the 20 lines that produced the number.

A fixed number of attempts

Three attempts is a choice, not a rule. The important part is that there is a limit: without one, a question the data cannot answer becomes an endless loop of model calls and sandbox runs. When the limit is hit, say so to the user, rather than returning the last bad output.

What the sandbox does and does not protect

The sandbox keeps the model's script away from your server: its files, its environment, its credentials and its network. Each Sandscale sandbox is a Firecracker microVM with its own kernel, and it goes away when you stop it.

It does not protect the data from the script. The script can read every row of data.csv, because that is its job. So do not put anything in the sandbox that the question does not need: if the user asked about revenue by region, consider sending only those columns. And treat the answer string as model output: escape it before rendering, and do not let it trigger further actions without a person looking at it.

Variations

  • Several files. Write each with writeFile, or upload a folder as a gzip tar; see getting code into a sandbox and results out.
  • Charts. Have the script write a PNG to /workspace/chart.png and read it back with readFile. Validate that it is a PNG before serving it.
  • Long analyses. Pass onStdout to run to show progress lines as they arrive; streaming command output covers the details.

The core stays the same: the model writes the code, the sandbox runs it, and your code decides what counts as an answer.

Originally published on the Sandscale blog.

Top comments (0)