Huzaifa1435 commited on
Commit
345a446
·
0 Parent(s):

Deploy AI SQL Agent Backend

Browse files
Files changed (9) hide show
  1. Dockerfile +23 -0
  2. agent.py +40 -0
  3. app.py +481 -0
  4. config.py +7 -0
  5. create_db.py +49 -0
  6. database.py +72 -0
  7. llm.py +23 -0
  8. prompts.py +50 -0
  9. requirements.txt +8 -0
Dockerfile ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ WORKDIR /app
4
+
5
+ # Install dependencies
6
+ COPY requirements.txt .
7
+ RUN pip install --no-cache-dir -r requirements.txt
8
+
9
+ # Copy all backend files
10
+ COPY . .
11
+
12
+ # Create required dirs
13
+ RUN mkdir -p database databases uploads backup logs
14
+
15
+ # Copy default DB if present (included in repo)
16
+ # If not present, users can upload via the UI
17
+
18
+ EXPOSE 7860
19
+
20
+ ENV FLASK_ENV=production
21
+ ENV PORT=7860
22
+
23
+ CMD ["gunicorn", "--bind", "0.0.0.0:7860", "--workers", "1", "--timeout", "120", "app:app"]
agent.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from llm import generate_sql
2
+ from database import fetch_query, execute_query, get_schema_info, get_db_path
3
+ import pandas as pd
4
+
5
+ ALLOWED = ("SELECT", "INSERT", "UPDATE", "DELETE")
6
+
7
+
8
+ def ask_ai(question: str):
9
+ """
10
+ Takes English question, returns (answer, sql, dataframe_or_none)
11
+ """
12
+ # Build schema from currently active DB
13
+ schema = get_schema_info(get_db_path())
14
+ sql = generate_sql(question, schema_info=schema)
15
+
16
+ sql_upper = sql.upper().strip()
17
+
18
+ # Block unsafe or invalid queries
19
+ if sql_upper == "INVALID_QUERY":
20
+ return ("❌ This question cannot be answered with the current database.", sql, None)
21
+
22
+ if not sql_upper.startswith(ALLOWED):
23
+ return ("❌ Unsafe or unsupported query blocked.", sql, None)
24
+
25
+ try:
26
+ if sql_upper.startswith("SELECT"):
27
+ rows = fetch_query(sql)
28
+
29
+ if not rows:
30
+ return ("No records found.", sql, pd.DataFrame())
31
+
32
+ df = pd.DataFrame(rows)
33
+ return (f"Found {len(df)} record(s).", sql, df)
34
+
35
+ else:
36
+ execute_query(sql)
37
+ return ("✅ Database updated successfully!", sql, None)
38
+
39
+ except Exception as e:
40
+ return (f"❌ Error: {e}", sql, None)
app.py ADDED
@@ -0,0 +1,481 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ AI SQL Agent - Backend Flask API
3
+ Local: python app.py
4
+ HF: gunicorn app:app
5
+ """
6
+
7
+ import os
8
+ import sqlite3
9
+ import shutil
10
+ import json
11
+ from datetime import datetime
12
+ from pathlib import Path
13
+ from werkzeug.utils import secure_filename
14
+ import pandas as pd
15
+ from flask import Flask, request, jsonify, send_file
16
+ from flask_cors import CORS
17
+
18
+ from agent import ask_ai
19
+ from config import MODEL_NAME
20
+ import database as db_module
21
+
22
+ # ==================== APP SETUP ====================
23
+
24
+ app = Flask(__name__)
25
+ CORS(app, origins="*")
26
+
27
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
28
+ DATABASE_FOLDER = os.path.join(BASE_DIR, "databases")
29
+ BACKUP_FOLDER = os.path.join(BASE_DIR, "backup")
30
+ LOG_FOLDER = os.path.join(BASE_DIR, "logs")
31
+
32
+ ALLOWED_EXTENSIONS = {"db", "sqlite", "sqlite3"}
33
+ MAX_FILE_SIZE = 50 * 1024 * 1024 # 50 MB
34
+
35
+ for folder in [DATABASE_FOLDER, BACKUP_FOLDER, LOG_FOLDER]:
36
+ os.makedirs(folder, exist_ok=True)
37
+
38
+ app.config["MAX_CONTENT_LENGTH"] = MAX_FILE_SIZE
39
+
40
+ # ==================== STATE ====================
41
+
42
+ query_count = 0
43
+ message_count = 0
44
+
45
+ # ==================== HELPERS ====================
46
+
47
+ def allowed_file(filename):
48
+ return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
49
+
50
+
51
+ def get_db_tables(db_path):
52
+ try:
53
+ conn = sqlite3.connect(db_path)
54
+ cursor = conn.cursor()
55
+ cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
56
+ tables = [row[0] for row in cursor.fetchall()]
57
+ conn.close()
58
+ return tables
59
+ except Exception:
60
+ return []
61
+
62
+
63
+ def get_table_info(db_path, table_name):
64
+ try:
65
+ conn = sqlite3.connect(db_path)
66
+ cursor = conn.cursor()
67
+ cursor.execute(f"SELECT COUNT(*) FROM [{table_name}]")
68
+ row_count = cursor.fetchone()[0]
69
+ cursor.execute(f"PRAGMA table_info([{table_name}])")
70
+ columns = [row[1] for row in cursor.fetchall()]
71
+ conn.close()
72
+ return {
73
+ "name": table_name,
74
+ "rows": row_count,
75
+ "columns": columns,
76
+ "column_count": len(columns),
77
+ }
78
+ except Exception:
79
+ return None
80
+
81
+
82
+ def get_table_data(db_path, table_name, limit=100):
83
+ try:
84
+ conn = sqlite3.connect(db_path)
85
+ df = pd.read_sql_query(f"SELECT * FROM [{table_name}] LIMIT {limit}", conn)
86
+ conn.close()
87
+ return df.to_dict("records")
88
+ except Exception:
89
+ return []
90
+
91
+
92
+ def log_action(action, details):
93
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
94
+ log_file = os.path.join(LOG_FOLDER, "activity.log")
95
+ with open(log_file, "a") as f:
96
+ f.write(f"[{timestamp}] {action}: {details}\n")
97
+
98
+
99
+ def current_db():
100
+ """Return active DB path or None."""
101
+ path = db_module.get_db_path()
102
+ return path if path and os.path.exists(path) else None
103
+
104
+
105
+ # ==================== ROUTES: STATUS ====================
106
+
107
+ @app.route("/api/health", methods=["GET"])
108
+ def health_check():
109
+ return jsonify({"status": "ok", "timestamp": datetime.now().isoformat()})
110
+
111
+
112
+ @app.route("/api/status", methods=["GET"])
113
+ def get_status():
114
+ cdb = current_db()
115
+ tables = get_db_tables(cdb) if cdb else []
116
+ return jsonify({
117
+ "model": MODEL_NAME,
118
+ "database": os.path.basename(cdb) if cdb else "Not Connected",
119
+ "tables": len(tables),
120
+ "queries": query_count,
121
+ "messages": message_count,
122
+ "timestamp": datetime.now().isoformat(),
123
+ "version": "1.0.0",
124
+ })
125
+
126
+
127
+ # ==================== ROUTES: DATABASE ====================
128
+
129
+ @app.route("/api/upload-database", methods=["POST"])
130
+ def upload_database():
131
+ try:
132
+ if "file" not in request.files:
133
+ return jsonify({"error": "No file provided"}), 400
134
+
135
+ file = request.files["file"]
136
+ if not file or file.filename == "":
137
+ return jsonify({"error": "No file selected"}), 400
138
+
139
+ if not allowed_file(file.filename):
140
+ return jsonify({"error": "Invalid file type. Only .db, .sqlite, .sqlite3 allowed"}), 400
141
+
142
+ filename = secure_filename(file.filename) or "database.db"
143
+ filepath = os.path.join(DATABASE_FOLDER, filename)
144
+ file.save(filepath)
145
+
146
+ # Validate it's a real SQLite file
147
+ try:
148
+ conn = sqlite3.connect(filepath)
149
+ conn.execute("SELECT 1")
150
+ conn.close()
151
+ except Exception:
152
+ os.remove(filepath)
153
+ return jsonify({"error": "Invalid SQLite database file"}), 400
154
+
155
+ db_module.set_db_path(filepath)
156
+ tables = get_db_tables(filepath)
157
+
158
+ log_action("DATABASE_UPLOAD", f"Uploaded {filename}")
159
+
160
+ return jsonify({
161
+ "success": True,
162
+ "message": f"Database uploaded: {filename}",
163
+ "database": filename,
164
+ "tables": tables,
165
+ "table_count": len(tables),
166
+ })
167
+
168
+ except Exception as e:
169
+ log_action("ERROR", f"Upload failed: {e}")
170
+ return jsonify({"error": str(e)}), 500
171
+
172
+
173
+ @app.route("/api/databases", methods=["GET"])
174
+ def list_databases():
175
+ try:
176
+ files = os.listdir(DATABASE_FOLDER)
177
+ databases = []
178
+ cdb = current_db()
179
+ for f in files:
180
+ fp = os.path.join(DATABASE_FOLDER, f)
181
+ if os.path.isfile(fp):
182
+ size = os.path.getsize(fp)
183
+ mtime = datetime.fromtimestamp(os.path.getmtime(fp))
184
+ databases.append({
185
+ "name": f,
186
+ "size": f"{size/1024:.2f} KB",
187
+ "modified": mtime.strftime("%Y-%m-%d %H:%M:%S"),
188
+ })
189
+ return jsonify({
190
+ "databases": databases,
191
+ "current": os.path.basename(cdb) if cdb else None,
192
+ })
193
+ except Exception as e:
194
+ return jsonify({"error": str(e)}), 500
195
+
196
+
197
+ @app.route("/api/select-database/<filename>", methods=["POST"])
198
+ def select_database(filename):
199
+ try:
200
+ filepath = os.path.join(DATABASE_FOLDER, secure_filename(filename))
201
+ if not os.path.exists(filepath):
202
+ return jsonify({"error": "Database not found"}), 404
203
+
204
+ conn = sqlite3.connect(filepath)
205
+ conn.execute("SELECT 1")
206
+ conn.close()
207
+
208
+ db_module.set_db_path(filepath)
209
+ tables = get_db_tables(filepath)
210
+
211
+ log_action("DATABASE_SELECT", filename)
212
+
213
+ return jsonify({
214
+ "success": True,
215
+ "database": filename,
216
+ "tables": tables,
217
+ "table_count": len(tables),
218
+ })
219
+ except Exception as e:
220
+ return jsonify({"error": str(e)}), 500
221
+
222
+
223
+ @app.route("/api/delete-database/<filename>", methods=["DELETE"])
224
+ def delete_database(filename):
225
+ try:
226
+ filepath = os.path.join(DATABASE_FOLDER, secure_filename(filename))
227
+ if not os.path.exists(filepath):
228
+ return jsonify({"error": "Database not found"}), 404
229
+
230
+ cdb = current_db()
231
+ if cdb and os.path.abspath(cdb) == os.path.abspath(filepath):
232
+ db_module.set_db_path(None)
233
+
234
+ os.remove(filepath)
235
+ log_action("DATABASE_DELETE", filename)
236
+ return jsonify({"success": True, "message": f"Deleted {filename}"})
237
+ except Exception as e:
238
+ return jsonify({"error": str(e)}), 500
239
+
240
+
241
+ @app.route("/api/download-database", methods=["GET"])
242
+ def download_database():
243
+ try:
244
+ cdb = current_db()
245
+ if not cdb:
246
+ return jsonify({"error": "No database selected"}), 400
247
+
248
+ log_action("DATABASE_DOWNLOAD", os.path.basename(cdb))
249
+ return send_file(
250
+ cdb,
251
+ as_attachment=True,
252
+ download_name=os.path.basename(cdb),
253
+ mimetype="application/octet-stream",
254
+ )
255
+ except Exception as e:
256
+ return jsonify({"error": str(e)}), 500
257
+
258
+
259
+ # ==================== ROUTES: TABLES ====================
260
+
261
+ @app.route("/api/tables", methods=["GET"])
262
+ def get_tables():
263
+ cdb = current_db()
264
+ if not cdb:
265
+ return jsonify({"error": "No database selected"}), 400
266
+ try:
267
+ tables = get_db_tables(cdb)
268
+ table_info = [get_table_info(cdb, t) for t in tables]
269
+ table_info = [t for t in table_info if t]
270
+ return jsonify({"tables": table_info, "total": len(table_info)})
271
+ except Exception as e:
272
+ return jsonify({"error": str(e)}), 500
273
+
274
+
275
+ @app.route("/api/table/<table_name>", methods=["GET"])
276
+ def get_table(table_name):
277
+ cdb = current_db()
278
+ if not cdb:
279
+ return jsonify({"error": "No database selected"}), 400
280
+ try:
281
+ info = get_table_info(cdb, table_name)
282
+ data = get_table_data(cdb, table_name)
283
+ return jsonify({"table": table_name, "info": info, "data": data, "row_count": len(data)})
284
+ except Exception as e:
285
+ return jsonify({"error": str(e)}), 500
286
+
287
+
288
+ # ==================== ROUTES: QUERY ====================
289
+
290
+ @app.route("/api/query", methods=["POST"])
291
+ def process_query():
292
+ global query_count, message_count
293
+ try:
294
+ body = request.get_json()
295
+ question = (body.get("question") or "").strip()
296
+
297
+ if not question:
298
+ return jsonify({"error": "Question cannot be empty"}), 400
299
+
300
+ cdb = current_db()
301
+ if not cdb:
302
+ return jsonify({"error": "No database selected. Please upload or select a database first."}), 400
303
+
304
+ answer, sql, result_df = ask_ai(question)
305
+
306
+ query_count += 1
307
+ message_count += 1
308
+
309
+ result_data = None
310
+ if isinstance(result_df, pd.DataFrame) and not result_df.empty:
311
+ result_data = result_df.to_dict("records")
312
+
313
+ sql_upper = sql.upper().strip()
314
+ if sql_upper.startswith("SELECT"):
315
+ operation = "SELECT"
316
+ elif sql_upper.startswith("INSERT"):
317
+ operation = "INSERT"
318
+ elif sql_upper.startswith("UPDATE"):
319
+ operation = "UPDATE"
320
+ elif sql_upper.startswith("DELETE"):
321
+ operation = "DELETE"
322
+ else:
323
+ operation = "UNKNOWN"
324
+
325
+ log_action("QUERY", f"{operation} | Q: {question[:60]}")
326
+
327
+ return jsonify({
328
+ "success": True,
329
+ "answer": answer,
330
+ "sql": sql,
331
+ "data": result_data,
332
+ "operation": operation,
333
+ "row_count": len(result_data) if result_data else 0,
334
+ "database": os.path.basename(cdb),
335
+ "timestamp": datetime.now().isoformat(),
336
+ })
337
+
338
+ except Exception as e:
339
+ log_action("ERROR", f"Query failed: {e}")
340
+ return jsonify({"error": str(e)}), 500
341
+
342
+
343
+ # ==================== ROUTES: BACKUP ====================
344
+
345
+ @app.route("/api/backup", methods=["POST"])
346
+ def create_backup():
347
+ cdb = current_db()
348
+ if not cdb:
349
+ return jsonify({"error": "No database selected"}), 400
350
+ try:
351
+ ts = datetime.now().strftime("%Y%m%d_%H%M%S")
352
+ base = os.path.splitext(os.path.basename(cdb))[0]
353
+ backup_name = f"{base}_backup_{ts}.db"
354
+ backup_path = os.path.join(BACKUP_FOLDER, backup_name)
355
+ shutil.copy2(cdb, backup_path)
356
+ log_action("BACKUP_CREATED", backup_name)
357
+ return jsonify({"success": True, "message": f"Backup created: {backup_name}", "backup": backup_name})
358
+ except Exception as e:
359
+ return jsonify({"error": str(e)}), 500
360
+
361
+
362
+ @app.route("/api/backups", methods=["GET"])
363
+ def list_backups():
364
+ try:
365
+ files = os.listdir(BACKUP_FOLDER)
366
+ backups = []
367
+ for f in files:
368
+ fp = os.path.join(BACKUP_FOLDER, f)
369
+ if os.path.isfile(fp):
370
+ size = os.path.getsize(fp)
371
+ mtime = datetime.fromtimestamp(os.path.getmtime(fp))
372
+ backups.append({
373
+ "name": f,
374
+ "size": f"{size/1024:.2f} KB",
375
+ "created": mtime.strftime("%Y-%m-%d %H:%M:%S"),
376
+ })
377
+ backups.sort(key=lambda x: x["created"], reverse=True)
378
+ return jsonify({"backups": backups, "total": len(backups)})
379
+ except Exception as e:
380
+ return jsonify({"error": str(e)}), 500
381
+
382
+
383
+ @app.route("/api/restore/<backup_name>", methods=["POST"])
384
+ def restore_backup(backup_name):
385
+ try:
386
+ backup_path = os.path.join(BACKUP_FOLDER, secure_filename(backup_name))
387
+ if not os.path.exists(backup_path):
388
+ return jsonify({"error": "Backup not found"}), 404
389
+
390
+ restore_name = backup_name.replace("_backup", "").split("_")[0] + ".db"
391
+ restore_path = os.path.join(DATABASE_FOLDER, restore_name)
392
+ shutil.copy2(backup_path, restore_path)
393
+ db_module.set_db_path(restore_path)
394
+ tables = get_db_tables(restore_path)
395
+ log_action("BACKUP_RESTORED", backup_name)
396
+ return jsonify({
397
+ "success": True,
398
+ "message": "Backup restored successfully",
399
+ "database": restore_name,
400
+ "tables": tables,
401
+ })
402
+ except Exception as e:
403
+ return jsonify({"error": str(e)}), 500
404
+
405
+
406
+ @app.route("/api/backup/<backup_name>", methods=["DELETE"])
407
+ def delete_backup(backup_name):
408
+ try:
409
+ backup_path = os.path.join(BACKUP_FOLDER, secure_filename(backup_name))
410
+ if not os.path.exists(backup_path):
411
+ return jsonify({"error": "Backup not found"}), 404
412
+ os.remove(backup_path)
413
+ log_action("BACKUP_DELETED", backup_name)
414
+ return jsonify({"success": True, "message": "Backup deleted"})
415
+ except Exception as e:
416
+ return jsonify({"error": str(e)}), 500
417
+
418
+
419
+ # ==================== ROUTES: MANAGEMENT ====================
420
+
421
+ @app.route("/api/clear-all", methods=["POST"])
422
+ def clear_all():
423
+ try:
424
+ for folder in [DATABASE_FOLDER]:
425
+ for f in os.listdir(folder):
426
+ fp = os.path.join(folder, f)
427
+ if os.path.isfile(fp):
428
+ os.remove(fp)
429
+ db_module.set_db_path(None)
430
+ log_action("CLEAR_ALL", "Cleared all databases")
431
+ return jsonify({"success": True, "message": "All databases cleared (backups preserved)"})
432
+ except Exception as e:
433
+ return jsonify({"error": str(e)}), 500
434
+
435
+
436
+ @app.route("/api/logs", methods=["GET"])
437
+ def get_logs():
438
+ try:
439
+ log_file = os.path.join(LOG_FOLDER, "activity.log")
440
+ if not os.path.exists(log_file):
441
+ return jsonify({"logs": [], "total": 0})
442
+ with open(log_file, "r") as f:
443
+ logs = f.readlines()
444
+ logs = list(reversed(logs[-100:]))
445
+ return jsonify({"logs": logs, "total": len(logs)})
446
+ except Exception as e:
447
+ return jsonify({"error": str(e)}), 500
448
+
449
+
450
+ # ==================== ERROR HANDLERS ====================
451
+
452
+ @app.errorhandler(404)
453
+ def not_found(e):
454
+ return jsonify({"error": "Not found"}), 404
455
+
456
+ @app.errorhandler(413)
457
+ def too_large(e):
458
+ return jsonify({"error": "File too large (max 50 MB)"}), 413
459
+
460
+ @app.errorhandler(500)
461
+ def server_error(e):
462
+ return jsonify({"error": "Internal server error"}), 500
463
+
464
+
465
+ # ==================== MAIN ====================
466
+
467
+ if __name__ == "__main__":
468
+ # Auto-load default DB if it exists
469
+ default_db = os.path.join(BASE_DIR, "database", "company.db")
470
+ if os.path.exists(default_db):
471
+ db_module.set_db_path(default_db)
472
+ print(f"✅ Default DB loaded: {default_db}")
473
+
474
+ print("=" * 60)
475
+ print("🚀 AI SQL Agent – Backend API")
476
+ print("=" * 60)
477
+ print(f"Model : {MODEL_NAME}")
478
+ print(f"API URL : http://localhost:5000")
479
+ print("=" * 60)
480
+
481
+ app.run(debug=True, host="0.0.0.0", port=5000)
config.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+
4
+ load_dotenv()
5
+
6
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY")
7
+ MODEL_NAME = "llama-3.3-70b-versatile"
create_db.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Run this once to create the default sample database.
3
+ Usage: python create_db.py
4
+ """
5
+ import sqlite3
6
+ import os
7
+
8
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
9
+ DB_FOLDER = os.path.join(BASE_DIR, "database")
10
+ DB_PATH = os.path.join(DB_FOLDER, "company.db")
11
+
12
+ os.makedirs(DB_FOLDER, exist_ok=True)
13
+
14
+ conn = sqlite3.connect(DB_PATH)
15
+ cursor = conn.cursor()
16
+
17
+ cursor.execute("""
18
+ CREATE TABLE IF NOT EXISTS customers(
19
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
20
+ name TEXT NOT NULL,
21
+ age INTEGER,
22
+ city TEXT,
23
+ email TEXT
24
+ )
25
+ """)
26
+
27
+ cursor.execute("SELECT COUNT(*) FROM customers")
28
+ count = cursor.fetchone()[0]
29
+
30
+ if count == 0:
31
+ customers = [
32
+ ("Ali", 23, "Lahore", "ali@gmail.com"),
33
+ ("Ahmed", 25, "Islamabad", "ahmed@gmail.com"),
34
+ ("Sara", 22, "Karachi", "sara@gmail.com"),
35
+ ("Usman", 27, "Lahore", "usman@gmail.com"),
36
+ ("Ayesha", 24, "Faisalabad", "ayesha@gmail.com"),
37
+ ]
38
+ cursor.executemany(
39
+ "INSERT INTO customers(name, age, city, email) VALUES (?, ?, ?, ?)",
40
+ customers,
41
+ )
42
+ print("✅ Sample data inserted.")
43
+ else:
44
+ print("ℹ️ Data already exists, skipping insert.")
45
+
46
+ conn.commit()
47
+ conn.close()
48
+
49
+ print(f"✅ Database ready at: {DB_PATH}")
database.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sqlite3
2
+ import os
3
+
4
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
5
+ DEFAULT_DB_PATH = os.path.join(BASE_DIR, "database", "company.db")
6
+
7
+ # Holds the currently active database path
8
+ _current_db_path = DEFAULT_DB_PATH
9
+
10
+
11
+ def set_db_path(path: str):
12
+ global _current_db_path
13
+ _current_db_path = path
14
+
15
+
16
+ def get_db_path() -> str:
17
+ return _current_db_path
18
+
19
+
20
+ def get_connection():
21
+ return sqlite3.connect(_current_db_path)
22
+
23
+
24
+ def execute_query(query: str, params=None):
25
+ conn = get_connection()
26
+ cursor = conn.cursor()
27
+ if params:
28
+ cursor.execute(query, params)
29
+ else:
30
+ cursor.execute(query)
31
+ conn.commit()
32
+ conn.close()
33
+
34
+
35
+ def fetch_query(query: str, params=None):
36
+ conn = get_connection()
37
+ cursor = conn.cursor()
38
+ if params:
39
+ cursor.execute(query, params)
40
+ else:
41
+ cursor.execute(query)
42
+ # Return list of dicts
43
+ columns = [desc[0] for desc in cursor.description]
44
+ rows = [dict(zip(columns, row)) for row in cursor.fetchall()]
45
+ conn.close()
46
+ return rows
47
+
48
+
49
+ def get_schema_info(db_path: str) -> str:
50
+ """Extract full schema string from a SQLite database."""
51
+ try:
52
+ conn = sqlite3.connect(db_path)
53
+ cursor = conn.cursor()
54
+ cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
55
+ tables = [row[0] for row in cursor.fetchall()]
56
+
57
+ schema_parts = []
58
+ for table in tables:
59
+ cursor.execute(f"PRAGMA table_info({table})")
60
+ cols = cursor.fetchall()
61
+ col_defs = []
62
+ for col in cols:
63
+ col_name = col[1]
64
+ col_type = col[2]
65
+ pk = " PRIMARY KEY" if col[5] else ""
66
+ col_defs.append(f" {col_name} {col_type}{pk}")
67
+ schema_parts.append(f"{table}(\n" + ",\n".join(col_defs) + "\n)")
68
+
69
+ conn.close()
70
+ return "\n\n".join(schema_parts)
71
+ except Exception as e:
72
+ return f"Error reading schema: {e}"
llm.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_groq import ChatGroq
2
+ from langchain_core.messages import SystemMessage, HumanMessage
3
+
4
+ from config import GROQ_API_KEY, MODEL_NAME
5
+ from prompts import build_system_prompt, SYSTEM_PROMPT
6
+
7
+ llm = ChatGroq(
8
+ api_key=GROQ_API_KEY,
9
+ model=MODEL_NAME,
10
+ temperature=0
11
+ )
12
+
13
+
14
+ def generate_sql(user_question: str, schema_info: str = None) -> str:
15
+ """Generate SQL from natural language question."""
16
+ prompt = build_system_prompt(schema_info) if schema_info else SYSTEM_PROMPT
17
+
18
+ response = llm.invoke([
19
+ SystemMessage(content=prompt),
20
+ HumanMessage(content=user_question)
21
+ ])
22
+
23
+ return response.content.strip()
prompts.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def build_system_prompt(schema_info: str) -> str:
2
+ return f"""You are an expert SQLite SQL Agent.
3
+
4
+ Your task is to convert the user's English request into a valid SQLite SQL query.
5
+
6
+ Database Schema:
7
+ {schema_info}
8
+
9
+ Rules:
10
+ 1. Return ONLY the SQL query.
11
+ 2. Never explain anything.
12
+ 3. Never use markdown or code fences.
13
+ 4. Never write ```sql or ```.
14
+ 5. Never add comments.
15
+ 6. Use valid SQLite syntax only.
16
+ 7. If the user asks to view data, generate SELECT queries.
17
+ 8. If the user asks to add data, generate INSERT queries.
18
+ 9. If the user asks to update data, generate UPDATE queries.
19
+ 10. If the user asks to delete data, generate DELETE queries.
20
+ 11. If the request cannot be answered using this database, return exactly:
21
+ INVALID_QUERY
22
+
23
+ Examples:
24
+
25
+ User: Show all customers
26
+ SQL: SELECT * FROM customers;
27
+
28
+ User: Show customers from Lahore
29
+ SQL: SELECT * FROM customers WHERE city='Lahore';
30
+
31
+ User: Add customer Ali age 23 city Lahore email ali@gmail.com
32
+ SQL: INSERT INTO customers(name,age,city,email) VALUES('Ali',23,'Lahore','ali@gmail.com');
33
+
34
+ User: Delete customer Ali
35
+ SQL: DELETE FROM customers WHERE name='Ali';
36
+
37
+ User: Update Ali city to Islamabad
38
+ SQL: UPDATE customers SET city='Islamabad' WHERE name='Ali';
39
+ """
40
+
41
+ # Default fallback prompt (used when no DB loaded)
42
+ SYSTEM_PROMPT = build_system_prompt("""
43
+ customers(
44
+ id INTEGER PRIMARY KEY,
45
+ name TEXT,
46
+ age INTEGER,
47
+ city TEXT,
48
+ email TEXT
49
+ )
50
+ """)
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ Flask>=2.3.0
2
+ Flask-CORS>=4.0.0
3
+ Werkzeug>=2.3.0
4
+ pandas>=2.0.0
5
+ python-dotenv>=1.0.0
6
+ gunicorn>=21.0.0
7
+ langchain-groq>=0.1.9
8
+ langchain-core>=0.1.52