Pranit PatilMumbai IST
All notes

AI · Updated 28 Nov 2026

Text to SQL with an agent loop

How DataBot turns a plain-English question into a safe query and a chart.

Step one: describe the database

A model cannot write a good query for tables it has never seen. So when you connect, DataBot reads the database first and keeps what it learns for the session.

  1. Connection string

  2. Open a pool

    and test it

  3. Read the schema

    tables, columns, comments

  4. Row counts

    plus 5 sample rows per table

  5. Session

    in memory, 1 hour

Fig 1 What happens on connect. The session lives in server memory and expires after an hour.

Column comments and sample rows matter more than they look. A column called status means little on its own. Five real rows showing values like shipped and refunded tell the model exactly what to filter on.

Step two: let the model use tools

Question

“Which products sold most last month?”

Agent loop · up to 10 steps

Model (GPT-4o-mini)

its prompt holds the schema, row counts and sample rows

execute_sql

checked, then run on Postgres. Returns rows, or the error.

Chart tools

14 chart types or a table. Returns a chart config.

Answer

streamed text with the chart

Fig 2 The agent loop. The model chooses which tool to call; DataBot runs it and hands back the result, including any SQL error so the model can fix its query and try again.

Keeping it read-only

Letting a model write SQL against a real database needs a guard. Before running anything, DataBot checks that the query starts with SELECT or WITH and rejects it if it contains words like DROP, DELETE, UPDATE or INSERT.

In the app

Query check

must start with SELECT or WITH, no write keywords

In Postgres

Read-only role

the database refuses writes whatever the query says

Fig 3 Two layers of protection. The check in the app catches mistakes early; a database user with read-only rights is what guarantees nothing can change.

A keyword check is a good first line, but it is matching text, not understanding SQL. Connecting with a user that only has read permission makes the database itself refuse writes, which is the guarantee you want when the query author is a model.

What I would carry into the next one

Next noteServing a small LLM: quantization, the KV cache and an APIStudy notes on fitting a model in GPU memory, why the KV cache matters and what to measure