Skip to content

raminious/sql-analyst-ai-agent

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SQL Analyst Agent

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.

How It Works

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)

Prerequisites

Setup

# 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 seed

Usage

node 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?"

Example Questions

  • "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?"

Project Structure

├── 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

Database

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.

License

MIT

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors