Shashwat-18 commited on
Commit
8a4717c
·
verified ·
1 Parent(s): a5dce9b

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -849
app.py DELETED
@@ -1,849 +0,0 @@
1
- # %%
2
- import warnings
3
- warnings.filterwarnings("ignore")
4
-
5
- import os
6
- import sqlite3
7
- from typing import Tuple, Optional, List, Dict, Any
8
-
9
- import matplotlib.pyplot as plt
10
-
11
- import gradio as gr
12
- import pandas as pd
13
-
14
- import uuid
15
- from dotenv import load_dotenv
16
- from langchain_groq import ChatGroq
17
- from langchain_community.embeddings import HuggingFaceEmbeddings
18
- from langchain_community.vectorstores import Chroma
19
-
20
- # %% [markdown]
21
- # ### 0. Global configurations.
22
-
23
- # %%
24
- load_dotenv()
25
-
26
- DB_PATH = "olist.db"
27
- DATA_DIR = "data"
28
-
29
- # Groq Model
30
- GROQ_MODEL_NAME = "llama-3.3-70b-versatile"
31
-
32
- GROQ_API_KEY = os.getenv("GROQ_API_KEY")
33
- if not GROQ_API_KEY:
34
- raise ValueError("GROQ_API_KEY not found.")
35
-
36
- # Embedding model
37
- EMBED_MODEL_NAME = "sentence-transformers/all-mpnet-base-v2"
38
-
39
-
40
- # %%
41
- import datetime
42
-
43
- PROMPT_LOG_PATH = "prompt_logs.txt"
44
-
45
- def log_prompt(tag: str, prompt: str) -> None:
46
- """
47
- Append the full prompt to a log file, with a tag and timestamp.
48
- """
49
- timestamp = datetime.datetime.now().isoformat(timespec="seconds")
50
- header = f"\n\n================ {tag} @ {timestamp} ================\n"
51
- with open(PROMPT_LOG_PATH, "a", encoding="utf-8") as f:
52
- f.write(header)
53
- f.write(prompt)
54
- f.write("\n================ END PROMPT ================\n")
55
-
56
-
57
- # %%
58
- RUN_LOG_PATH = "run_logs.txt"
59
-
60
- def log_run_event(tag: str, content: str) -> None:
61
- """
62
- Append model response, final SQL, and error info into a run log.
63
- """
64
- timestamp = datetime.datetime.now().isoformat(timespec="seconds")
65
- header = f"\n\n================ {tag} @ {timestamp} ================\n"
66
- with open(RUN_LOG_PATH, "a", encoding="utf-8") as f:
67
- f.write(header)
68
- f.write(content)
69
- f.write("\n================ END EVENT ================\n")
70
-
71
-
72
- # %% [markdown]
73
- # ### 1. Database setup (from CSVs)
74
-
75
- # %%
76
- def init_db() -> sqlite3.Connection:
77
- """
78
- Load all CSVs from the data/ folder into a local SQLite DB.
79
- Table names are derived from file names (without .csv).
80
- """
81
- conn = sqlite3.connect(DB_PATH, check_same_thread=False)
82
-
83
- csv_files = [
84
- "olist_customers_dataset.csv",
85
- "olist_orders_dataset.csv",
86
- "olist_order_items_dataset.csv",
87
- "olist_products_dataset.csv",
88
- "olist_order_reviews_dataset.csv",
89
- "olist_order_payments_dataset.csv",
90
- "product_category_name_translation.csv",
91
- "olist_sellers_dataset.csv",
92
- "olist_geolocation_dataset.csv",
93
- ]
94
-
95
- for fname in csv_files:
96
- path = os.path.join(DATA_DIR, fname)
97
- print(path)
98
- if not os.path.exists(path):
99
- print(f"CSV not found: {path} - skipping")
100
- continue
101
-
102
- table_name = os.path.splitext(fname)[0]
103
- print(f"Loading {path} into table {table_name}...")
104
- df = pd.read_csv(path)
105
- df.to_sql(table_name, conn, if_exists="replace", index=False)
106
-
107
- return conn
108
-
109
- conn = init_db()
110
-
111
-
112
- # %% [markdown]
113
- # ### 2. Schema extractor + metadata YAML
114
-
115
- # %%
116
- OLIST_DOCS: Dict[str, Dict[str, Any]] = {
117
- "olist_customers_dataset": {
118
- "description": "Customer master data, one row per customer_id (which can change over time for the same end-user).",
119
- "columns": {
120
- "customer_id": "Primary key for this table. Unique technical identifier for a customer at a point in time. Used to join with olist_orders_dataset.customer_id.",
121
- "customer_unique_id": "Stable unique identifier for the end-user. A single customer_unique_id can map to multiple customer_id records over time.",
122
- "customer_zip_code_prefix": "Customer ZIP/postal code prefix. Used to join with olist_geolocation_dataset.geolocation_zip_code_prefix.",
123
- "customer_city": "Customer's city as captured at the time of the order or registration.",
124
- "customer_state": "Customer's state (two-letter Brazilian state code, e.g. SP, RJ)."
125
- }
126
- },
127
- "olist_orders_dataset": {
128
- "description": "Customer orders placed on the Olist marketplace, one row per order.",
129
- "columns": {
130
- "order_id": "Primary key. Unique identifier for each order. Used to join with items, payments, and reviews.",
131
- "customer_id": "Foreign key to olist_customers_dataset.customer_id indicating who placed the order.",
132
- "order_status": "Current lifecycle status of the order (e.g. created, shipped, delivered, canceled, unavailable).",
133
- "order_purchase_timestamp": "Timestamp when the customer completed the purchase (event time for order placement).",
134
- "order_approved_at": "Timestamp when the payment was approved by the system or financial gateway.",
135
- "order_delivered_carrier_date": "Timestamp when the order was handed over by the seller to the carrier/logistics provider.",
136
- "order_delivered_customer_date": "Timestamp when the carrier reported the order as delivered to the final customer.",
137
- "order_estimated_delivery_date": "Estimated delivery date promised to the customer at checkout."
138
- }
139
- },
140
- "olist_order_items_dataset": {
141
- "description": "Order line items, one row per product per order.",
142
- "columns": {
143
- "order_id": "Foreign key to olist_orders_dataset.order_id. Multiple order_items can belong to the same order.",
144
- "order_item_id": "Sequential item number within an order (1, 2, 3, ...). Uniquely identifies a line inside an order.",
145
- "product_id": "Foreign key to olist_products_dataset.product_id representing the purchased product.",
146
- "seller_id": "Foreign key to olist_sellers_dataset.seller_id representing the seller that fulfilled this item.",
147
- "shipping_limit_date": "Deadline for the seller to hand the item over to the carrier for shipping.",
148
- "price": "Item price paid by the customer for this line (in BRL, not including freight).",
149
- "freight_value": "Freight (shipping) cost attributed to this line item (in BRL)."
150
- }
151
- },
152
- "olist_products_dataset": {
153
- "description": "Product catalog with physical and category attributes, one row per product.",
154
- "columns": {
155
- "product_id": "Primary key. Unique identifier for each product. Used to join with olist_order_items_dataset.product_id.",
156
- "product_category_name": "Product category name in Portuguese. Join to product_category_name_translation.product_category_name for English.",
157
- "product_name_lenght": "Number of characters in the product name (field name misspelled as 'lenght' in the original dataset).",
158
- "product_description_lenght": "Number of characters in the product description (also misspelled as 'lenght').",
159
- "product_photos_qty": "Number of product images associated with the listing.",
160
- "product_weight_g": "Product weight in grams.",
161
- "product_length_cm": "Product length in centimeters (package dimension).",
162
- "product_height_cm": "Product height in centimeters (package dimension).",
163
- "product_width_cm": "Product width in centimeters (package dimension)."
164
- }
165
- },
166
- "olist_order_reviews_dataset": {
167
- "description": "Post-purchase customer reviews and satisfaction scores, one row per review.",
168
- "columns": {
169
- "review_id": "Primary key. Unique identifier for each review record.",
170
- "order_id": "Foreign key to olist_orders_dataset.order_id for the reviewed order.",
171
- "review_score": "Star rating given by the customer on a 1–5 scale (5 = very satisfied, 1 = very dissatisfied).",
172
- "review_comment_title": "Optional short text title or summary of the review.",
173
- "review_comment_message": "Optional detailed free-text comment describing the customer experience.",
174
- "review_creation_date": "Date when the customer created the review.",
175
- "review_answer_timestamp": "Timestamp when Olist or the seller responded to the review (if applicable)."
176
- }
177
- },
178
- "olist_order_payments_dataset": {
179
- "description": "Payments associated with orders, one row per payment record (order can have multiple payments).",
180
- "columns": {
181
- "order_id": "Foreign key to olist_orders_dataset.order_id.",
182
- "payment_sequential": "Sequence number for multiple payments of the same order (1 for first payment, 2 for second, etc.).",
183
- "payment_type": "Payment method used (e.g. credit_card, boleto, voucher, debit_card).",
184
- "payment_installments": "Number of installments chosen by the customer for this payment.",
185
- "payment_value": "Monetary amount paid in this payment record (in BRL)."
186
- }
187
- },
188
- "product_category_name_translation": {
189
- "description": "Lookup table mapping Portuguese product category names to English equivalents.",
190
- "columns": {
191
- "product_category_name": "Product category name in Portuguese as used in olist_products_dataset.",
192
- "product_category_name_english": "Translated product category name in English."
193
- }
194
- },
195
- "olist_sellers_dataset": {
196
- "description": "Seller master data, one row per seller operating on the Olist marketplace.",
197
- "columns": {
198
- "seller_id": "Primary key. Unique identifier for each seller. Used to join with olist_order_items_dataset.seller_id.",
199
- "seller_zip_code_prefix": "Seller ZIP/postal code prefix, used to join with olist_geolocation_dataset.geolocation_zip_code_prefix.",
200
- "seller_city": "City where the seller is located.",
201
- "seller_state": "State where the seller is located (two-letter Brazilian state code)."
202
- }
203
- },
204
- "olist_geolocation_dataset": {
205
- "description": "Geolocation reference data for ZIP code prefixes in Brazil, not unique per prefix.",
206
- "columns": {
207
- "geolocation_zip_code_prefix": "ZIP/postal code prefix, used to link customers and sellers via zip code.",
208
- "geolocation_lat": "Latitude coordinate of the location.",
209
- "geolocation_lng": "Longitude coordinate of the location.",
210
- "geolocation_city": "City name for the location.",
211
- "geolocation_state": "State code for the location (two-letter Brazilian state code)."
212
- }
213
- }
214
- }
215
-
216
-
217
-
218
- # %%
219
- def extract_schema_metadata(connection: sqlite3.Connection) -> Dict[str, Any]:
220
- """
221
- Introspect SQLite tables, columns and foreign key relationships.
222
- """
223
- cursor = connection.cursor()
224
- cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
225
- tables = [row[0] for row in cursor.fetchall()]
226
-
227
- metadata: Dict[str, Any] = {"tables": {}}
228
-
229
- for table in tables:
230
- cursor.execute(f"PRAGMA table_info('{table}')")
231
- cols = cursor.fetchall()
232
-
233
- # Manual docs for the table
234
- table_docs = OLIST_DOCS.get(table, {})
235
- table_desc: str = table_docs.get(
236
- "description",
237
- f"Table '{table}' from Olist dataset."
238
- )
239
- column_docs: Dict[str, str] = table_docs.get("columns", {})
240
-
241
- columns_meta: Dict[str, str] = {}
242
- for c in cols:
243
- col_name = c[1]
244
- col_type = c[2] or "TEXT"
245
-
246
- if col_name in column_docs:
247
- columns_meta[col_name] = column_docs[col_name]
248
- else:
249
- columns_meta[col_name] = f"Column '{col_name}' of type {col_type}"
250
-
251
- cursor.execute(f"PRAGMA foreign_key_list('{table}')")
252
-
253
-
254
- fk_rows = cursor.fetchall()
255
- relationships: List[str] = []
256
- for fk in fk_rows:
257
- ref_table = fk[2]
258
- from_col = fk[3]
259
- to_col = fk[4]
260
- relationships.append(
261
- f"{table}.{from_col} → {ref_table}.{to_col} (foreign key)"
262
- )
263
-
264
- metadata["tables"][table] = {
265
- "description": table_desc,
266
- "columns": columns_meta,
267
- "relationships": relationships,
268
- }
269
-
270
- return metadata
271
-
272
- schema_metadata = extract_schema_metadata(conn)
273
- schema_metadata
274
-
275
-
276
- # %%
277
- def build_schema_yaml(metadata: Dict[str, Any]) -> str:
278
- """
279
- Render metadata dict into a YAML-style string.
280
- """
281
- lines: List[str] = ["tables:"]
282
- for tname, tinfo in metadata["tables"].items():
283
- lines.append(f" {tname}:")
284
- desc = tinfo.get("description", "").replace('"', "'")
285
- lines.append(f' description: "{desc}"')
286
- lines.append(" columns:")
287
- for col_name, col_desc in tinfo.get("columns", {}).items():
288
- col_desc_clean = col_desc.replace('"', "'")
289
- lines.append(f' {col_name}: "{col_desc_clean}"')
290
- rels = tinfo.get("relationships", [])
291
- if rels:
292
- lines.append(" relationships:")
293
- for rel in rels:
294
- rel_clean = rel.replace('"', "'")
295
- lines.append(f' - "{rel_clean}"')
296
- return "\n".join(lines)
297
-
298
- schema_yaml = build_schema_yaml(schema_metadata)
299
-
300
-
301
- # %% [markdown]
302
- # ### 4. Build schema documents for RAG (taking samples from the table)
303
-
304
- # %%
305
- def build_schema_documents(
306
- connection: sqlite3.Connection,
307
- schema_metadata: Dict[str, Any],
308
- sample_rows: int = 5,
309
- ) -> Tuple[List[str], List[Dict[str, Any]]]:
310
- """
311
- Build one rich RAG document per table, using schema_metadata.
312
-
313
- Each document inclu des:
314
- - Table name
315
- - Table description
316
- - Columns with type + description
317
- - Relationships (FKs)
318
- - A few sample rows
319
-
320
- Returns:
321
- docs: list of plain-text documents (one per table)
322
- metadatas: list of metadata dicts aligned with docs
323
- (each has doc_type="table_schema", table_name="<name>")
324
- """
325
- cursor = connection.cursor()
326
- cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
327
- tables = [row[0] for row in cursor.fetchall()]
328
-
329
- docs: List[str] = []
330
- metadatas: List[Dict[str, Any]] = []
331
-
332
- for table in tables:
333
- tmeta = schema_metadata["tables"][table]
334
- table_desc = tmeta.get("description", "")
335
- columns_meta = tmeta.get("columns", {})
336
- relationships = tmeta.get("relationships", [])
337
-
338
- # Use PRAGMA to get types, then enrich with descriptions -- STILL NEED TO WORK ON.
339
- cursor.execute(f"PRAGMA table_info('{table}')")
340
- cols = cursor.fetchall()
341
-
342
- col_lines = []
343
- for c in cols:
344
- col_name = c[1]
345
- col_type = c[2] or "TEXT"
346
- col_desc = columns_meta.get(col_name, f"Column '{col_name}' of type {col_type}")
347
- col_lines.append(f"- {col_name} ({col_type}): {col_desc}")
348
-
349
- # Sample rows
350
- try:
351
- sample_df = pd.read_sql_query(
352
- f"SELECT * FROM '{table}' LIMIT {sample_rows}",
353
- connection,
354
- )
355
- sample_text = sample_df.to_markdown(index=False)
356
- except Exception:
357
- sample_text = "(could not fetch sample rows)"
358
-
359
- # Relationships block
360
- rel_block = ""
361
- if relationships:
362
- rel_block = "Relationships:\n" + "\n".join(
363
- f"- {rel}" for rel in relationships
364
- ) + "\n"
365
-
366
- doc_text = (
367
- f"Table: {table}\n"
368
- f"Description: {table_desc}\n\n"
369
- f"Columns:\n" + "\n".join(col_lines) + "\n\n"
370
- f"{rel_block}\n"
371
- f"Example rows:\n{sample_text}\n"
372
- )
373
-
374
- docs.append(doc_text)
375
- metadatas.append({
376
- "doc_type": "table_schema",
377
- "table_name": table,
378
- })
379
-
380
- return docs, metadatas
381
-
382
-
383
- # %%
384
- # Build RAG texts + metadata
385
- schema_docs, schema_doc_metas = build_schema_documents(conn, schema_metadata)
386
-
387
- RAG_TEXTS: List[str] = []
388
- RAG_METADATAS: List[Dict[str, Any]] = []
389
-
390
- # 1) Per-table docs
391
- RAG_TEXTS.extend(schema_docs)
392
- RAG_METADATAS.extend(schema_doc_metas)
393
-
394
- # 2) Global YAML as a separate doc
395
- RAG_TEXTS.append("SCHEMA_METADATA_YAML:\n" + schema_yaml)
396
- RAG_METADATAS.append({"doc_type": "global_schema"})
397
-
398
-
399
- # %% [markdown]
400
- # ### 5. Build Chroma store + global RAG retriever
401
- #
402
-
403
- # %%
404
-
405
- def build_store_final() -> Tuple[Chroma, Any]:
406
- """
407
- Build the production RAG store with fixed embedding model.
408
- """
409
- embedding_model = HuggingFaceEmbeddings(model_name=EMBED_MODEL_NAME)
410
-
411
- collection_name = f"olist_schema_all_mpnet_{uuid.uuid4().hex[:8]}"
412
-
413
- store = Chroma.from_texts(
414
- RAG_TEXTS,
415
- embedding_model,
416
- metadatas=RAG_METADATAS,
417
- collection_name=collection_name,
418
- persist_directory=None, # in-memory
419
- )
420
-
421
- retriever = store.as_retriever(
422
- search_kwargs={
423
- "k": 3,
424
- "filter": {"doc_type": "table_schema"},
425
- }
426
- )
427
-
428
- return store, retriever
429
-
430
- rag_store, rag_retriever = build_store_final()
431
-
432
-
433
- # %% [markdown]
434
- # ### 6. Groq LLM via LangChain
435
-
436
- # %%
437
- llm = ChatGroq(model=GROQ_MODEL_NAME, groq_api_key=GROQ_API_KEY)
438
-
439
- def get_rag_context(question: str) -> str:
440
- """
441
- Retrieve the most relevant schema documents for the question.
442
- """
443
- docs = rag_retriever.invoke(question)
444
- return "\n\n---\n\n".join(d.page_content for d in docs)
445
-
446
- def clean_sql(sql: str) -> str:
447
- sql = sql.strip()
448
- if "```" in sql:
449
- sql = sql.replace("```sql", "").replace("```", "").strip()
450
- return sql
451
-
452
- # 6b. General / descriptive questions
453
-
454
- GENERAL_DESC_KEYWORDS = [
455
- "what is this dataset about",
456
- "what is this data about",
457
- "describe this dataset",
458
- "describe the dataset",
459
- "dataset overview",
460
- "data overview",
461
- "summary of the dataset",
462
- "explain this dataset",
463
- ]
464
-
465
-
466
- def is_general_question(question: str) -> bool:
467
- """
468
- Detect high-level descriptive questions where we should answer
469
- directly from schema context instead of generating SQL.
470
- """
471
- q = question.lower().strip()
472
- return any(key in q for key in GENERAL_DESC_KEYWORDS)
473
-
474
-
475
- def answer_general_question(question: str) -> str:
476
- """
477
- Use the RAG schema docs to generate a rich, high-level description
478
- of the Olist dataset for conceptual questions.
479
- """
480
- rag_context = get_rag_context(question)
481
-
482
- system_instructions = """
483
- You are a data documentation expert.
484
-
485
- You will be given:
486
- - Schema documentation for the Olist dataset (tables, descriptions, columns, relationships).
487
- - A high-level user question like "what is this dataset about?".
488
-
489
- Your job:
490
- - Write a clear, structured overview of the dataset.
491
- - Explain the main entities (customers, orders, items, products, sellers, payments, reviews, geolocation).
492
- - Mention typical analysis use-cases (delivery performance, customer behavior, seller performance, product/category analysis, etc.).
493
- - Target a data analyst seeing the dataset for the first time.
494
-
495
- Do NOT write SQL. Answer in Markdown.
496
- """
497
-
498
- prompt = (
499
- system_instructions
500
- + "\n\n=== SCHEMA CONTEXT ===\n"
501
- + rag_context
502
- + "\n\n=== USER QUESTION ===\n"
503
- + question
504
- + "\n\nDetailed dataset overview:"
505
- )
506
-
507
- log_prompt("GENERAL_DATASET_QUESTION", prompt)
508
-
509
- response = llm.invoke(prompt)
510
- log_run_event("RAW_MODEL_RESPONSE_GENERAL_DATASET", response.content)
511
-
512
- return response.content.strip()
513
-
514
-
515
- # %% [markdown]
516
- # ### 7. SQL execution / validation
517
-
518
- # %%
519
- def execute_sql(sql: str, connection: sqlite3.Connection) -> Tuple[Optional[pd.DataFrame], Optional[str]]:
520
- """
521
- Execute SQL on SQLite and return a DataFrame, else return an error.
522
- """
523
- try:
524
- df = pd.read_sql_query(sql, connection)
525
- return df, None
526
- except Exception as e:
527
- return None, str(e)
528
-
529
- def validate_sql(sql: str, connection: sqlite3.Connection) -> Tuple[bool, Optional[str]]:
530
- """
531
- Basic SQL validator:
532
- - Uses EXPLAIN QUERY PLAN to detect syntax or schema issues.
533
- """
534
- try:
535
- cursor = connection.cursor()
536
- cursor.execute(f"EXPLAIN QUERY PLAN {sql}")
537
- return True, None
538
- except Exception as e:
539
- return False, str(e)
540
-
541
-
542
- # %% [markdown]
543
- # ### 8. SQL Generation + Repair with LLM
544
-
545
- # %%
546
- def generate_sql(question: str, rag_context: str) -> str:
547
- system_instructions = """
548
- You are a senior data analyst writing SQL for a SQLite database.
549
-
550
- You will be given:
551
- - A description of available tables, columns, and relationships (schema + YAML metadata).
552
- - A natural language question from the user.
553
-
554
- Your job:
555
- - Write ONE valid SQLite SQL query that answers the question.
556
- - ONLY use tables and columns that exist in the schema_context.
557
- - Use explicit JOINs with ON conditions.
558
- - Do not use DROP, INSERT, UPDATE, DELETE or other destructive operations.
559
- - Always use floating-point division for percentage calculations using 1.0 * numerator / denominator, and round to 2 decimals when appropriate.
560
-
561
- Return ONLY the SQL query, no explanation or markdown.
562
- """
563
-
564
- prompt = (
565
- system_instructions
566
- + "\n\n"
567
- + "=== RAG CONTEXT ===\n"
568
- + rag_context
569
- + "\n\n=== USER QUESTION ===\n"
570
- + question
571
- + "\n\nSQL query:"
572
- )
573
-
574
- log_prompt("SQL_GENERATION", prompt)
575
-
576
-
577
- response = llm.invoke(prompt)
578
-
579
- log_run_event("RAW_MODEL_RESPONSE_SQL_GENERATION", response.content)
580
- sql = clean_sql(response.content)
581
- return sql
582
-
583
- def repair_sql(
584
- question: str, rag_context: str, bad_sql: str, error_message: str
585
- ) -> str:
586
- """
587
- Ask the LLM to correct a failing SQL query.
588
- """
589
- system_instructions = """
590
- You are a senior data analyst fixing an existing SQL query for a SQLite database.
591
-
592
- You will be given:
593
- - Schema context (tables, columns, relationships).
594
- - The user's question.
595
- - A previously generated SQL query that failed.
596
- - The SQLite error message.
597
-
598
- Your job:
599
- - Diagnose why the query failed.
600
- - Rewrite ONE valid SQLite SQL query that answers the question.
601
- - ONLY use tables and columns that exist in the schema_context.
602
- - Use explicit JOINs with ON conditions.
603
- - Do not use DROP, INSERT, UPDATE, DELETE or other destructive operations.
604
-
605
- Return ONLY the corrected SQL query, no explanation or markdown.
606
- """
607
-
608
- prompt = (
609
- system_instructions
610
- + "\n\n=== RAG CONTEXT ===\n"
611
- + rag_context
612
- + "\n\n=== USER QUESTION ===\n"
613
- + question
614
- + "\n\n=== PREVIOUS (FAILING) SQL ===\n"
615
- + bad_sql
616
- + "\n\n=== SQLITE ERROR ===\n"
617
- + error_message
618
- + "\n\nCorrected SQL query:"
619
- )
620
-
621
- log_prompt("SQL_REPAIR", prompt)
622
-
623
- response = llm.invoke(prompt)
624
- log_run_event("RAW_MODEL_RESPONSE_SQL_REPAIR", response.content)
625
- sql = clean_sql(response.content)
626
- return sql
627
-
628
-
629
- # %% [markdown]
630
- # ### 9. Result summarization
631
-
632
- # %%
633
- def summarize_results(
634
- question: str,
635
- sql: str,
636
- df: Optional[pd.DataFrame],
637
- rag_context: str,
638
- error: Optional[str] = None,
639
- ) -> str:
640
- """
641
- Ask the LLM to produce a concise, human-readable answer.
642
- """
643
- system_instructions = """
644
- You are a senior data analyst.
645
-
646
- You will be given:
647
- - The user's question.
648
- - The final SQL that was executed.
649
- - A small preview of the query result (as a Markdown table, if available).
650
- - Optional error information if the query failed.
651
-
652
- Your job:
653
- - Provide a clear, concise answer in Markdown.
654
- - If the result is numeric / aggregated, explain what it means in business terms.
655
- - If there was an error, explain it simply and suggest how the user could rephrase.
656
- - Do NOT show raw SQL unless it is helpful to the user.
657
- """
658
-
659
- if df is not None and not df.empty:
660
- preview_rows = min(len(df), 50)
661
- df_preview_md = df.head(preview_rows).to_markdown(index=False)
662
- else:
663
- df_preview_md = "(no rows returned)"
664
-
665
- prompt = (
666
- system_instructions
667
- + "\n\n=== USER QUESTION ===\n"
668
- + question
669
- + "\n\n=== EXECUTED SQL ===\n"
670
- + sql
671
- + "\n\n=== QUERY RESULT PREVIEW ===\n"
672
- + df_preview_md
673
- + "\n\n=== RAG CONTEXT (schema) ===\n"
674
- + rag_context
675
- )
676
-
677
- if error:
678
- prompt += "\n\n=== ERROR ===\n" + error
679
-
680
- log_prompt("RESULT_SUMMARY", prompt)
681
-
682
- response = llm.invoke(prompt)
683
- log_run_event("RAW_MODEL_RESPONSE_RESULT_SUMMARY", response.content)
684
-
685
- return response.content.strip()
686
-
687
-
688
- # %% [markdown]
689
- # ### 10. Backend Pipeline
690
-
691
- # %%
692
- def backend_pipeline(question: str):
693
- """
694
- End-to-end flow:
695
-
696
- 1. Retrieve RAG context (schema).
697
- 2. LLM generates SQL.
698
- 3. SQL validator checks & attempts auto-repair if needed - Currently Done Once.
699
- 4. Execute query on SQLite.
700
- 5. LLM summarizes results.
701
- """
702
- if not question or not question.strip():
703
- return "Please type a question.", pd.DataFrame()
704
-
705
- if is_general_question(question):
706
- overview_md = answer_general_question(question)
707
- return overview_md, pd.DataFrame()
708
-
709
- # Step 1: RAG retrieve
710
- rag_context = get_rag_context(question)
711
-
712
- # Step 2: LLM generates SQL
713
- sql = generate_sql(question, rag_context)
714
- original_sql = sql
715
-
716
- # Step 3: Validate SQL; auto-repair once if needed
717
- is_valid, validation_error = validate_sql(sql, conn)
718
- repaired = False
719
-
720
- if not is_valid and validation_error:
721
- # Attempt repair
722
- repaired_sql = repair_sql(question, rag_context, sql, validation_error)
723
- repaired_valid, repaired_error = validate_sql(repaired_sql, conn)
724
-
725
- if repaired_valid:
726
- # Successfully repaired
727
- sql = repaired_sql
728
- repaired = True
729
- log_run_event(
730
- "SQL_REPAIR_SUCCESS",
731
- f"Original SQL:\n{original_sql}\n\nRepaired SQL:\n{sql}\n",
732
- )
733
- validation_error = None
734
- else:
735
- # Repair attempt failed
736
- log_run_event(
737
- "SQL_REPAIR_FAILED",
738
- f"Original SQL:\n{original_sql}\n\nRepaired SQL:\n{repaired_sql}\n\nValidation error:\n{repaired_error}",
739
- )
740
- validation_error = repaired_error or validation_error
741
-
742
- # Log final SQL (whether repaired or not)
743
- log_run_event("FINAL_SQL", sql)
744
-
745
- # Step 4: Execute query
746
- df, exec_error = (None, None)
747
- if validation_error:
748
- exec_error = validation_error
749
- log_run_event(
750
- "EXECUTION_SKIPPED_DUE_TO_VALIDATION_ERROR",
751
- f"SQL:\n{sql}\n\nValidation error:\n{validation_error}",
752
- )
753
- else:
754
- df, exec_error = execute_sql(sql, conn)
755
- if exec_error:
756
- log_run_event(
757
- "EXECUTION_ERROR",
758
- f"SQL:\n{sql}\n\nExecution error:\n{exec_error}",
759
- )
760
- else:
761
- rows = 0 if df is None else len(df)
762
- log_run_event(
763
- "EXECUTION_SUCCESS",
764
- f"SQL:\n{sql}\n\nRows returned: {rows}",
765
- )
766
-
767
- # Step 5: LLM summary / answer
768
- summary_text = summarize_results(
769
- question=question,
770
- sql=sql,
771
- df=df,
772
- rag_context=rag_context,
773
- error=exec_error,
774
- )
775
-
776
- # Build SQL debug / status section
777
- sql_status_lines = []
778
- if exec_error:
779
- sql_status_lines.append("There was an error running the SQL.")
780
- sql_status_lines.append(f"**Error:** `{exec_error}`")
781
- else:
782
- sql_status_lines.append("Query ran successfully.")
783
-
784
- if repaired:
785
- sql_status_lines.append("_Note: The original SQL was corrected by the assistant._")
786
-
787
- sql_status_lines.append("\n**Final SQL used:**\n")
788
- sql_status_lines.append(f"```sql\n{sql}\n```")
789
-
790
- sql_debug_md = "\n".join(sql_status_lines)
791
-
792
- # Result table
793
- if df is not None and exec_error is None:
794
- df_preview = df
795
- else:
796
- df_preview = pd.DataFrame()
797
-
798
- # Combine summary and SQL status
799
- answer_md = summary_text + "\n\n---\n\n" + sql_debug_md
800
-
801
- return answer_md, df_preview
802
-
803
-
804
- # %% [markdown]
805
- # ### 11. Gradio Interface
806
-
807
- # %%
808
- with gr.Blocks() as demo:
809
- gr.Markdown(
810
- """
811
- Olist Analytics Assistant (RAG + Groq LLM)
812
-
813
- Ask questions in natural language about the Olist dataset.
814
- The app will:
815
-
816
- 1. Retrieve schema with RAG.
817
- 2. Generate and (if needed) repair SQL
818
- 3. Run it on a local SQLite DB
819
- 4. Show the SQL query, the output and summarize the results
820
- """
821
- )
822
-
823
- with gr.Row():
824
- with gr.Column(scale=1):
825
- question_in = gr.Textbox(
826
- label="Your question",
827
- placeholder="e.g. Total revenue per seller in 2017 (include shipping)",
828
- lines=4,
829
- )
830
- submit_btn = gr.Button("Run")
831
- with gr.Column(scale=2):
832
- answer_out = gr.Markdown(label="Answer & Details")
833
- table_out = gr.Dataframe(label="Result table")
834
-
835
- submit_btn.click(
836
- fn=backend_pipeline,
837
- inputs=question_in,
838
- outputs=[answer_out, table_out],
839
- )
840
-
841
- app = demo
842
-
843
- # %%
844
- if __name__ == "__main__":
845
- import os
846
- demo.launch(
847
- server_name = "0.0.0.0",
848
- server_port = int(os.getenv("PORT", 7860))
849
- )