An AI agent that answers natural-language questions by autonomously querying a SQLite database. Built with the Vercel AI SDK and OpenAI.
The agent follows a tool-use loop: it discovers tables, inspects schemas, writes SQL, and interprets the results — all without manual intervention.
Question → Agent → listTables → describeTable → runSql → Answer
The agent has three tools at its disposal:
| Tool | Purpose |
|---|---|
listTables |
Discover available tables |
describeTable |
Inspect columns, types, and foreign keys |
runSql |
Execute read-only SELECT queries (max 100 rows) |
- Node.js 18+
- An OpenAI API key
# Clone the repo
git clone https://github.com/<your-username>/sql-analyst.git
cd sql-analyst
# Install dependencies
npm install
# Add your API key
cp .env.sample .env
# Edit .env and paste your OpenAI key
# Seed the database
npm run seednode src/main.mjs "Which country has the highest average invoice total?"Or use the npm script:
npm start -- "Who are the top 3 customers by total spend?"- "Which country has the highest average invoice total?"
- "What's the best-selling genre in Japan?"
- "How much revenue did each artist generate?"
- "Who are the top 3 customers by total spend?"
├── src/
│ ├── main.mjs # Entry point — accepts a question via CLI args
│ ├── system.mjs # System prompt for the agent
│ ├── db.mjs # SQLite connection (read-only)
│ └── tools/
│ ├── list-tables.mjs
│ ├── describe-table.mjs
│ └── run-sql.mjs
├── seed.sql # Database schema and sample data
├── seed.mjs # Script to create and populate chinook.db
├── .env.sample # Template for environment variables
└── package.json
The included seed data is a mini music-store schema (inspired by the Chinook dataset) with artists, albums, tracks, customers, invoices, and invoice lines.
Run npm run seed to create the chinook.db file from seed.sql.
MIT