← Blog

Use case: a text-to-SQL agent that queries a read-only copy in a sandbox

Let a model answer questions with SQL without giving it your database. Copy a SQLite extract into a Firecracker sandbox, open it read-only, cap rows, and return results as JSON to a Vercel AI SDK tool. Type-checked, with the runner tested.

Text-to-SQL is one of the most useful things to put in front of a model, and one of the easiest to get wrong. The usual risks:

  • The model writes a DELETE or UPDATE, through a prompt injection or a plain mistake.
  • A query scans a huge table and takes the production database with it.
  • Results with personal data flow into the conversation.
  • The model is pointed at more data than the question needs.

This use case answers questions over a copy of the data, in a Sandscale sandbox, opened read-only. The production database never sees the model’s SQL.

The shape

  1. Export the tables the agent needs to a SQLite file. Leave out what it does not need, and mask columns it should not see.
  2. Start a sandbox, write the file in, and read its schema.
  3. Give the model one tool, run_sql, that runs a query against the copy in read-only mode and returns at most 200 rows as JSON.
  4. Stop the sandbox when the answer is in. Stopping deletes its disk, copy included.

The code

Uses the Vercel AI SDK for the tool loop. Type-checked with tsc --strict against ai 7, @ai-sdk/openai, zod 4 and @sandscale/sdk 1.0. The Python runner inside the sandbox was tested separately against a SQLite file: SELECT returns columns and rows, more than 200 rows sets truncated, and a DELETE fails with “attempt to write a readonly database”.

import { generateText, tool, isStepCount } from 'ai';
import { openai } from '@ai-sdk/openai';
import { readFile } from 'node:fs/promises';
import { z } from 'zod';
import { Sandscale } from '@sandscale/sdk';

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

// Runs inside the sandbox. Opens the database read-only, caps rows, prints JSON.
const RUNNER = `
import json, sqlite3, sys
sql = open('/workspace/query.sql').read()
con = sqlite3.connect('file:/workspace/db.sqlite?mode=ro', uri=True)
con.execute('PRAGMA query_only = ON')
cur = con.execute(sql)
cols = [d[0] for d in cur.description or []]
rows = cur.fetchmany(201)
print(json.dumps({"columns": cols, "rows": rows[:200], "truncated": len(rows) > 200}, default=str))
`;

export async function askDatabase(question: string, sqlitePath: string) {
  const sb = await sandscale.sandboxes.create({
    template: 'builtin:python',
    timeoutSeconds: 900,
    labels: { app: 'text-to-sql' },
  });
  const opts = { region: sb.region };
  try {
    await sandscale.sandboxes.writeFile(sb.id, '/workspace/db.sqlite', await readFile(sqlitePath), opts);
    await sandscale.sandboxes.writeFile(sb.id, '/workspace/run.py', RUNNER, opts);
    const schema = await sandscale.sandboxes.run(
      sb.id,
      ['python3', '-c', "import sqlite3;c=sqlite3.connect('/workspace/db.sqlite');print('\\n'.join(r[0] for r in c.execute(\"select sql from sqlite_master where sql is not null\")))"],
      { ...opts, timeoutSeconds: 30 },
    );

    const result = await generateText({
      model: openai('gpt-4.1'),
      system:
        'Answer questions about a SQLite database by writing SQL. Use only SELECT statements. ' +
        'Results are capped at 200 rows; aggregate in SQL instead of reading raw rows. ' +
        'In your answer, include the final SQL you used.\n\nSchema:\n' + schema.stdout,
      prompt: question,
      tools: {
        run_sql: tool({
          description: 'Run one read-only SQL query against the database. Returns columns and up to 200 rows as JSON.',
          inputSchema: z.object({ sql: z.string().max(10_000) }),
          execute: async ({ sql }) => {
            await sandscale.sandboxes.writeFile(sb.id, '/workspace/query.sql', sql, opts);
            const r = await sandscale.sandboxes.run(sb.id, ['python3', '/workspace/run.py'], {
              ...opts,
              timeoutSeconds: 60,
            });
            if (r.timedOut) return { error: 'query timed out; narrow it or add a WHERE clause' };
            if (r.exitCode !== 0) return { error: r.stderr.slice(-2_000) };
            return JSON.parse(r.stdout);
          },
        }),
      },
      stopWhen: isStepCount(12),
    });
    return result.text;
  } finally {
    await sandscale.sandboxes.stop(sb.id, opts);
  }
}

The layers, and what each one stops

A copy, not a connection. The model’s SQL never reaches your production database, so no query can lock a table or slow your app, and no write can land there.

Read-only at three levels. The runner opens the file with SQLite’s mode=ro URI parameter and sets PRAGMA query_only = ON. Either alone rejects writes. And the copy is disposable: if both failed, the damage would be confined to a file that is deleted when the sandbox stops.

A box with no network. The sandbox is created without a network option, and the SDK’s default is none. Even if the model persuaded the runner to do something unexpected, there is nowhere to send the data.

Time and row caps. Each query runs with a time limit (60, in seconds); a timed-out query returns an error the model can act on (“narrow it”). Results are capped at 200 rows, and the system prompt tells the model to aggregate in SQL. That keeps context small and nudges the model toward the right kind of query.

Errors go back to the model. SQLite’s error message, such as a missing column, is returned as the tool result. The model fixes its query on the next step, which is most of what makes text-to-SQL work in practice.

The schema up front. The schema is read once, inside the sandbox, and put in the system prompt, so the model does not spend steps discovering tables.

What the copy should contain

The sandbox protects your database from the model. It does not decide what the model may know. Every row a query returns goes into the conversation. So:

  • Export only the tables and columns the questions need.
  • Replace direct identifiers with stable surrogates if questions are about patterns, not people.
  • For broader coverage, look at Sandscale’s DLP on prompts and tool calls, which is on every plan.

Bigger data

For exports too large to upload with one writeFile call (the API refuses oversized files with file_too_large), prepare a snapshot that already contains the extract, so each question starts with the data in place. For engines other than SQLite, such as DuckDB over Parquet files, the pattern is the same: a template with the engine installed, files in /workspace, and a runner that opens them read-only.

Cost

A question that takes a few queries runs for a short time and stops its box. Awake vCPU-hours come from your plan: 100 a month on Free, 1,500 on Pro, 2,000 per member pooled on Team.

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

Keep reading