Upload 10 files
Browse files- README.md +282 -20
- agents/langchain_sql_agent.py +142 -0
- agents/sql_agent.py +111 -0
- app.py +100 -0
- database/create_db.py +82 -0
- database/ecommerce.db +0 -0
- database/seed_db.py +141 -0
- prompts/sql_prompt.py +67 -0
- utils/query_engine.py +28 -0
- utils/sql_utils.py +12 -0
README.md
CHANGED
|
@@ -1,20 +1,282 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
--
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🤖 GenAI Text2SQL Analytics Assistant
|
| 2 |
+
|
| 3 |
+
An advanced Generative AI-powered analytics assistant that converts natural language questions into executable SQL queries and retrieves insights from a live relational database.
|
| 4 |
+
|
| 5 |
+
Built using LangChain, Groq LLMs, SQLAlchemy, SQLite, and Streamlit.
|
| 6 |
+
|
| 7 |
+
---
|
| 8 |
+
|
| 9 |
+
# 🚀 Features
|
| 10 |
+
|
| 11 |
+
- Natural Language to SQL Conversion
|
| 12 |
+
- Live Database Query Execution
|
| 13 |
+
- AI-Powered Business Analytics
|
| 14 |
+
- SQL Query Transparency
|
| 15 |
+
- Interactive Analytics Dashboard
|
| 16 |
+
- CSV Export Functionality
|
| 17 |
+
- Automatic SQL Cleaning & Validation
|
| 18 |
+
- Multi-table SQL Reasoning
|
| 19 |
+
- Conversational Analytics Experience
|
| 20 |
+
- Real-time Data Insights
|
| 21 |
+
|
| 22 |
+
---
|
| 23 |
+
|
| 24 |
+
# 🧠 How It Works
|
| 25 |
+
|
| 26 |
+
The application does not train a custom AI model.
|
| 27 |
+
|
| 28 |
+
Instead, it uses a Large Language Model (LLM) to:
|
| 29 |
+
1. Understand the user's business question
|
| 30 |
+
2. Generate optimized SQL queries dynamically
|
| 31 |
+
3. Execute queries on a live SQLite database
|
| 32 |
+
4. Return analytics results and business insights
|
| 33 |
+
|
| 34 |
+
---
|
| 35 |
+
|
| 36 |
+
# 🏗️ Architecture
|
| 37 |
+
|
| 38 |
+
```text
|
| 39 |
+
User Query
|
| 40 |
+
↓
|
| 41 |
+
LLM (Groq + LangChain)
|
| 42 |
+
↓
|
| 43 |
+
SQL Query Generation
|
| 44 |
+
↓
|
| 45 |
+
SQLite Database Execution
|
| 46 |
+
↓
|
| 47 |
+
Analytics Results
|
| 48 |
+
↓
|
| 49 |
+
AI Business Summary + Visualization
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
---
|
| 53 |
+
|
| 54 |
+
# 🛠️ Tech Stack
|
| 55 |
+
|
| 56 |
+
| Category | Technology |
|
| 57 |
+
|---|---|
|
| 58 |
+
| LLM Provider | Groq |
|
| 59 |
+
| Framework | LangChain |
|
| 60 |
+
| Database | SQLite |
|
| 61 |
+
| ORM | SQLAlchemy |
|
| 62 |
+
| Frontend | Streamlit |
|
| 63 |
+
| Data Generation | Faker |
|
| 64 |
+
| Data Processing | Pandas |
|
| 65 |
+
| Language | Python |
|
| 66 |
+
|
| 67 |
+
---
|
| 68 |
+
|
| 69 |
+
# 📂 Project Structure
|
| 70 |
+
|
| 71 |
+
```bash
|
| 72 |
+
TEXT2SQL-GENAI/
|
| 73 |
+
│
|
| 74 |
+
├── agents/
|
| 75 |
+
│ ├── sql_agent.py
|
| 76 |
+
│ └── langchain_sql_agent.py
|
| 77 |
+
│
|
| 78 |
+
├── database/
|
| 79 |
+
│ ├── create_db.py
|
| 80 |
+
│ ├── seed_data.py
|
| 81 |
+
│ └── ecommerce.db
|
| 82 |
+
│
|
| 83 |
+
├── prompts/
|
| 84 |
+
│ └── sql_prompt.py
|
| 85 |
+
│
|
| 86 |
+
├── utils/
|
| 87 |
+
│ ├── sql_utils.py
|
| 88 |
+
│ └── query_engine.py
|
| 89 |
+
│
|
| 90 |
+
├── app.py
|
| 91 |
+
├── requirements.txt
|
| 92 |
+
├── .env
|
| 93 |
+
└── README.md
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
---
|
| 97 |
+
|
| 98 |
+
# 🗄️ Database Schema
|
| 99 |
+
|
| 100 |
+
The project uses a relational e-commerce database containing:
|
| 101 |
+
|
| 102 |
+
- Customers
|
| 103 |
+
- Products
|
| 104 |
+
- Employees
|
| 105 |
+
- Orders
|
| 106 |
+
- Order Items
|
| 107 |
+
|
| 108 |
+
The database was populated with synthetic business data using Faker.
|
| 109 |
+
|
| 110 |
+
---
|
| 111 |
+
|
| 112 |
+
# 📊 Example Questions
|
| 113 |
+
|
| 114 |
+
```text
|
| 115 |
+
Top 5 products by revenue
|
| 116 |
+
```
|
| 117 |
+
|
| 118 |
+
```text
|
| 119 |
+
Which employee handled the most orders?
|
| 120 |
+
```
|
| 121 |
+
|
| 122 |
+
```text
|
| 123 |
+
Average order value by city
|
| 124 |
+
```
|
| 125 |
+
|
| 126 |
+
```text
|
| 127 |
+
Show revenue by product category
|
| 128 |
+
```
|
| 129 |
+
|
| 130 |
+
```text
|
| 131 |
+
Top customers by spending
|
| 132 |
+
```
|
| 133 |
+
|
| 134 |
+
---
|
| 135 |
+
|
| 136 |
+
# 🔥 Advanced Features Implemented
|
| 137 |
+
|
| 138 |
+
## ✅ Schema-Aware Prompting
|
| 139 |
+
Injected database schema directly into prompts to improve SQL accuracy.
|
| 140 |
+
|
| 141 |
+
## ✅ SQL Cleaning
|
| 142 |
+
Automatically removes markdown formatting and cleans generated SQL.
|
| 143 |
+
|
| 144 |
+
## ✅ Error Handling & Retry Logic
|
| 145 |
+
Detects invalid SQL queries and retries with correction prompts.
|
| 146 |
+
|
| 147 |
+
## ✅ LangChain SQL Agent
|
| 148 |
+
Implemented autonomous SQL reasoning using LangChain SQL Agent.
|
| 149 |
+
|
| 150 |
+
## ✅ AI Business Summaries
|
| 151 |
+
Generates human-readable business insights from query results.
|
| 152 |
+
|
| 153 |
+
## ✅ Interactive Analytics Dashboard
|
| 154 |
+
Built using Streamlit with:
|
| 155 |
+
- Data tables
|
| 156 |
+
- SQL visibility
|
| 157 |
+
- CSV export
|
| 158 |
+
- Charts and visualizations
|
| 159 |
+
|
| 160 |
+
---
|
| 161 |
+
|
| 162 |
+
# 📈 Sample Analytics Capabilities
|
| 163 |
+
|
| 164 |
+
- Revenue Analysis
|
| 165 |
+
- Customer Segmentation
|
| 166 |
+
- Product Performance
|
| 167 |
+
- Sales Trends
|
| 168 |
+
- Employee Performance Metrics
|
| 169 |
+
- Business Intelligence Reporting
|
| 170 |
+
|
| 171 |
+
---
|
| 172 |
+
|
| 173 |
+
# ⚙️ Installation
|
| 174 |
+
|
| 175 |
+
## 1️⃣ Clone Repository
|
| 176 |
+
|
| 177 |
+
```bash
|
| 178 |
+
git clone <your_repo_url>
|
| 179 |
+
cd TEXT2SQL-GENAI
|
| 180 |
+
```
|
| 181 |
+
|
| 182 |
+
---
|
| 183 |
+
|
| 184 |
+
## 2️⃣ Create Virtual Environment
|
| 185 |
+
|
| 186 |
+
### Windows
|
| 187 |
+
|
| 188 |
+
```bash
|
| 189 |
+
python -m venv venv
|
| 190 |
+
venv\Scripts\activate
|
| 191 |
+
```
|
| 192 |
+
|
| 193 |
+
---
|
| 194 |
+
|
| 195 |
+
## 3️⃣ Install Dependencies
|
| 196 |
+
|
| 197 |
+
```bash
|
| 198 |
+
pip install -r requirements.txt
|
| 199 |
+
```
|
| 200 |
+
|
| 201 |
+
---
|
| 202 |
+
|
| 203 |
+
## 4️⃣ Configure Environment Variables
|
| 204 |
+
|
| 205 |
+
Create `.env`
|
| 206 |
+
|
| 207 |
+
```env
|
| 208 |
+
GROQ_API_KEY=your_api_key_here
|
| 209 |
+
```
|
| 210 |
+
|
| 211 |
+
---
|
| 212 |
+
|
| 213 |
+
# ▶️ Running The Project
|
| 214 |
+
|
| 215 |
+
## Step 1 — Create Database
|
| 216 |
+
|
| 217 |
+
```bash
|
| 218 |
+
python database/create_db.py
|
| 219 |
+
```
|
| 220 |
+
|
| 221 |
+
---
|
| 222 |
+
|
| 223 |
+
## Step 2 — Seed Database
|
| 224 |
+
|
| 225 |
+
```bash
|
| 226 |
+
python database/seed_data.py
|
| 227 |
+
```
|
| 228 |
+
|
| 229 |
+
---
|
| 230 |
+
|
| 231 |
+
## Step 3 — Run Streamlit App
|
| 232 |
+
|
| 233 |
+
```bash
|
| 234 |
+
streamlit run app.py
|
| 235 |
+
```
|
| 236 |
+
|
| 237 |
+
---
|
| 238 |
+
|
| 239 |
+
# 🌟 Key Learning Outcomes
|
| 240 |
+
|
| 241 |
+
- Generative AI Application Development
|
| 242 |
+
- Prompt Engineering
|
| 243 |
+
- LangChain Agent Workflows
|
| 244 |
+
- SQL Query Generation
|
| 245 |
+
- Database Integration with LLMs
|
| 246 |
+
- Conversational Analytics Systems
|
| 247 |
+
- Streamlit Dashboard Development
|
| 248 |
+
- AI-powered Business Intelligence
|
| 249 |
+
|
| 250 |
+
---
|
| 251 |
+
|
| 252 |
+
# 🎯 Future Improvements
|
| 253 |
+
|
| 254 |
+
- PostgreSQL Support
|
| 255 |
+
- Authentication System
|
| 256 |
+
- Query History
|
| 257 |
+
- Role-Based Access Control
|
| 258 |
+
- Real-time Streaming Responses
|
| 259 |
+
- Data Upload & Auto Analysis
|
| 260 |
+
- Multi-turn Conversational Memory
|
| 261 |
+
- Advanced Chart Visualizations
|
| 262 |
+
|
| 263 |
+
---
|
| 264 |
+
|
| 265 |
+
# 📌 Important Note
|
| 266 |
+
|
| 267 |
+
This project does not fine-tune or train an LLM.
|
| 268 |
+
|
| 269 |
+
Instead, it demonstrates:
|
| 270 |
+
- LLM orchestration
|
| 271 |
+
- schema-aware prompting
|
| 272 |
+
- live SQL generation
|
| 273 |
+
- autonomous database querying
|
| 274 |
+
- AI analytics workflows
|
| 275 |
+
|
| 276 |
+
which closely reflects real-world enterprise GenAI systems.
|
| 277 |
+
|
| 278 |
+
---
|
| 279 |
+
|
| 280 |
+
# 👨💻 Author
|
| 281 |
+
|
| 282 |
+
Mohd Faizanullah
|
agents/langchain_sql_agent.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
|
| 4 |
+
from dotenv import load_dotenv
|
| 5 |
+
|
| 6 |
+
from langchain_groq import ChatGroq
|
| 7 |
+
from langchain_core.messages import HumanMessage, SystemMessage
|
| 8 |
+
|
| 9 |
+
from utils.query_engine import run_query
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
load_dotenv()
|
| 13 |
+
|
| 14 |
+
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
llm = ChatGroq(
|
| 19 |
+
groq_api_key=GROQ_API_KEY,
|
| 20 |
+
model_name="llama-3.3-70b-versatile",
|
| 21 |
+
temperature=0
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
SYSTEM_PROMPT = """
|
| 27 |
+
You are an expert SQL assistant.
|
| 28 |
+
|
| 29 |
+
IMPORTANT:
|
| 30 |
+
1. Generate ONLY SQLite SQL queries.
|
| 31 |
+
2. Do not explain anything.
|
| 32 |
+
3. Use valid SQLite syntax.
|
| 33 |
+
4. Return only executable SQL.
|
| 34 |
+
|
| 35 |
+
DATABASE TABLES:
|
| 36 |
+
|
| 37 |
+
customers(
|
| 38 |
+
customer_id,
|
| 39 |
+
name,
|
| 40 |
+
email,
|
| 41 |
+
city,
|
| 42 |
+
signup_date
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
products(
|
| 46 |
+
product_id,
|
| 47 |
+
product_name,
|
| 48 |
+
category,
|
| 49 |
+
price,
|
| 50 |
+
stock
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
employees(
|
| 54 |
+
employee_id,
|
| 55 |
+
employee_name,
|
| 56 |
+
department
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
orders(
|
| 60 |
+
order_id,
|
| 61 |
+
customer_id,
|
| 62 |
+
employee_id,
|
| 63 |
+
order_date,
|
| 64 |
+
total_amount
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
order_items(
|
| 68 |
+
order_item_id,
|
| 69 |
+
order_id,
|
| 70 |
+
product_id,
|
| 71 |
+
quantity
|
| 72 |
+
)
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def clean_sql(query):
|
| 78 |
+
|
| 79 |
+
query = query.replace("```sql", "")
|
| 80 |
+
query = query.replace("```", "")
|
| 81 |
+
|
| 82 |
+
return query.strip()
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def generate_sql(question):
|
| 87 |
+
|
| 88 |
+
messages = [
|
| 89 |
+
SystemMessage(content=SYSTEM_PROMPT),
|
| 90 |
+
HumanMessage(content=question)
|
| 91 |
+
]
|
| 92 |
+
|
| 93 |
+
response = llm.invoke(messages)
|
| 94 |
+
|
| 95 |
+
sql_query = clean_sql(response.content)
|
| 96 |
+
|
| 97 |
+
return sql_query
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def generate_summary(question, dataframe):
|
| 102 |
+
|
| 103 |
+
summary_prompt = f"""
|
| 104 |
+
User Question:
|
| 105 |
+
{question}
|
| 106 |
+
|
| 107 |
+
Query Result:
|
| 108 |
+
{dataframe.head(10).to_string()}
|
| 109 |
+
|
| 110 |
+
Generate a short business summary.
|
| 111 |
+
"""
|
| 112 |
+
|
| 113 |
+
response = llm.invoke(summary_prompt)
|
| 114 |
+
|
| 115 |
+
return response.content
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def ask_agent(question):
|
| 120 |
+
|
| 121 |
+
try:
|
| 122 |
+
|
| 123 |
+
# Generate SQL
|
| 124 |
+
sql_query = generate_sql(question)
|
| 125 |
+
|
| 126 |
+
# Execute Query
|
| 127 |
+
result_df = run_query(sql_query)
|
| 128 |
+
|
| 129 |
+
# Generate Summary
|
| 130 |
+
summary = generate_summary(question, result_df)
|
| 131 |
+
|
| 132 |
+
return {
|
| 133 |
+
"sql": sql_query,
|
| 134 |
+
"data": result_df,
|
| 135 |
+
"summary": summary
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
except Exception as e:
|
| 139 |
+
|
| 140 |
+
return {
|
| 141 |
+
"error": str(e)
|
| 142 |
+
}
|
agents/sql_agent.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from dotenv import load_dotenv
|
| 3 |
+
|
| 4 |
+
from langchain_groq import ChatGroq
|
| 5 |
+
from langchain_core.messages import HumanMessage, SystemMessage
|
| 6 |
+
|
| 7 |
+
from sqlalchemy import create_engine, text
|
| 8 |
+
import pandas as pd
|
| 9 |
+
|
| 10 |
+
from prompts.sql_prompt import SYSTEM_PROMPT
|
| 11 |
+
from utils.sql_utils import clean_sql_query
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
load_dotenv()
|
| 16 |
+
|
| 17 |
+
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
llm = ChatGroq(
|
| 22 |
+
groq_api_key=GROQ_API_KEY,
|
| 23 |
+
model_name="llama-3.3-70b-versatile"
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
engine = create_engine("sqlite:///database/ecommerce.db")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def generate_sql(user_question):
|
| 33 |
+
|
| 34 |
+
messages = [
|
| 35 |
+
SystemMessage(content=SYSTEM_PROMPT),
|
| 36 |
+
HumanMessage(content=user_question)
|
| 37 |
+
]
|
| 38 |
+
|
| 39 |
+
response = llm.invoke(messages)
|
| 40 |
+
|
| 41 |
+
sql_query = response.content.strip()
|
| 42 |
+
|
| 43 |
+
cleaned_query = clean_sql_query(sql_query)
|
| 44 |
+
|
| 45 |
+
return cleaned_query
|
| 46 |
+
|
| 47 |
+
# =====================================
|
| 48 |
+
# Execute SQL
|
| 49 |
+
# =====================================
|
| 50 |
+
|
| 51 |
+
def execute_sql(sql_query):
|
| 52 |
+
|
| 53 |
+
try:
|
| 54 |
+
with engine.connect() as connection:
|
| 55 |
+
|
| 56 |
+
result = connection.execute(text(sql_query))
|
| 57 |
+
|
| 58 |
+
rows = result.fetchall()
|
| 59 |
+
|
| 60 |
+
columns = result.keys()
|
| 61 |
+
|
| 62 |
+
df = pd.DataFrame(rows, columns=columns)
|
| 63 |
+
|
| 64 |
+
return df
|
| 65 |
+
|
| 66 |
+
except Exception as e:
|
| 67 |
+
|
| 68 |
+
return f"SQL ERROR: {str(e)}"
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
if __name__ == "__main__":
|
| 73 |
+
|
| 74 |
+
question = input("Ask your question: ")
|
| 75 |
+
|
| 76 |
+
# Generate SQL
|
| 77 |
+
sql_query = generate_sql(question)
|
| 78 |
+
|
| 79 |
+
print("\nGenerated SQL:\n")
|
| 80 |
+
print(sql_query)
|
| 81 |
+
|
| 82 |
+
print("\nExecuting Query...\n")
|
| 83 |
+
|
| 84 |
+
# Execute SQL
|
| 85 |
+
result = execute_sql(sql_query)
|
| 86 |
+
|
| 87 |
+
# Retry if SQL fails
|
| 88 |
+
if isinstance(result, str) and "SQL ERROR" in result:
|
| 89 |
+
|
| 90 |
+
print("\nRetrying with error feedback...\n")
|
| 91 |
+
|
| 92 |
+
retry_prompt = f"""
|
| 93 |
+
The following SQL query failed:
|
| 94 |
+
|
| 95 |
+
{sql_query}
|
| 96 |
+
|
| 97 |
+
Error:
|
| 98 |
+
{result}
|
| 99 |
+
|
| 100 |
+
Generate corrected SQLite SQL only.
|
| 101 |
+
"""
|
| 102 |
+
|
| 103 |
+
corrected_sql = generate_sql(retry_prompt)
|
| 104 |
+
|
| 105 |
+
print("\nCorrected SQL:\n")
|
| 106 |
+
print(corrected_sql)
|
| 107 |
+
|
| 108 |
+
result = execute_sql(corrected_sql)
|
| 109 |
+
|
| 110 |
+
print("\nFinal Result:\n")
|
| 111 |
+
print(result)
|
app.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import pandas as pd
|
| 3 |
+
|
| 4 |
+
from agents.langchain_sql_agent import ask_agent
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
st.set_page_config(
|
| 9 |
+
page_title="GenAI Text2SQL Assistant",
|
| 10 |
+
page_icon="🤖",
|
| 11 |
+
layout="wide"
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
st.title("🤖 GenAI Text2SQL Analytics Assistant")
|
| 17 |
+
|
| 18 |
+
st.markdown("""
|
| 19 |
+
Query your business database using natural language.
|
| 20 |
+
|
| 21 |
+
Examples:
|
| 22 |
+
- Top selling products
|
| 23 |
+
- Revenue by category
|
| 24 |
+
- Monthly sales trend
|
| 25 |
+
- Customer spending analysis
|
| 26 |
+
""")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
question = st.text_input(
|
| 31 |
+
"Ask your business question:"
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
if st.button("Generate Insights"):
|
| 37 |
+
|
| 38 |
+
if question:
|
| 39 |
+
|
| 40 |
+
with st.spinner("Analyzing database..."):
|
| 41 |
+
|
| 42 |
+
response = ask_agent(question)
|
| 43 |
+
|
| 44 |
+
# Error Handling
|
| 45 |
+
if "error" in response:
|
| 46 |
+
|
| 47 |
+
st.error(response["error"])
|
| 48 |
+
|
| 49 |
+
else:
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
st.subheader("🧠 Generated SQL")
|
| 53 |
+
|
| 54 |
+
st.code(response["sql"], language="sql")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
st.subheader("📊 Query Results")
|
| 59 |
+
|
| 60 |
+
st.dataframe(
|
| 61 |
+
response["data"],
|
| 62 |
+
use_container_width=True
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
csv = response["data"].to_csv(index=False)
|
| 68 |
+
|
| 69 |
+
st.download_button(
|
| 70 |
+
label="⬇ Download Results CSV",
|
| 71 |
+
data=csv,
|
| 72 |
+
file_name="query_results.csv",
|
| 73 |
+
mime="text/csv"
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
st.subheader("🤖 AI Business Summary")
|
| 79 |
+
|
| 80 |
+
st.write(response["summary"])
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
df = response["data"]
|
| 85 |
+
|
| 86 |
+
if len(df.columns) >= 2:
|
| 87 |
+
|
| 88 |
+
numeric_cols = df.select_dtypes(
|
| 89 |
+
include="number"
|
| 90 |
+
).columns
|
| 91 |
+
|
| 92 |
+
if len(numeric_cols) > 0:
|
| 93 |
+
|
| 94 |
+
st.subheader("📈 Visualization")
|
| 95 |
+
|
| 96 |
+
chart_col = numeric_cols[0]
|
| 97 |
+
|
| 98 |
+
st.bar_chart(
|
| 99 |
+
df.set_index(df.columns[0])[chart_col]
|
| 100 |
+
)
|
database/create_db.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sqlalchemy import create_engine, Column, Integer, String, Float, ForeignKey, Date
|
| 2 |
+
from sqlalchemy.orm import declarative_base, relationship
|
| 3 |
+
from sqlalchemy.orm import sessionmaker
|
| 4 |
+
|
| 5 |
+
engine = create_engine("sqlite:///ecommerce.db")
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
Base = declarative_base()
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Customer(Base):
|
| 12 |
+
__tablename__ = "customers"
|
| 13 |
+
|
| 14 |
+
customer_id = Column(Integer, primary_key=True)
|
| 15 |
+
name = Column(String, nullable=False)
|
| 16 |
+
email = Column(String, unique=True, nullable=False)
|
| 17 |
+
city = Column(String)
|
| 18 |
+
signup_date = Column(Date)
|
| 19 |
+
|
| 20 |
+
orders = relationship("Order", back_populates="customer")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class Product(Base):
|
| 25 |
+
__tablename__ = "products"
|
| 26 |
+
|
| 27 |
+
product_id = Column(Integer, primary_key=True)
|
| 28 |
+
product_name = Column(String, nullable=False)
|
| 29 |
+
category = Column(String)
|
| 30 |
+
price = Column(Float)
|
| 31 |
+
stock = Column(Integer)
|
| 32 |
+
|
| 33 |
+
order_items = relationship("OrderItem", back_populates="product")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class Employee(Base):
|
| 37 |
+
__tablename__ = "employees"
|
| 38 |
+
|
| 39 |
+
employee_id = Column(Integer, primary_key=True)
|
| 40 |
+
employee_name = Column(String, nullable=False)
|
| 41 |
+
department = Column(String)
|
| 42 |
+
|
| 43 |
+
orders = relationship("Order", back_populates="employee")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class Order(Base):
|
| 48 |
+
__tablename__ = "orders"
|
| 49 |
+
|
| 50 |
+
order_id = Column(Integer, primary_key=True)
|
| 51 |
+
|
| 52 |
+
customer_id = Column(Integer, ForeignKey("customers.customer_id"))
|
| 53 |
+
employee_id = Column(Integer, ForeignKey("employees.employee_id"))
|
| 54 |
+
|
| 55 |
+
order_date = Column(Date)
|
| 56 |
+
total_amount = Column(Float)
|
| 57 |
+
|
| 58 |
+
customer = relationship("Customer", back_populates="orders")
|
| 59 |
+
employee = relationship("Employee", back_populates="orders")
|
| 60 |
+
|
| 61 |
+
order_items = relationship("OrderItem", back_populates="order")
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class OrderItem(Base):
|
| 66 |
+
__tablename__ = "order_items"
|
| 67 |
+
|
| 68 |
+
order_item_id = Column(Integer, primary_key=True)
|
| 69 |
+
|
| 70 |
+
order_id = Column(Integer, ForeignKey("orders.order_id"))
|
| 71 |
+
product_id = Column(Integer, ForeignKey("products.product_id"))
|
| 72 |
+
|
| 73 |
+
quantity = Column(Integer)
|
| 74 |
+
|
| 75 |
+
order = relationship("Order", back_populates="order_items")
|
| 76 |
+
product = relationship("Product", back_populates="order_items")
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
Base.metadata.create_all(engine)
|
| 81 |
+
|
| 82 |
+
print(" Database and tables created successfully!")
|
database/ecommerce.db
ADDED
|
Binary file (73.7 kB). View file
|
|
|
database/seed_db.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
from faker import Faker
|
| 3 |
+
from datetime import datetime, timedelta
|
| 4 |
+
|
| 5 |
+
from sqlalchemy import create_engine
|
| 6 |
+
from sqlalchemy.orm import sessionmaker
|
| 7 |
+
|
| 8 |
+
from create_db import (
|
| 9 |
+
Base,
|
| 10 |
+
Customer,
|
| 11 |
+
Product,
|
| 12 |
+
Employee,
|
| 13 |
+
Order,
|
| 14 |
+
OrderItem
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
fake = Faker()
|
| 20 |
+
|
| 21 |
+
engine = create_engine("sqlite:///ecommerce.db")
|
| 22 |
+
Session = sessionmaker(bind=engine)
|
| 23 |
+
|
| 24 |
+
session = Session()
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
customers = []
|
| 29 |
+
|
| 30 |
+
for _ in range(100):
|
| 31 |
+
customer = Customer(
|
| 32 |
+
name=fake.name(),
|
| 33 |
+
email=fake.unique.email(),
|
| 34 |
+
city=fake.city(),
|
| 35 |
+
signup_date=fake.date_between(start_date="-2y", end_date="today")
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
customers.append(customer)
|
| 39 |
+
|
| 40 |
+
session.add_all(customers)
|
| 41 |
+
session.commit()
|
| 42 |
+
|
| 43 |
+
print(" Customers inserted")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
categories = [
|
| 48 |
+
"Electronics",
|
| 49 |
+
"Clothing",
|
| 50 |
+
"Books",
|
| 51 |
+
"Home",
|
| 52 |
+
"Sports"
|
| 53 |
+
]
|
| 54 |
+
|
| 55 |
+
products = []
|
| 56 |
+
|
| 57 |
+
for _ in range(50):
|
| 58 |
+
product = Product(
|
| 59 |
+
product_name=fake.word().capitalize() + " Product",
|
| 60 |
+
category=random.choice(categories),
|
| 61 |
+
price=round(random.uniform(10, 1000), 2),
|
| 62 |
+
stock=random.randint(10, 500)
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
products.append(product)
|
| 66 |
+
|
| 67 |
+
session.add_all(products)
|
| 68 |
+
session.commit()
|
| 69 |
+
|
| 70 |
+
print(" Products inserted")
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
departments = [
|
| 74 |
+
"Sales",
|
| 75 |
+
"Support",
|
| 76 |
+
"Operations",
|
| 77 |
+
"HR"
|
| 78 |
+
]
|
| 79 |
+
|
| 80 |
+
employees = []
|
| 81 |
+
|
| 82 |
+
for _ in range(10):
|
| 83 |
+
employee = Employee(
|
| 84 |
+
employee_name=fake.name(),
|
| 85 |
+
department=random.choice(departments)
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
employees.append(employee)
|
| 89 |
+
|
| 90 |
+
session.add_all(employees)
|
| 91 |
+
session.commit()
|
| 92 |
+
|
| 93 |
+
print(" Employees inserted")
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
orders = []
|
| 98 |
+
|
| 99 |
+
for _ in range(500):
|
| 100 |
+
|
| 101 |
+
customer = random.choice(customers)
|
| 102 |
+
employee = random.choice(employees)
|
| 103 |
+
|
| 104 |
+
order = Order(
|
| 105 |
+
customer_id=customer.customer_id,
|
| 106 |
+
employee_id=employee.employee_id,
|
| 107 |
+
order_date=fake.date_between(start_date="-1y", end_date="today"),
|
| 108 |
+
total_amount=0
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
session.add(order)
|
| 112 |
+
session.flush()
|
| 113 |
+
|
| 114 |
+
total_amount = 0
|
| 115 |
+
|
| 116 |
+
# Each order gets 1-5 products
|
| 117 |
+
for _ in range(random.randint(1, 5)):
|
| 118 |
+
|
| 119 |
+
product = random.choice(products)
|
| 120 |
+
|
| 121 |
+
quantity = random.randint(1, 5)
|
| 122 |
+
|
| 123 |
+
order_item = OrderItem(
|
| 124 |
+
order_id=order.order_id,
|
| 125 |
+
product_id=product.product_id,
|
| 126 |
+
quantity=quantity
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
session.add(order_item)
|
| 130 |
+
|
| 131 |
+
total_amount += product.price * quantity
|
| 132 |
+
|
| 133 |
+
order.total_amount = round(total_amount, 2)
|
| 134 |
+
|
| 135 |
+
orders.append(order)
|
| 136 |
+
|
| 137 |
+
session.commit()
|
| 138 |
+
|
| 139 |
+
print(" Orders and order items inserted")
|
| 140 |
+
|
| 141 |
+
print("\n🎉 Database successfully populated with synthetic data!")
|
prompts/sql_prompt.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
SYSTEM_PROMPT = """
|
| 2 |
+
You are an expert SQL assistant.
|
| 3 |
+
|
| 4 |
+
Your task:
|
| 5 |
+
1. Convert natural language questions into valid SQLite SQL queries.
|
| 6 |
+
2. Only generate SQL.
|
| 7 |
+
3. Do NOT explain anything.
|
| 8 |
+
4. Use only the provided schema.
|
| 9 |
+
|
| 10 |
+
DATABASE SCHEMA:
|
| 11 |
+
|
| 12 |
+
CREATE TABLE customers (
|
| 13 |
+
customer_id INTEGER PRIMARY KEY,
|
| 14 |
+
name TEXT,
|
| 15 |
+
email TEXT,
|
| 16 |
+
city TEXT,
|
| 17 |
+
signup_date DATE
|
| 18 |
+
);
|
| 19 |
+
|
| 20 |
+
CREATE TABLE products (
|
| 21 |
+
product_id INTEGER PRIMARY KEY,
|
| 22 |
+
product_name TEXT,
|
| 23 |
+
category TEXT,
|
| 24 |
+
price FLOAT,
|
| 25 |
+
stock INTEGER
|
| 26 |
+
);
|
| 27 |
+
|
| 28 |
+
CREATE TABLE employees (
|
| 29 |
+
employee_id INTEGER PRIMARY KEY,
|
| 30 |
+
employee_name TEXT,
|
| 31 |
+
department TEXT
|
| 32 |
+
);
|
| 33 |
+
|
| 34 |
+
CREATE TABLE orders (
|
| 35 |
+
order_id INTEGER PRIMARY KEY,
|
| 36 |
+
customer_id INTEGER,
|
| 37 |
+
employee_id INTEGER,
|
| 38 |
+
order_date DATE,
|
| 39 |
+
total_amount FLOAT
|
| 40 |
+
);
|
| 41 |
+
|
| 42 |
+
CREATE TABLE order_items (
|
| 43 |
+
order_item_id INTEGER PRIMARY KEY,
|
| 44 |
+
order_id INTEGER,
|
| 45 |
+
product_id INTEGER,
|
| 46 |
+
quantity INTEGER
|
| 47 |
+
);
|
| 48 |
+
|
| 49 |
+
FEW SHOT EXAMPLES:
|
| 50 |
+
|
| 51 |
+
Q: Show all customers from Hyderabad
|
| 52 |
+
SQL:
|
| 53 |
+
SELECT * FROM customers
|
| 54 |
+
WHERE city = 'Hyderabad';
|
| 55 |
+
|
| 56 |
+
Q: Top 5 products by price
|
| 57 |
+
SQL:
|
| 58 |
+
SELECT product_name, price
|
| 59 |
+
FROM products
|
| 60 |
+
ORDER BY price DESC
|
| 61 |
+
LIMIT 5;
|
| 62 |
+
|
| 63 |
+
Q: Total revenue generated
|
| 64 |
+
SQL:
|
| 65 |
+
SELECT SUM(total_amount) AS total_revenue
|
| 66 |
+
FROM orders;
|
| 67 |
+
"""
|
utils/query_engine.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
from sqlalchemy import create_engine, text
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
engine = create_engine("sqlite:///database/ecommerce.db")
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def run_query(sql_query):
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
|
| 14 |
+
with engine.connect() as connection:
|
| 15 |
+
|
| 16 |
+
result = connection.execute(text(sql_query))
|
| 17 |
+
|
| 18 |
+
rows = result.fetchall()
|
| 19 |
+
|
| 20 |
+
columns = result.keys()
|
| 21 |
+
|
| 22 |
+
df = pd.DataFrame(rows, columns=columns)
|
| 23 |
+
|
| 24 |
+
return df
|
| 25 |
+
|
| 26 |
+
except Exception as e:
|
| 27 |
+
|
| 28 |
+
return str(e)
|
utils/sql_utils.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
def clean_sql_query(query):
|
| 4 |
+
|
| 5 |
+
# Remove markdown SQL formatting
|
| 6 |
+
query = query.replace("```sql", "")
|
| 7 |
+
query = query.replace("```", "")
|
| 8 |
+
|
| 9 |
+
# Remove extra spaces/newlines
|
| 10 |
+
query = query.strip()
|
| 11 |
+
|
| 12 |
+
return query
|