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.
Connection string
Open a pool
and test it
Read the schema
tables, columns, comments
Row counts
plus 5 sample rows per table
Session
in memory, 1 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
- Self-correction comes free. If a query fails, the Postgres error goes back to the model as the tool result. It reads the error, fixes the query and calls the tool again.
- Charts are tools too. The model picks a chart type and shapes the rows for it, and the browser renders the configuration with Recharts.
- The loop has a ceiling. The agent stops after 10 steps, so a confused model cannot loop forever.
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
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
- Spend the effort on context: schema, comments and sample rows decide most of the answer quality.
- Return errors to the model instead of hiding them. It is usually able to fix its own query.
- Cap the steps, and put the hard safety limits in the database, not in the prompt.