Shashwat-18 commited on
Commit
73e95b9
·
verified ·
1 Parent(s): 95b2079

Upload 20 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,8 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ chroma_data/chroma.sqlite3 filter=lfs diff=lfs merge=lfs -text
37
+ data/olist_geolocation_dataset.csv filter=lfs diff=lfs merge=lfs -text
38
+ data/olist_order_items_dataset.csv filter=lfs diff=lfs merge=lfs -text
39
+ data/olist_order_reviews_dataset.csv filter=lfs diff=lfs merge=lfs -text
40
+ data/olist_orders_dataset.csv filter=lfs diff=lfs merge=lfs -text
app.py ADDED
@@ -0,0 +1,2353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # %%
2
+ import os
3
+ import uuid
4
+ import sqlite3
5
+ import datetime
6
+ import json
7
+ import re
8
+ import time
9
+ from typing import Dict, Any, List, Tuple, Optional
10
+ import hashlib
11
+
12
+ import pandas as pd
13
+ from groq import Groq
14
+ from langchain_community.vectorstores import Chroma
15
+ from langchain_community.embeddings import HuggingFaceEmbeddings
16
+
17
+ # %%
18
+ # 0. Global config
19
+ DB_PATH = "olist.db"
20
+ DATA_DIR = "data"
21
+
22
+ # Groq Model
23
+ GROQ_MODEL_NAME = "llama-3.3-70b-versatile"
24
+
25
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY")
26
+ if not GROQ_API_KEY:
27
+ raise ValueError("GROQ_API_KEY not found.")
28
+
29
+ groq_client = Groq(api_key=GROQ_API_KEY)
30
+
31
+ # Embedding model
32
+ EMBED_MODEL_NAME = "sentence-transformers/all-mpnet-base-v2"
33
+
34
+ # Logging paths
35
+ PROMPT_LOG_PATH = "prompt_logs.txt"
36
+ RUN_LOG_PATH = "run_logs.txt"
37
+
38
+ # %%
39
+
40
+ import os
41
+ import chromadb
42
+ from chromadb.config import Settings
43
+
44
+ CHROMA_PERSIST_DIR = os.path.abspath("./chroma_data")
45
+ os.makedirs(CHROMA_PERSIST_DIR, exist_ok=True)
46
+
47
+ _CHROMA_CLIENT = None
48
+
49
+ def get_chroma_client():
50
+ global _CHROMA_CLIENT
51
+ if _CHROMA_CLIENT is None:
52
+ _CHROMA_CLIENT = chromadb.PersistentClient(
53
+ path=CHROMA_PERSIST_DIR,
54
+ settings=Settings(
55
+ anonymized_telemetry=False,
56
+ ),
57
+ )
58
+ return _CHROMA_CLIENT
59
+
60
+
61
+ # %%
62
+
63
+ def log_prompt(tag: str, prompt: str) -> None:
64
+ """
65
+ Append the full prompt to a log file, with a tag and timestamp.
66
+ """
67
+ timestamp = datetime.datetime.now().isoformat(timespec="seconds")
68
+ header = f"\n\n================ {tag} @ {timestamp} ================\n"
69
+ with open(PROMPT_LOG_PATH, "a", encoding="utf-8") as f:
70
+ f.write(header)
71
+ f.write(prompt)
72
+ f.write("\n================ END PROMPT ================\n")
73
+
74
+
75
+ def log_run_event(tag: str, content: str) -> None:
76
+ """
77
+ Append model response, final SQL, and error info into a run log.
78
+ """
79
+ timestamp = datetime.datetime.now().isoformat(timespec="seconds")
80
+ header = f"\n\n================ {tag} @ {timestamp} ================\n"
81
+ with open(RUN_LOG_PATH, "a", encoding="utf-8") as f:
82
+ f.write(header)
83
+ f.write(content)
84
+ f.write("\n================ END EVENT ================\n")
85
+
86
+
87
+ # %%
88
+ # ==============================
89
+ # Chat message helpers
90
+ # ==============================
91
+
92
+ def assistant_msg(text: str):
93
+ return (None, text)
94
+
95
+ def user_msg(text: str):
96
+ return (text, None)
97
+
98
+ def add_assistant_state(history, text):
99
+ history.append(assistant_msg(text))
100
+ return history
101
+
102
+
103
+ # %%
104
+ import pandas as pd
105
+
106
+ def df_to_state(df: pd.DataFrame) -> dict:
107
+ """Safely converts a DataFrame to a Gradio-compatible dictionary."""
108
+ # Ensure df is actually a DataFrame and not None/Empty
109
+ if df is None or not isinstance(df, pd.DataFrame) or df.empty:
110
+ return {"columns": [], "rows": []}
111
+
112
+ try:
113
+ return {
114
+ "columns": list(df.columns),
115
+ # Converting to string ensures JSON serialization never fails
116
+ "rows": df.astype(str).values.tolist()
117
+ }
118
+ except Exception:
119
+ return {"columns": [], "rows": []}
120
+
121
+
122
+ def state_to_df(state: dict) -> pd.DataFrame:
123
+ """Safely converts a state dictionary back to a DataFrame."""
124
+ # This is the "Type Guard" that stops the 'bool' TypeError
125
+ if not isinstance(state, dict):
126
+ return pd.DataFrame()
127
+
128
+ cols = state.get("columns")
129
+ rows = state.get("rows")
130
+
131
+ if not cols or rows is None:
132
+ return pd.DataFrame()
133
+
134
+ return pd.DataFrame(rows, columns=cols)
135
+
136
+ # %%
137
+
138
+ def init_feedback_table(conn: sqlite3.Connection) -> None:
139
+ """
140
+ Create (or upgrade) a table to capture user feedback on model answers.
141
+ """
142
+ conn.execute("""
143
+ CREATE TABLE IF NOT EXISTS user_feedback (
144
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
145
+ created_at TEXT NOT NULL,
146
+ question TEXT NOT NULL,
147
+ generated_sql TEXT,
148
+ model_answer TEXT,
149
+ rating TEXT CHECK(rating IN ('good','bad')) NOT NULL,
150
+ comment TEXT,
151
+ corrected_sql TEXT
152
+ )
153
+ """)
154
+ conn.commit()
155
+
156
+
157
+ def record_feedback(
158
+ conn: sqlite3.Connection,
159
+ question: str,
160
+ generated_sql: str,
161
+ model_answer: str,
162
+ rating: str, # "good" or "bad"
163
+ comment: Optional[str] = None,
164
+ corrected_sql: Optional[str] = None,
165
+ ) -> None:
166
+ """
167
+ Store user feedback about a particular model answer / SQL query.
168
+ If corrected_sql is provided, it is treated as an external correction.
169
+ """
170
+ rating = rating.lower()
171
+ if rating not in ("good", "bad"):
172
+ raise ValueError("rating must be 'good' or 'bad'")
173
+
174
+ ts = datetime.datetime.now().isoformat(timespec="seconds")
175
+ conn.execute(
176
+ """
177
+ INSERT INTO user_feedback (
178
+ created_at, question, generated_sql, model_answer,
179
+ rating, comment, corrected_sql
180
+ )
181
+ VALUES (?, ?, ?, ?, ?, ?, ?)
182
+ """,
183
+ (ts, question, generated_sql, model_answer, rating, comment, corrected_sql),
184
+ )
185
+ conn.commit()
186
+
187
+
188
+ def get_last_feedback_for_question(
189
+ conn: sqlite3.Connection,
190
+ question: str,
191
+ ) -> Optional[Dict[str, Any]]:
192
+ """
193
+ Return the most recent feedback row for this question (if any).
194
+ """
195
+ cur = conn.cursor()
196
+ cur.execute(
197
+ """
198
+ SELECT created_at, generated_sql, model_answer,
199
+ rating, comment, corrected_sql
200
+ FROM user_feedback
201
+ WHERE question = ?
202
+ ORDER BY created_at DESC
203
+ LIMIT 1
204
+ """,
205
+ (question,),
206
+ )
207
+ row = cur.fetchone()
208
+ if not row:
209
+ return None
210
+
211
+ return {
212
+ "created_at": row[0],
213
+ "generated_sql": row[1],
214
+ "model_answer": row[2],
215
+ "rating": row[3],
216
+ "comment": row[4],
217
+ "corrected_sql": row[5],
218
+ }
219
+
220
+
221
+ # %%
222
+
223
+ def init_db() -> sqlite3.Connection:
224
+ """
225
+ Load all CSVs from the data/ folder into a local SQLite DB.
226
+ Table names are derived from file names (without .csv).
227
+ """
228
+ conn = sqlite3.connect(DB_PATH, check_same_thread=False)
229
+
230
+ csv_files = [
231
+ "olist_customers_dataset.csv",
232
+ "olist_orders_dataset.csv",
233
+ "olist_order_items_dataset.csv",
234
+ "olist_products_dataset.csv",
235
+ "olist_order_reviews_dataset.csv",
236
+ "olist_order_payments_dataset.csv",
237
+ "product_category_name_translation.csv",
238
+ "olist_sellers_dataset.csv",
239
+ "olist_geolocation_dataset.csv",
240
+ ]
241
+
242
+ for fname in csv_files:
243
+ path = os.path.join(DATA_DIR, fname)
244
+ print(path)
245
+ if not os.path.exists(path):
246
+ print(f"CSV not found: {path} - skipping")
247
+ continue
248
+
249
+ table_name = os.path.splitext(fname)[0]
250
+ print(f"Loading {path} into table {table_name}...")
251
+ df = pd.read_csv(path)
252
+ df.to_sql(table_name, conn, if_exists="replace", index=False)
253
+
254
+
255
+ init_feedback_table(conn)
256
+
257
+ return conn
258
+
259
+
260
+ conn = init_db()
261
+
262
+
263
+
264
+ # %%
265
+ # 4. Manual docs for Olist tables
266
+
267
+ OLIST_DOCS: Dict[str, Dict[str, Any]] = {
268
+ "olist_customers_dataset": {
269
+ "description": "Customer master data, one row per customer_id (which can change over time for the same end-user).",
270
+ "columns": {
271
+ "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.",
272
+ "customer_unique_id": "Stable unique identifier for the end-user. A single customer_unique_id can map to multiple customer_id records over time.",
273
+ "customer_zip_code_prefix": "Customer ZIP/postal code prefix. Used to join with olist_geolocation_dataset.geolocation_zip_code_prefix.",
274
+ "customer_city": "Customer's city as captured at the time of the order or registration.",
275
+ "customer_state": "Customer's state (two-letter Brazilian state code, e.g. SP, RJ)."
276
+ }
277
+ },
278
+ "olist_orders_dataset": {
279
+ "description": "Customer orders placed on the Olist marketplace, one row per order.",
280
+ "columns": {
281
+ "order_id": "Primary key. Unique identifier for each order. Used to join with items, payments, and reviews.",
282
+ "customer_id": "Foreign key to olist_customers_dataset.customer_id indicating who placed the order.",
283
+ "order_status": "Current lifecycle status of the order (e.g. created, shipped, delivered, canceled, unavailable).",
284
+ "order_purchase_timestamp": "Timestamp when the customer completed the purchase (event time for order placement).",
285
+ "order_approved_at": "Timestamp when the payment was approved by the system or financial gateway.",
286
+ "order_delivered_carrier_date": "Timestamp when the order was handed over by the seller to the carrier/logistics provider.",
287
+ "order_delivered_customer_date": "Timestamp when the carrier reported the order as delivered to the final customer.",
288
+ "order_estimated_delivery_date": "Estimated delivery date promised to the customer at checkout."
289
+ }
290
+ },
291
+ "olist_order_items_dataset": {
292
+ "description": "Order line items, one row per product per order.",
293
+ "columns": {
294
+ "order_id": "Foreign key to olist_orders_dataset.order_id. Multiple order_items can belong to the same order.",
295
+ "order_item_id": "Sequential item number within an order (1, 2, 3, ...). Uniquely identifies a line inside an order.",
296
+ "product_id": "Foreign key to olist_products_dataset.product_id representing the purchased product.",
297
+ "seller_id": "Foreign key to olist_sellers_dataset.seller_id representing the seller that fulfilled this item.",
298
+ "shipping_limit_date": "Deadline for the seller to hand the item over to the carrier for shipping.",
299
+ "price": "Item price paid by the customer for this line (in BRL, not including freight).",
300
+ "freight_value": "Freight (shipping) cost attributed to this line item (in BRL)."
301
+ }
302
+ },
303
+ "olist_products_dataset": {
304
+ "description": "Product catalog with physical and category attributes, one row per product.",
305
+ "columns": {
306
+ "product_id": "Primary key. Unique identifier for each product. Used to join with olist_order_items_dataset.product_id.",
307
+ "product_category_name": "Product category name in Portuguese. Join to product_category_name_translation.product_category_name for English.",
308
+ "product_name_lenght": "Number of characters in the product name (field name misspelled as 'lenght' in the original dataset).",
309
+ "product_description_lenght": "Number of characters in the product description (also misspelled as 'lenght').",
310
+ "product_photos_qty": "Number of product images associated with the listing.",
311
+ "product_weight_g": "Product weight in grams.",
312
+ "product_length_cm": "Product length in centimeters (package dimension).",
313
+ "product_height_cm": "Product height in centimeters (package dimension).",
314
+ "product_width_cm": "Product width in centimeters (package dimension)."
315
+ }
316
+ },
317
+ "olist_order_reviews_dataset": {
318
+ "description": "Post-purchase customer reviews and satisfaction scores, one row per review.",
319
+ "columns": {
320
+ "review_id": "Primary key. Unique identifier for each review record.",
321
+ "order_id": "Foreign key to olist_orders_dataset.order_id for the reviewed order.",
322
+ "review_score": "Star rating given by the customer on a 1–5 scale (5 = very satisfied, 1 = very dissatisfied).",
323
+ "review_comment_title": "Optional short text title or summary of the review.",
324
+ "review_comment_message": "Optional detailed free-text comment describing the customer experience.",
325
+ "review_creation_date": "Date when the customer created the review.",
326
+ "review_answer_timestamp": "Timestamp when Olist or the seller responded to the review (if applicable)."
327
+ }
328
+ },
329
+ "olist_order_payments_dataset": {
330
+ "description": "Payments associated with orders, one row per payment record (order can have multiple payments).",
331
+ "columns": {
332
+ "order_id": "Foreign key to olist_orders_dataset.order_id.",
333
+ "payment_sequential": "Sequence number for multiple payments of the same order (1 for first payment, 2 for second, etc.).",
334
+ "payment_type": "Payment method used (e.g. credit_card, boleto, voucher, debit_card).",
335
+ "payment_installments": "Number of installments chosen by the customer for this payment.",
336
+ "payment_value": "Monetary amount paid in this payment record (in BRL)."
337
+ }
338
+ },
339
+ "product_category_name_translation": {
340
+ "description": "Lookup table mapping Portuguese product category names to English equivalents.",
341
+ "columns": {
342
+ "product_category_name": "Product category name in Portuguese as used in olist_products_dataset.",
343
+ "product_category_name_english": "Translated product category name in English."
344
+ }
345
+ },
346
+ "olist_sellers_dataset": {
347
+ "description": "Seller master data, one row per seller operating on the Olist marketplace.",
348
+ "columns": {
349
+ "seller_id": "Primary key. Unique identifier for each seller. Used to join with olist_order_items_dataset.seller_id.",
350
+ "seller_zip_code_prefix": "Seller ZIP/postal code prefix, used to join with olist_geolocation_dataset.geolocation_zip_code_prefix.",
351
+ "seller_city": "City where the seller is located.",
352
+ "seller_state": "State where the seller is located (two-letter Brazilian state code)."
353
+ }
354
+ },
355
+ "olist_geolocation_dataset": {
356
+ "description": "Geolocation reference data for ZIP code prefixes in Brazil, not unique per prefix.",
357
+ "columns": {
358
+ "geolocation_zip_code_prefix": "ZIP/postal code prefix, used to link customers and sellers via zip code.",
359
+ "geolocation_lat": "Latitude coordinate of the location.",
360
+ "geolocation_lng": "Longitude coordinate of the location.",
361
+ "geolocation_city": "City name for the location.",
362
+ "geolocation_state": "State code for the location (two-letter Brazilian state code)."
363
+ }
364
+ }
365
+ }
366
+
367
+
368
+
369
+ # %%
370
+
371
+ def extract_schema_metadata(connection: sqlite3.Connection) -> Dict[str, Any]:
372
+ """
373
+ Introspect SQLite tables, columns and foreign key relationships.
374
+ """
375
+ cursor = connection.cursor()
376
+ cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
377
+ tables = [row[0] for row in cursor.fetchall()]
378
+
379
+ metadata: Dict[str, Any] = {"tables": {}}
380
+
381
+ for table in tables:
382
+ cursor.execute(f"PRAGMA table_info('{table}')")
383
+ cols = cursor.fetchall()
384
+
385
+ # Manual docs for the table
386
+ table_docs = OLIST_DOCS.get(table, {})
387
+ table_desc: str = table_docs.get(
388
+ "description",
389
+ f"Table '{table}' from Olist dataset."
390
+ )
391
+ column_docs: Dict[str, str] = table_docs.get("columns", {})
392
+
393
+ columns_meta: Dict[str, str] = {}
394
+ for c in cols:
395
+ col_name = c[1]
396
+ col_type = c[2] or "TEXT"
397
+
398
+ if col_name in column_docs:
399
+ columns_meta[col_name] = column_docs[col_name]
400
+ else:
401
+ columns_meta[col_name] = f"Column '{col_name}' of type {col_type}"
402
+
403
+ cursor.execute(f"PRAGMA foreign_key_list('{table}')")
404
+ fk_rows = cursor.fetchall()
405
+ relationships: List[str] = []
406
+ for fk in fk_rows:
407
+ ref_table = fk[2]
408
+ from_col = fk[3]
409
+ to_col = fk[4]
410
+ relationships.append(
411
+ f"{table}.{from_col} → {ref_table}.{to_col} (foreign key)"
412
+ )
413
+
414
+ metadata["tables"][table] = {
415
+ "description": table_desc,
416
+ "columns": columns_meta,
417
+ "relationships": relationships,
418
+ }
419
+
420
+ return metadata
421
+
422
+
423
+ schema_metadata = extract_schema_metadata(conn)
424
+
425
+
426
+ def build_schema_yaml(metadata: Dict[str, Any]) -> str:
427
+ """
428
+ Render metadata dict into a YAML-style string.
429
+ """
430
+ lines: List[str] = ["tables:"]
431
+ for tname, tinfo in metadata["tables"].items():
432
+ lines.append(f" {tname}:")
433
+ desc = tinfo.get("description", "").replace('"', "'")
434
+ lines.append(f' description: "{desc}"')
435
+ lines.append(" columns:")
436
+ for col_name, col_desc in tinfo.get("columns", {}).items():
437
+ col_desc_clean = col_desc.replace('"', "'")
438
+ lines.append(f' {col_name}: "{col_desc_clean}"')
439
+ rels = tinfo.get("relationships", [])
440
+ if rels:
441
+ lines.append(" relationships:")
442
+ for rel in rels:
443
+ rel_clean = rel.replace('"', "'")
444
+ lines.append(f' - "{rel_clean}"')
445
+ return "\n".join(lines)
446
+
447
+
448
+ schema_yaml = build_schema_yaml(schema_metadata)
449
+
450
+
451
+
452
+ # %%
453
+ # 6. Build schema documents for RAG (taking samples from the table)
454
+
455
+ def build_schema_documents(
456
+ connection: sqlite3.Connection,
457
+ schema_metadata: Dict[str, Any],
458
+ sample_rows: int = 5,
459
+ ) -> Tuple[List[str], List[Dict[str, Any]]]:
460
+ """
461
+ Build one rich RAG document per table, using schema_metadata.
462
+
463
+ Each document includes:
464
+ - Table name
465
+ - Table description
466
+ - Columns with type + description
467
+ - Relationships (FKs)
468
+ - A few sample rows
469
+ """
470
+ cursor = connection.cursor()
471
+ cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
472
+ tables = [row[0] for row in cursor.fetchall()]
473
+
474
+ docs: List[str] = []
475
+ metadatas: List[Dict[str, Any]] = []
476
+
477
+ for table in tables:
478
+ tmeta = schema_metadata["tables"][table]
479
+ table_desc = tmeta.get("description", "")
480
+ columns_meta = tmeta.get("columns", {})
481
+ relationships = tmeta.get("relationships", [])
482
+
483
+ # Use PRAGMA to get types, then enrich with descriptions
484
+ cursor.execute(f"PRAGMA table_info('{table}')")
485
+ cols = cursor.fetchall()
486
+
487
+ col_lines = []
488
+ for c in cols:
489
+ col_name = c[1]
490
+ col_type = c[2] or "TEXT"
491
+ col_desc = columns_meta.get(col_name, f"Column '{col_name}' of type {col_type}")
492
+ col_lines.append(f"- {col_name} ({col_type}): {col_desc}")
493
+
494
+ # Sample rows
495
+ try:
496
+ sample_df = pd.read_sql_query(
497
+ f"SELECT * FROM '{table}' LIMIT {sample_rows}",
498
+ connection,
499
+ )
500
+ sample_text = sample_df.to_markdown(index=False)
501
+ except Exception:
502
+ sample_text = "(could not fetch sample rows)"
503
+
504
+ # Relationships block
505
+ rel_block = ""
506
+ if relationships:
507
+ rel_block = "Relationships:\n" + "\n".join(
508
+ f"- {rel}" for rel in relationships
509
+ ) + "\n"
510
+
511
+ doc_text = (
512
+ f"Table: {table}\n"
513
+ f"Description: {table_desc}\n\n"
514
+ f"Columns:\n" + "\n".join(col_lines) + "\n\n"
515
+ f"{rel_block}\n"
516
+ f"Example rows:\n{sample_text}\n"
517
+ )
518
+
519
+ docs.append(doc_text)
520
+ metadatas.append({
521
+ "doc_type": "table_schema",
522
+ "table_name": table,
523
+ })
524
+
525
+ return docs, metadatas
526
+
527
+
528
+ # Build RAG texts + metadata
529
+ schema_docs, schema_doc_metas = build_schema_documents(conn, schema_metadata)
530
+
531
+ RAG_TEXTS: List[str] = []
532
+ RAG_METADATAS: List[Dict[str, Any]] = []
533
+
534
+ # 1) Per-table docs
535
+ RAG_TEXTS.extend(schema_docs)
536
+ RAG_METADATAS.extend(schema_doc_metas)
537
+
538
+ # 2) Global YAML as a separate doc
539
+ RAG_TEXTS.append("SCHEMA_METADATA_YAML:\n" + schema_yaml)
540
+ RAG_METADATAS.append({"doc_type": "global_schema"})
541
+
542
+
543
+ # %%
544
+ def build_store_final():
545
+ embedding_model = HuggingFaceEmbeddings(
546
+ model_name=EMBED_MODEL_NAME,
547
+ encode_kwargs={"normalize_embeddings": True},
548
+ )
549
+
550
+ rag_store = Chroma(
551
+ client=get_chroma_client(),
552
+ collection_name="rag_schema_store",
553
+ embedding_function=embedding_model,
554
+ )
555
+
556
+ if rag_store._collection.count() == 0:
557
+ rag_store.add_texts(
558
+ texts=RAG_TEXTS,
559
+ metadatas=RAG_METADATAS,
560
+ )
561
+
562
+ rag_retriever = rag_store.as_retriever(
563
+ search_kwargs={"k": 3, "filter": {"doc_type": "table_schema"}}
564
+ )
565
+
566
+ return rag_store, rag_retriever
567
+
568
+ # Initialize once
569
+ rag_store, rag_retriever = build_store_final()
570
+
571
+
572
+ # %%
573
+ from langchain_community.vectorstores import Chroma
574
+ from langchain_community.embeddings import HuggingFaceEmbeddings
575
+
576
+
577
+ _sql_cache_store = None
578
+ _sql_embedding_fn = None
579
+
580
+ SQL_CACHE_COLLECTION = "sql_cache_mpnet"
581
+
582
+ def get_sql_cache_store():
583
+ global _sql_cache_store, _sql_embedding_fn
584
+
585
+ if _sql_cache_store is not None:
586
+ return _sql_cache_store
587
+
588
+ if _sql_embedding_fn is None:
589
+ _sql_embedding_fn = HuggingFaceEmbeddings(
590
+ model_name=EMBED_MODEL_NAME,
591
+ encode_kwargs={"normalize_embeddings": True},
592
+ )
593
+
594
+ _sql_cache_store = Chroma(
595
+ client=get_chroma_client(),
596
+ collection_name=SQL_CACHE_COLLECTION,
597
+ embedding_function=_sql_embedding_fn,
598
+ )
599
+
600
+ return _sql_cache_store
601
+
602
+
603
+ # %%
604
+ def sanitize_metadata_for_chroma(metadata: dict) -> dict:
605
+ safe = {}
606
+ for k, v in (metadata or {}).items():
607
+ if v is None:
608
+ continue
609
+ if isinstance(v, (int, float, bool)):
610
+ safe[k] = v
611
+ elif isinstance(v, str):
612
+ safe[k] = v
613
+ else:
614
+ safe[k] = str(v)
615
+ return safe
616
+
617
+
618
+ # %%
619
+ def normalize_question_strict(q: str) -> str:
620
+ """
621
+ Deterministic normalization for exact cache hits.
622
+ """
623
+ if not q:
624
+ return ""
625
+ q = q.lower().strip()
626
+ q = re.sub(r"[^\w\s]", "", q)
627
+ q = re.sub(r"\s+", " ", q)
628
+ return q
629
+
630
+
631
+ # %%
632
+ # Helper: normalize question
633
+
634
+ def normalize_question_text(q: str) -> str:
635
+ if not q:
636
+ return ""
637
+ q = q.strip().lower()
638
+ q = re.sub(r"[^\w\s]", " ", q)
639
+ q = re.sub(r"\s+", " ", q).strip()
640
+ return q
641
+
642
+ # Helper: compute success rate
643
+ def compute_success_rate(md: dict) -> float:
644
+ sc = md.get("success_count", 0) or 0
645
+ tf = md.get("total_feedbacks", 0) or 0
646
+ if tf <= 0:
647
+ return 0.0
648
+ return float(sc) / float(tf)
649
+
650
+ # Insert initial cache entry (no feedback yet)
651
+ def cache_sql_answer_initial(question: str, sql: str, answer_md: str, store=None, extra_metadata: dict = None):
652
+ """
653
+ Insert a cached entry when you run a query and want to cache it regardless of feedback.
654
+ initial metrics: views=1, success_count=0, total_feedbacks=0, success_rate=1.0
655
+ """
656
+ if store is None:
657
+ store = get_sql_cache_store()
658
+
659
+ ident = uuid.uuid4().hex
660
+ norm = normalize_question_text(question)
661
+ md = {
662
+ "id": ident,
663
+ "normalized_question": norm,
664
+ "sql": sql,
665
+ "answer_md": answer_md,
666
+ "saved_at": time.time(),
667
+ "views": 1,
668
+ "success_count": 0,
669
+ "total_feedbacks": 0,
670
+ "success_rate": 1.0,
671
+ }
672
+ if extra_metadata:
673
+ md.update(extra_metadata)
674
+
675
+ # Use store's API;
676
+ store.add_texts([question], metadatas=[md])
677
+ return ident
678
+
679
+
680
+
681
+ # %%
682
+ import time
683
+ import logging
684
+ from typing import Optional, List, Dict, Any
685
+ from difflib import SequenceMatcher
686
+
687
+ _logger = logging.getLogger(__name__)
688
+
689
+ # -------------------------------------------------------------------------
690
+ # Utility helpers
691
+ # -------------------------------------------------------------------------
692
+
693
+ def _now_ts() -> float:
694
+ return time.time()
695
+
696
+ def similarity_score(a: str, b: str) -> float:
697
+ return SequenceMatcher(None, (a or ""), (b or "")).ratio()
698
+
699
+ # -------------------------------------------------------------------------
700
+ # Persist helper
701
+ # -------------------------------------------------------------------------
702
+ def langchain_upsert(
703
+ store,
704
+ text: str,
705
+ metadata: dict,
706
+ cache_id: str,
707
+ ):
708
+ safe_md = sanitize_metadata_for_chroma(metadata)
709
+
710
+ try:
711
+ store.add_texts(
712
+ texts=[text],
713
+ metadatas=[safe_md],
714
+ ids=[cache_id],
715
+ )
716
+ except TypeError:
717
+ store.add_texts(
718
+ texts=[text],
719
+ metadatas=[safe_md],
720
+ )
721
+
722
+
723
+ # -------------------------------------------------------------------------
724
+ # Cache insert / update
725
+ # -------------------------------------------------------------------------
726
+ def cache_sql_answer_dedup(
727
+ question: str,
728
+ sql: str,
729
+ answer_md: str,
730
+ metadata: dict,
731
+ store,
732
+ ):
733
+ norm_q_semantic = normalize_text(question)
734
+ norm_q_exact = normalize_question_strict(question)
735
+
736
+ cache_id = generate_cache_id(question, sql)
737
+ now = _now_ts()
738
+
739
+ md = {
740
+ # identity
741
+ "cache_id": cache_id,
742
+ "sql": sql,
743
+ "answer_md": answer_md,
744
+
745
+ # exact match key
746
+ "normalized_question": norm_q_exact,
747
+
748
+ # timestamps
749
+ "saved_at": metadata.get("saved_at", now),
750
+ "last_updated_at": now,
751
+ "last_viewed_at": metadata.get("last_viewed_at", 0),
752
+
753
+ # metrics
754
+ "good_count": metadata.get("good_count", 0),
755
+ "bad_count": metadata.get("bad_count", 0),
756
+ "total_feedbacks": metadata.get("total_feedbacks", 0),
757
+ "success_rate": metadata.get("success_rate", 0.5),
758
+ "views": metadata.get("views", 0),
759
+ }
760
+
761
+ langchain_upsert(
762
+ store=store,
763
+ text=norm_q_semantic, # semantic vector
764
+ metadata=md,
765
+ cache_id=cache_id,
766
+ )
767
+
768
+ return {
769
+ "question": question,
770
+ "sql": sql,
771
+ "answer_md": answer_md,
772
+ "metadata": md,
773
+ }
774
+
775
+ # -------------------------------------------------------------------------
776
+ # Find exact cached entry (question + SQL)
777
+ # -------------------------------------------------------------------------
778
+
779
+ def find_cached_doc_by_sql(question: str, sql: str, store):
780
+ cache_id = generate_cache_id(question, sql)
781
+ coll = getattr(store, "_collection", None)
782
+
783
+ if coll and hasattr(coll, "get"):
784
+ try:
785
+ res = coll.get(ids=[cache_id])
786
+ if res and res.get("metadatas"):
787
+ md = res["metadatas"][0]
788
+ return {
789
+ "id": cache_id,
790
+ "question": question,
791
+ "sql": md.get("sql"),
792
+ "answer_md": md.get("answer_md"),
793
+ "metadata": md,
794
+ }
795
+ except Exception:
796
+ pass
797
+
798
+ return None
799
+
800
+ # -------------------------------------------------------------------------
801
+ # Retrieve cached answers ranked primarily by success rate
802
+ # -------------------------------------------------------------------------
803
+
804
+ import re
805
+ import unicodedata
806
+
807
+
808
+ def normalize_text(text: str) -> str:
809
+ if not text:
810
+ return ""
811
+ text = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode("ascii")
812
+ text = text.lower()
813
+ text = re.sub(r"[^\w\s]", " ", text)
814
+ text = re.sub(r"\s+", " ", text).strip()
815
+ return text
816
+
817
+ import hashlib
818
+
819
+ def generate_cache_id(question: str, sql: str) -> str:
820
+ q = normalize_text(question)
821
+ s = (sql or "").strip()
822
+ key = f"{q}||{s}".encode("utf-8")
823
+ return hashlib.sha1(key).hexdigest()
824
+
825
+
826
+ def rank_cached_candidates(candidates: list[dict]) -> dict:
827
+ """
828
+ Deterministic quality-first ranking.
829
+ """
830
+ candidates.sort(
831
+ key=lambda c: (
832
+ -float(c["metadata"].get("success_rate", 0.5)),
833
+ -int(c["metadata"].get("good_count", 0)),
834
+ int(c["metadata"].get("bad_count", 0)),
835
+ -float(c["metadata"].get("last_updated_at", 0)),
836
+ )
837
+ )
838
+ return candidates[0]
839
+
840
+
841
+
842
+ def retrieve_exact_cached_sql(question: str, store):
843
+ """
844
+ Exact question match, but still quality-ranked.
845
+ """
846
+ norm_q = normalize_question_strict(question)
847
+ coll = store._collection
848
+
849
+ try:
850
+ res = coll.get(where={"normalized_question": norm_q})
851
+ if not res or not res.get("metadatas"):
852
+ return None
853
+
854
+ candidates = []
855
+ for md in res["metadatas"]:
856
+ candidates.append({
857
+ "matched_question": question,
858
+ "sql": md["sql"],
859
+ "answer_md": md.get("answer_md", ""),
860
+ "distance": 0.0,
861
+ "metadata": md,
862
+ })
863
+
864
+ return rank_cached_candidates(candidates)
865
+
866
+ except Exception:
867
+ return None
868
+
869
+
870
+ def retrieve_best_cached_sql(
871
+ question: str,
872
+ store,
873
+ max_distance: float = 0.25,
874
+ ):
875
+ norm_q = normalize_text(question)
876
+ results = store.similarity_search_with_score(norm_q, k=20)
877
+
878
+ candidates = []
879
+
880
+ for doc, score in results:
881
+ distance = float(score)
882
+ if distance > max_distance:
883
+ continue
884
+
885
+ md = doc.metadata or {}
886
+ if "sql" not in md:
887
+ continue
888
+
889
+ candidates.append({
890
+ "matched_question": doc.page_content,
891
+ "sql": md["sql"],
892
+ "answer_md": md.get("answer_md", ""),
893
+ "distance": distance,
894
+ "metadata": md,
895
+
896
+ # ranking signals (FORCED numeric)
897
+ "success_rate": float(md.get("success_rate", 0.5)),
898
+ "good": int(md.get("good_count", 0)),
899
+ "bad": int(md.get("bad_count", 0)),
900
+ "views": int(md.get("views", 0)),
901
+ "last_updated": float(md.get("last_updated_at", 0)),
902
+ })
903
+
904
+ if not candidates:
905
+ return None
906
+
907
+ # QUALITY-FIRST RANKING
908
+ candidates.sort(
909
+ key=lambda c: (
910
+ -c["success_rate"],
911
+ -c["good"],
912
+ c["bad"],
913
+ c["distance"],
914
+ -c["last_updated"],
915
+ )
916
+ )
917
+
918
+
919
+ return candidates[0]
920
+
921
+ # -------------------------------------------------------------------------
922
+ # Increment views
923
+ # -------------------------------------------------------------------------
924
+
925
+ def increment_cache_views(metadata: dict, store):
926
+ if not metadata:
927
+ return False
928
+
929
+ cache_id = metadata.get("cache_id")
930
+ if not cache_id:
931
+ return False
932
+
933
+ md = dict(metadata)
934
+ md["views"] = int(md.get("views", 0)) + 1
935
+ md["last_viewed_at"] = _now_ts()
936
+ md["last_updated_at"] = _now_ts()
937
+ md["saved_at"] = md.get("saved_at", _now_ts())
938
+
939
+ try:
940
+ langchain_upsert(
941
+ store=store,
942
+ text=normalize_text(md.get("normalized_question", "")),
943
+ metadata=md,
944
+ cache_id=cache_id,
945
+ )
946
+ return True
947
+ except Exception:
948
+ _logger.exception("increment_cache_views failed")
949
+ return False
950
+
951
+
952
+ # Update metrics on feedback
953
+ def update_cache_on_feedback(
954
+ question: str,
955
+ original_doc_md: dict,
956
+ user_marked_good: bool,
957
+ llm_corrected_sql: str | None,
958
+ llm_corrected_answer_md: str | None,
959
+ store,
960
+ ):
961
+ if not original_doc_md:
962
+ return
963
+
964
+ md = dict(original_doc_md["metadata"])
965
+ cache_id = md["cache_id"]
966
+
967
+ # ---- feedback counts ----
968
+ if user_marked_good:
969
+ md["good_count"] = md.get("good_count", 0) + 1
970
+ else:
971
+ md["bad_count"] = md.get("bad_count", 0) + 1
972
+
973
+ md["total_feedbacks"] = md.get("total_feedbacks", 0) + 1
974
+ md["success_rate"] = (
975
+ md["good_count"] / md["total_feedbacks"]
976
+ if md["total_feedbacks"] > 0 else 0.5
977
+ )
978
+
979
+ # ---- timestamps ----
980
+ md["saved_at"] = md.get("saved_at", _now_ts()) # preserve
981
+ md["last_updated_at"] = _now_ts()
982
+
983
+ langchain_upsert(
984
+ store=store,
985
+ text=normalize_text(question),
986
+ metadata=md,
987
+ cache_id=cache_id,
988
+ )
989
+
990
+ # -------------------------
991
+ # Corrected SQL --> NEW ENTRY
992
+ # -------------------------
993
+ if llm_corrected_sql and llm_corrected_answer_md:
994
+ cache_sql_answer_dedup(
995
+ question=question,
996
+ sql=llm_corrected_sql,
997
+ answer_md=llm_corrected_answer_md,
998
+ metadata={
999
+ "good_count": 1,
1000
+ "bad_count": 0,
1001
+ "total_feedbacks": 1,
1002
+ "success_rate": 1.0,
1003
+ "views": 0,
1004
+ "saved_at": _now_ts(),
1005
+ },
1006
+ store=store,
1007
+ )
1008
+
1009
+
1010
+ # %%
1011
+ import datetime
1012
+
1013
+ def log_pipeline(event: str, detail: str = ""):
1014
+ """
1015
+ Centralized pipeline logger.
1016
+ Shows in console + can be routed to file later.
1017
+ """
1018
+ ts = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
1019
+ msg = f"[{ts}] PIPELINE::{event}"
1020
+ if detail:
1021
+ msg += f" | {detail}"
1022
+ print(msg)
1023
+
1024
+
1025
+ # %%
1026
+
1027
+
1028
+ # %%
1029
+ # ### 8. Groq LLM via LangChain
1030
+
1031
+ from langchain_groq import ChatGroq
1032
+ import re
1033
+ import gradio as gr
1034
+
1035
+ llm = ChatGroq(model=GROQ_MODEL_NAME, groq_api_key=GROQ_API_KEY)
1036
+
1037
+ # %%
1038
+ def get_rag_context(question: str) -> str:
1039
+ """
1040
+ Retrieve the most relevant schema documents for the question.
1041
+ """
1042
+ docs = rag_retriever.invoke(question)
1043
+ return "\n\n---\n\n".join(d.page_content for d in docs)
1044
+
1045
+ def clean_sql(sql: str) -> str:
1046
+ sql = sql.strip()
1047
+ if "```" in sql:
1048
+ sql = sql.replace("```sql", "").replace("```", "").strip()
1049
+ return sql
1050
+
1051
+ def extract_sql_from_markdown(text: str) -> str:
1052
+ """
1053
+ Extract the first ```sql ... ``` block from LLM output.
1054
+ If not found, return the whole text.
1055
+ """
1056
+ match = re.search(r"```sql(.*?)```", text, flags=re.DOTALL | re.IGNORECASE)
1057
+ if match:
1058
+ return match.group(1).strip()
1059
+ return text.strip()
1060
+
1061
+ def extract_explanation_after_marker(text: str, marker: str = "EXPLANATION:") -> str:
1062
+ """
1063
+ After the given marker, return the rest of the text as explanation.
1064
+ """
1065
+ idx = text.upper().find(marker.upper())
1066
+ if idx == -1:
1067
+ return text.strip()
1068
+ return text[idx + len(marker):].strip()
1069
+
1070
+ # 6b. General / descriptive questions
1071
+
1072
+ GENERAL_DESC_KEYWORDS = [
1073
+ "what is this dataset about",
1074
+ "what is this data about",
1075
+ "describe this dataset",
1076
+ "describe the dataset",
1077
+ "dataset overview",
1078
+ "data overview",
1079
+ "summary of the dataset",
1080
+ "explain this dataset",
1081
+ ]
1082
+
1083
+
1084
+ def is_general_question(question: str) -> bool:
1085
+ """
1086
+ Detect high-level descriptive questions where we should answer
1087
+ directly from schema context instead of generating SQL.
1088
+ """
1089
+ q = question.lower().strip()
1090
+ return any(key in q for key in GENERAL_DESC_KEYWORDS)
1091
+
1092
+
1093
+ def answer_general_question(question: str) -> str:
1094
+ """
1095
+ Use the RAG schema docs to generate a rich, high-level description
1096
+ of the Olist dataset for conceptual questions.
1097
+ """
1098
+ rag_context = get_rag_context(question)
1099
+
1100
+ system_instructions = """
1101
+ You are a data documentation expert.
1102
+
1103
+ You will be given:
1104
+ - Schema documentation for the Olist dataset (tables, descriptions, columns, relationships).
1105
+ - A high-level user question like "what is this dataset about?".
1106
+
1107
+ Your job:
1108
+ - Write a clear, structured overview of the dataset.
1109
+ - Explain the main entities (customers, orders, items, products, sellers, payments, reviews, geolocation).
1110
+ - Mention typical analysis use-cases (delivery performance, customer behavior, seller performance, product/category analysis, etc.).
1111
+ - Target a non-technical person.
1112
+
1113
+ Do NOT write SQL. Answer in Markdown.
1114
+ """
1115
+
1116
+ prompt = (
1117
+ system_instructions
1118
+ + "\n\n=== SCHEMA CONTEXT ===\n"
1119
+ + rag_context
1120
+ + "\n\n=== USER QUESTION ===\n"
1121
+ + question
1122
+ + "\n\nDetailed dataset overview:"
1123
+ )
1124
+
1125
+ log_prompt("GENERAL_DATASET_QUESTION", prompt)
1126
+
1127
+ response = llm.invoke(prompt)
1128
+ log_run_event("RAW_MODEL_RESPONSE_GENERAL_DATASET", response.content)
1129
+
1130
+ return response.content.strip()
1131
+
1132
+ # %%
1133
+ # ### 9. SQL execution / validation
1134
+
1135
+ def execute_sql(sql: str, connection: sqlite3.Connection) -> Tuple[Optional[pd.DataFrame], Optional[str]]:
1136
+ """
1137
+ Execute SQL on SQLite and return a DataFrame, else return an error.
1138
+ """
1139
+ try:
1140
+ df = pd.read_sql_query(sql, connection)
1141
+ return df, None
1142
+ except Exception as e:
1143
+ return None, str(e)
1144
+
1145
+ def validate_sql(sql: str, connection: sqlite3.Connection) -> Tuple[bool, Optional[str]]:
1146
+ """
1147
+ Basic SQL validator:
1148
+ - Uses EXPLAIN QUERY PLAN to detect syntax or schema issues.
1149
+ """
1150
+ try:
1151
+ cursor = connection.cursor()
1152
+ cursor.execute(f"EXPLAIN QUERY PLAN {sql}")
1153
+ return True, None
1154
+ except Exception as e:
1155
+ return False, str(e)
1156
+
1157
+ # %%
1158
+ # ### 10. SQL Generation + Repair with LLM
1159
+ def review_and_correct_sql_with_llm(
1160
+ question: str,
1161
+ generated_sql: str,
1162
+ user_feedback_comment: str,
1163
+ validation_payload: dict,
1164
+ decision_reason: str,
1165
+ rag_context: str,
1166
+ ) -> tuple[str, str]:
1167
+ """
1168
+ Fix SQL ONLY after LLM has decided it is necessary.
1169
+ """
1170
+
1171
+ log_pipeline("SQL_CORRECTION_START")
1172
+
1173
+ evidence_md = ""
1174
+ for chk in validation_payload.get("equivalence", []):
1175
+ evidence_md += chk["df"].to_markdown(index=False) + "\n\n"
1176
+
1177
+ prompt = f"""
1178
+ Original question:
1179
+ {question}
1180
+
1181
+ Original SQL:
1182
+ ```sql
1183
+ {generated_sql}
1184
+
1185
+ User feedback:
1186
+ {user_feedback_comment}
1187
+
1188
+ Reason SQL is considered incorrect:
1189
+ {decision_reason}
1190
+
1191
+ Validation evidence:
1192
+ {evidence_md}
1193
+
1194
+ Schema:
1195
+ {rag_context}
1196
+
1197
+ TASK:
1198
+
1199
+ Fix the SQL ONLY if necessary
1200
+
1201
+ If SQL is already correct, return it unchanged
1202
+
1203
+ Explain your reasoning
1204
+
1205
+ Return corrected SQL and explanation.
1206
+ """
1207
+
1208
+ resp = llm.invoke(prompt)
1209
+
1210
+ corrected_sql = extract_sql_from_markdown(resp.content) or generated_sql
1211
+ corrected_sql = clean_sql(corrected_sql)
1212
+
1213
+ explanation = extract_explanation_after_marker(resp.content, "EXPLANATION:")
1214
+
1215
+ log_pipeline(
1216
+ "SQL_CORRECTION_DONE",
1217
+ f"sql_changed={corrected_sql.strip() != generated_sql.strip()}"
1218
+ )
1219
+
1220
+ return corrected_sql, explanation
1221
+
1222
+
1223
+
1224
+ # %%
1225
+
1226
+
1227
+ # %%
1228
+ # Generate SQL
1229
+
1230
+ def generate_sql(question: str, rag_context: str) -> str:
1231
+ """
1232
+ Generate SQL using LLM, but also pull in any past user feedback
1233
+ (corrected SQL) for this question as external guidance.
1234
+ """
1235
+ # External correction from past feedback, if any
1236
+ last_fb = get_last_feedback_for_question(conn, question)
1237
+ if last_fb and last_fb.get("corrected_sql"):
1238
+ previous_feedback_block = f"""
1239
+ EXTERNAL USER FEEDBACK FROM PAST RUNS:
1240
+
1241
+ Previous generated SQL:
1242
+ {last_fb['generated_sql']}
1243
+
1244
+ Corrected SQL (preferred reference):
1245
+ {last_fb['corrected_sql']}
1246
+
1247
+ User comment & prior explanation:
1248
+ {last_fb.get('comment') or '(none)'}
1249
+
1250
+ You must avoid repeating the same mistake and should follow the logic of
1251
+ the corrected SQL when appropriate, while still reasoning from the schema.
1252
+ """
1253
+ else:
1254
+ previous_feedback_block = ""
1255
+
1256
+ system_instructions = f"""
1257
+ You are a senior data analyst writing SQL for a SQLite database.
1258
+
1259
+ You will be given:
1260
+
1261
+ - A description of available tables, columns, and relationships (schema + YAML metadata).
1262
+ - A natural language question from the user.
1263
+
1264
+ Your job:
1265
+
1266
+ - Write ONE valid SQLite SQL query that answers the question.
1267
+ - ONLY use tables and columns that exist in the schema_context.
1268
+ - Use correct JOINS (Left, Right, Inner, Outer, Full Outer etc.) with ON conditions.
1269
+ - Do not use DROP, INSERT, UPDATE, DELETE or other destructive operations.
1270
+ - Always use floating-point division for percentage calculations using 1.0 * numerator / denominator,
1271
+ and round to 2 decimals when appropriate.
1272
+
1273
+ {previous_feedback_block}
1274
+ """
1275
+
1276
+ prompt = (
1277
+ system_instructions
1278
+ + "\n\n=== RAG CONTEXT ===\n"
1279
+ + rag_context
1280
+ + "\n\n=== USER QUESTION ===\n"
1281
+ + question
1282
+ + "\n\nSQL query:"
1283
+ )
1284
+
1285
+ log_prompt("SQL_GENERATION", prompt)
1286
+ response = llm.invoke(prompt)
1287
+ log_run_event("RAW_MODEL_RESPONSE_SQL_GENERATION", response.content)
1288
+
1289
+ sql = clean_sql(response.content)
1290
+ return sql
1291
+
1292
+
1293
+ # %%
1294
+ # Repair SQL
1295
+
1296
+ def repair_sql(
1297
+ question: str,
1298
+ rag_context: str,
1299
+ bad_sql: str,
1300
+ error_message: str,
1301
+ ) -> str:
1302
+ """
1303
+ Ask the LLM to correct a failing SQL query.
1304
+ """
1305
+ system_instructions = """
1306
+ You are a senior data analyst fixing an existing SQL query for a SQLite database.
1307
+
1308
+ You will be given:
1309
+
1310
+ - Schema context (tables, columns, relationships).
1311
+ - The user's question.
1312
+ - A previously generated SQL query that failed.
1313
+ - The SQLite error message.
1314
+
1315
+ Your job:
1316
+
1317
+ - Diagnose why the query failed.
1318
+ - Rewrite ONE valid SQLite SQL query that answers the question.
1319
+ - ONLY use tables and columns that exist in the schema_context.
1320
+ - Use correct JOINS (Left, Right, Inner, Outer, Full Outer etc.) with ON conditions.
1321
+ - Do not use DROP, INSERT, UPDATE, DELETE or other destructive operations.
1322
+ - Return ONLY the corrected SQL query, no explanation or markdown.
1323
+ """
1324
+
1325
+ prompt = (
1326
+ system_instructions
1327
+ + "\n\n=== RAG CONTEXT ===\n"
1328
+ + rag_context
1329
+ + "\n\n=== USER QUESTION ===\n"
1330
+ + question
1331
+ + "\n\n=== PREVIOUS (FAILING) SQL ===\n"
1332
+ + bad_sql
1333
+ + "\n\n=== SQLITE ERROR ===\n"
1334
+ + error_message
1335
+ + "\n\nCorrected SQL query:"
1336
+ )
1337
+
1338
+ log_prompt("SQL_REPAIR", prompt)
1339
+ response = llm.invoke(prompt)
1340
+ log_run_event("RAW_MODEL_RESPONSE_SQL_REPAIR", response.content)
1341
+
1342
+ sql = clean_sql(response.content)
1343
+ return sql
1344
+
1345
+
1346
+ # %%
1347
+ ### 11. Result summarization
1348
+
1349
+ def summarize_results(
1350
+ question: str,
1351
+ sql: str,
1352
+ df: Optional[pd.DataFrame],
1353
+ rag_context: str,
1354
+ error: Optional[str] = None,
1355
+ ) -> str:
1356
+ """
1357
+ Ask the LLM to produce a concise, human-readable answer.
1358
+ """
1359
+ system_instructions = """
1360
+ You are a senior data analyst.
1361
+
1362
+ You will be given:
1363
+
1364
+ The user's question.
1365
+ The final SQL that was executed.
1366
+ A small preview of the query result (as a Markdown table, if available).
1367
+ Optional error information if the query failed.
1368
+
1369
+ Your job:
1370
+
1371
+ Provide a clear, concise answer in Markdown.
1372
+ If the result is numeric / aggregated, explain what it means in business terms.
1373
+ If there was an error, explain it simply and suggest how the user could rephrase.
1374
+ Do NOT show raw SQL unless it is helpful to the user.
1375
+ """
1376
+
1377
+ # Build a markdown table preview if we have data
1378
+ if df is not None and not df.empty:
1379
+ preview_rows = min(len(df), 50)
1380
+ df_preview_md = df.head(preview_rows).to_markdown(index=False)
1381
+ else:
1382
+ df_preview_md = "(no rows returned)"
1383
+
1384
+ prompt = (
1385
+ system_instructions
1386
+ + "\n\n=== USER QUESTION ===\n"
1387
+ + question
1388
+ + "\n\n=== EXECUTED SQL ===\n"
1389
+ + sql
1390
+ + "\n\n=== QUERY RESULT PREVIEW ===\n"
1391
+ + df_preview_md
1392
+ + "\n\n=== RAG CONTEXT (schema) ===\n"
1393
+ + rag_context
1394
+ )
1395
+
1396
+ if error:
1397
+ prompt += "\n\n=== ERROR ===\n" + error
1398
+
1399
+ # Logging helpers assumed to exist
1400
+ log_prompt("RESULT_SUMMARY", prompt)
1401
+
1402
+ response = llm.invoke(prompt)
1403
+ log_run_event("RAW_MODEL_RESPONSE_RESULT_SUMMARY", response.content)
1404
+
1405
+ return response.content.strip()
1406
+
1407
+
1408
+ # %%
1409
+ def backend_pipeline(question: str):
1410
+ """
1411
+ STRICT cache-first backend.
1412
+ ALWAYS returns EXACTLY 10 values.
1413
+ """
1414
+
1415
+ if not question or not question.strip():
1416
+ return (
1417
+ "Please type a question.",
1418
+ pd.DataFrame(),
1419
+ "",
1420
+ "",
1421
+ "",
1422
+ "",
1423
+ {},
1424
+ 4,
1425
+ "**Feedback attempts remaining: 4**",
1426
+ "",
1427
+ )
1428
+
1429
+ attempts_left = 4
1430
+ attempts_text = f"**Feedback attempts remaining: {attempts_left}**"
1431
+ store = get_sql_cache_store()
1432
+
1433
+ # ---------------- CACHE LOOKUP ----------------
1434
+ cached = retrieve_exact_cached_sql(question, store)
1435
+ if cached is None:
1436
+ cached = retrieve_best_cached_sql(question, store, max_distance=0.25)
1437
+
1438
+ # ---------------- CACHE HIT ----------------
1439
+ if cached:
1440
+ increment_cache_views(cached["metadata"], store)
1441
+
1442
+ rag_context = get_rag_context(question)
1443
+ sql = cached["sql"]
1444
+
1445
+ df, err = execute_sql(sql, conn)
1446
+ if err:
1447
+ df = pd.DataFrame()
1448
+
1449
+ md = cached["metadata"]
1450
+
1451
+ answer_md = "### Cache Hit\n\n" + cached.get("answer_md", "")
1452
+
1453
+ debug_md = f"""
1454
+ ### Query Provenance (Cache)
1455
+
1456
+ **Matched question:** `{cached.get("matched_question", "")}`
1457
+ **Success rate:** {md.get("success_rate", 0.5):.2f}
1458
+ **Good / Bad:** {md.get("good_count", 0)} / {md.get("bad_count", 0)}
1459
+ **Views:** {md.get("views", 0)}
1460
+
1461
+ **SQL used:**
1462
+ ```sql
1463
+ {sql}
1464
+
1465
+
1466
+ """
1467
+
1468
+ return (
1469
+ answer_md,
1470
+ df,
1471
+ sql,
1472
+ rag_context,
1473
+ question,
1474
+ answer_md,
1475
+ df_to_state(df),
1476
+ attempts_left,
1477
+ attempts_text,
1478
+ debug_md,
1479
+ )
1480
+
1481
+ # ---------------- LLM FLOW ----------------
1482
+ rag_context = get_rag_context(question)
1483
+ sql = generate_sql(question, rag_context)
1484
+
1485
+ is_valid, err = validate_sql(sql, conn)
1486
+ if not is_valid and err:
1487
+ sql = repair_sql(question, rag_context, sql, err)
1488
+
1489
+ df, exec_error = execute_sql(sql, conn)
1490
+ if exec_error:
1491
+ df = pd.DataFrame()
1492
+
1493
+ answer_md = summarize_results(
1494
+ question=question,
1495
+ sql=sql,
1496
+ df=df if not exec_error else None,
1497
+ rag_context=rag_context,
1498
+ error=exec_error,
1499
+ )
1500
+
1501
+ # Cache LLM result
1502
+ cache_sql_answer_dedup(
1503
+ question=question,
1504
+ sql=sql,
1505
+ answer_md=answer_md,
1506
+ metadata={
1507
+ "good_count": 0,
1508
+ "bad_count": 0,
1509
+ "total_feedbacks": 0,
1510
+ "success_rate": 0.5,
1511
+ "views": 1,
1512
+ "saved_at": time.time(),
1513
+ },
1514
+ store=store,
1515
+ )
1516
+
1517
+ debug_md = f"""
1518
+
1519
+ Query Provenance (LLM Generated)
1520
+
1521
+ Source: LLM
1522
+ Execution status: {"Error" if exec_error else "Success"}
1523
+
1524
+ SQL used:
1525
+
1526
+ {sql}
1527
+
1528
+
1529
+ """
1530
+
1531
+ return (
1532
+ answer_md,
1533
+ df,
1534
+ sql,
1535
+ rag_context,
1536
+ question,
1537
+ answer_md,
1538
+ df_to_state(df),
1539
+ attempts_left,
1540
+ attempts_text,
1541
+ debug_md,
1542
+ )
1543
+
1544
+ # %%
1545
+ import re
1546
+
1547
+ def looks_like_sql(text: str) -> bool:
1548
+ if not text:
1549
+ return False
1550
+ return bool(re.search(
1551
+ r"\bselect\b|\bfrom\b|\bwhere\b|\bjoin\b|\bgroup by\b|\border by\b",
1552
+ text,
1553
+ flags=re.I,
1554
+ ))
1555
+
1556
+
1557
+ def is_feedback_sufficient(feedback_text: str) -> bool:
1558
+ """
1559
+ Decide whether feedback is actionable WITHOUT LLM.
1560
+ """
1561
+ if not feedback_text:
1562
+ return False
1563
+
1564
+ text = feedback_text.strip().lower()
1565
+
1566
+ # Long feedback → sufficient
1567
+ if len(text) >= 60:
1568
+ return True
1569
+
1570
+ # SQL pasted
1571
+ if looks_like_sql(text):
1572
+ return True
1573
+
1574
+ # Numbers + comparison language → sufficient
1575
+ if re.search(r"\b\d+\b", text) and any(
1576
+ k in text for k in [
1577
+ "last year", "previous", "this year",
1578
+ "increase", "decrease", "higher", "lower"
1579
+ ]
1580
+ ):
1581
+ return True
1582
+
1583
+ # Analytical keywords
1584
+ signal_words = [
1585
+ "filter", "where", "year", "month", "should", "instead",
1586
+ "expected", "wrong", "missing", "count", "distinct",
1587
+ "join", "exclude", "include", "only"
1588
+ ]
1589
+
1590
+ signals = sum(1 for w in signal_words if w in text)
1591
+ if signals >= 1 and len(text) >= 20:
1592
+ return True
1593
+
1594
+ return False
1595
+
1596
+
1597
+ # %%
1598
+ def build_followup_prompt_for_user(sample_feedback: str = "") -> str:
1599
+ """
1600
+ Deterministic follow-up question to ask the user when feedback is vague.
1601
+ Returns a friendly prompt that the UI can display to the user.
1602
+ """
1603
+ base = (
1604
+ "Thanks — I need a bit more detail to act on this feedback.\n\n"
1605
+ "Please tell me one (or more) of the following so I can check and correct the result:\n\n"
1606
+ "1. Which part looks wrong — the **numbers**, the **aggregation** (sum/count/avg),\n"
1607
+ " the **time range** (year/month), or the **filters** applied?\n"
1608
+ "2. If you expected a different number, what was the expected number (and how was it computed)?\n"
1609
+ "3. If you have a corrected SQL snippet, paste it (I can run and compare it).\n\n"
1610
+ "Examples you can copy-paste:\n"
1611
+ )
1612
+ examples = (
1613
+ "- \"I think the query should count DISTINCT customer_unique_id, not customer_id.\"\n"
1614
+ "- \"This looks off for year 2018 — I expected the count for 2018 to be ~40k.\"\n"
1615
+ "- \"Please exclude canceled orders (order_status = 'canceled').\"\n"
1616
+ "- \"SELECT COUNT(DISTINCT customer_unique_id) FROM olist_customers_dataset;\"\n"
1617
+ )
1618
+ hint = "\nIf you prefer, just paste a corrected SQL snippet and I'll run it and compare."
1619
+ prompt = base + examples + hint
1620
+ if sample_feedback:
1621
+ prompt = f"I saw your feedback: \"{sample_feedback}\"\n\n" + prompt
1622
+ return prompt
1623
+
1624
+
1625
+
1626
+ # %%
1627
+ def interpret_feedback_intent(question: str, feedback_text: str) -> dict:
1628
+ """
1629
+ Convert business feedback into a testable hypothesis.
1630
+ NO SQL generation here.
1631
+ """
1632
+
1633
+ system_prompt = """
1634
+ You are a senior analytics reviewer.
1635
+
1636
+ Your task:
1637
+ - Identify what the user is CLAIMING.
1638
+ - Do NOT assume they are correct.
1639
+ - Do NOT write SQL.
1640
+
1641
+ Possible intents:
1642
+ - comparison_claim (mentions last year / previous / higher / lower)
1643
+ - overcount
1644
+ - undercount
1645
+ - missing_entities
1646
+ - wrong_filter
1647
+ - wrong_time_range
1648
+ - unclear
1649
+
1650
+ Return JSON ONLY.
1651
+ """
1652
+
1653
+ prompt = f"""
1654
+ USER QUESTION:
1655
+ {question}
1656
+
1657
+ USER FEEDBACK:
1658
+ {feedback_text}
1659
+
1660
+ Return JSON exactly like this:
1661
+ {{
1662
+ "intent": "comparison_claim | overcount | undercount | missing_entities | wrong_filter | wrong_time_range | unclear",
1663
+ "confidence": "low | medium | high"
1664
+ }}
1665
+ """
1666
+
1667
+ resp = llm.invoke(system_prompt + "\n\n" + prompt)
1668
+ print(resp)
1669
+
1670
+ try:
1671
+ return json.loads(resp.content)
1672
+ except Exception:
1673
+ return {
1674
+ "intent": "unclear",
1675
+ "confidence": "low",
1676
+ }
1677
+
1678
+
1679
+ # %%
1680
+ def run_validation_queries(
1681
+ intent_info: dict,
1682
+ question: str,
1683
+ original_sql: str,
1684
+ user_feedback: str,
1685
+ rag_context: str,
1686
+ ) -> dict:
1687
+ """
1688
+ Generate AND EXECUTE validation SQL.
1689
+ Separates equivalence checks vs context checks.
1690
+ Uses USER FEEDBACK explicitly for context validation.
1691
+ """
1692
+
1693
+ log_pipeline(
1694
+ "VALIDATION_START",
1695
+ f"intent={intent_info.get('intent')}"
1696
+ )
1697
+
1698
+ system_prompt = f"""
1699
+ You are validating a business claim.
1700
+
1701
+ User intent:
1702
+ {intent_info.get("intent")}
1703
+
1704
+ Original question:
1705
+ {question}
1706
+
1707
+ User feedback (IMPORTANT):
1708
+ {user_feedback}
1709
+
1710
+ Original SQL:
1711
+ {original_sql}
1712
+
1713
+ Schema context:
1714
+ {rag_context}
1715
+
1716
+ TASK:
1717
+ - Generate 2-4 SQL queries.
1718
+ - Mark EACH query explicitly as one of:
1719
+ - "equivalence":
1720
+ * Alternative formulations of the SAME question
1721
+ * Used to verify SQL correctness (joins, filters, logic)
1722
+ - "context":
1723
+ * Used to VERIFY or CHALLENGE the user's feedback
1724
+ * If the user mentions years, comparisons, growth, or missing entities,
1725
+ generate year-over-year or comparative queries.
1726
+ - DO NOT fix or modify the original SQL.
1727
+ - These queries are ONLY for validation and analysis.
1728
+
1729
+ IMPORTANT:
1730
+ - Context queries MUST be driven by the user's feedback.
1731
+ - If the user claims a number, for example, values of a previous year, then generate queries that can verify that claim from the data.
1732
+ - If the user provides some query to test in the feedback for the original question, use it as well. Do not assume it is correct.
1733
+ Return JSON ONLY in this format:
1734
+ {{
1735
+ "checks": [
1736
+ {{
1737
+ "type": "equivalence | context",
1738
+ "sql": "SELECT ...",
1739
+ "label": "short description of what this validates"
1740
+ }}
1741
+ ]
1742
+ }}
1743
+ """
1744
+
1745
+ resp = llm.invoke(system_prompt)
1746
+ raw = resp.content.strip()
1747
+ print(raw)
1748
+
1749
+ # Strip ```json fences if present
1750
+ if raw.startswith("```"):
1751
+ raw = raw.strip("`")
1752
+ raw = raw.replace("json", "", 1).strip()
1753
+
1754
+ try:
1755
+ parsed = json.loads(raw)
1756
+ except Exception as e:
1757
+ log_pipeline("VALIDATION_PARSE_FAILED", str(e))
1758
+ return {
1759
+ "equivalence": [],
1760
+ "context": [],
1761
+ }
1762
+
1763
+ equivalence = []
1764
+ context = []
1765
+
1766
+ for chk in parsed.get("checks", []):
1767
+ sql = chk.get("sql")
1768
+ chk_type = chk.get("type")
1769
+ label = chk.get("label", "unnamed check")
1770
+
1771
+ if not sql or chk_type not in ("equivalence", "context"):
1772
+ continue
1773
+
1774
+ df, err = execute_sql(sql, conn)
1775
+ print(df)
1776
+
1777
+ log_pipeline(
1778
+ "VALIDATION_SQL_EXECUTED",
1779
+ f"type={chk_type} | label={label}"
1780
+ )
1781
+
1782
+ if err or df is None or df.empty:
1783
+ continue
1784
+
1785
+ payload = {
1786
+ "label": label,
1787
+ "sql": sql,
1788
+ "df": df,
1789
+ }
1790
+
1791
+ if chk_type == "equivalence":
1792
+ equivalence.append(payload)
1793
+ else:
1794
+ context.append(payload)
1795
+
1796
+ log_pipeline(
1797
+ "VALIDATION_DONE",
1798
+ f"equivalence={len(equivalence)}, context={len(context)}"
1799
+ )
1800
+
1801
+ return {
1802
+ "equivalence": equivalence,
1803
+ "context": context,
1804
+ }
1805
+
1806
+
1807
+ # %%
1808
+ def safe_json_load(text: str) -> dict | None:
1809
+ try:
1810
+ return json.loads(text)
1811
+ except Exception:
1812
+ pass
1813
+
1814
+ # Try extracting first JSON block
1815
+ match = re.search(r"\{[\s\S]*\}", text)
1816
+ if match:
1817
+ try:
1818
+ return json.loads(match.group(0))
1819
+ except Exception:
1820
+ return None
1821
+ return None
1822
+
1823
+
1824
+ # %%
1825
+ def decide_after_validation_with_llm(
1826
+ question: str,
1827
+ original_sql: str,
1828
+ user_feedback: str,
1829
+ intent_info: dict,
1830
+ original_df: pd.DataFrame,
1831
+ validation_payload: dict,
1832
+ rag_context: str,
1833
+ ) -> dict:
1834
+ """
1835
+ Use LLM to decide whether SQL must change or explanation is sufficient.
1836
+ Returns a structured decision.
1837
+ """
1838
+
1839
+ log_pipeline("DECISION_LLM_START")
1840
+
1841
+ # Build evidence
1842
+ evidence_md = "### Original Result\n"
1843
+ evidence_md += original_df.to_markdown(index=False)
1844
+
1845
+ for i, chk in enumerate(validation_payload.get("equivalence", []), 1):
1846
+ evidence_md += f"\n\n### Equivalence Check {i}: {chk['label']}\n"
1847
+ evidence_md += chk["df"].to_markdown(index=False)
1848
+
1849
+ for i, chk in enumerate(validation_payload.get("context", []), 1):
1850
+ evidence_md += f"\n\n### Context Check {i}: {chk['label']}\n"
1851
+ evidence_md += chk["df"].to_markdown(index=False)
1852
+
1853
+ system_prompt = """
1854
+ You are a senior analytics and data analyst.
1855
+
1856
+ Your task:
1857
+ - Decide whether the ORIGINAL SQL is logically correct or not, given the original question, the initial result, the feedback and the evidences of the equivalence check and context shown to you.
1858
+ - Do NOT judge based on expectations or growth alone.
1859
+ - Different definitions (e.g. customers vs customers-with-orders) are NOT errors.
1860
+ - Only mark SQL incorrect if evidences shows a true flaw in the results or the logic.
1861
+
1862
+ CRITICAL RULES:
1863
+ - You must return VALID JSON.
1864
+ - DO NOT add explnations outside JSON.
1865
+ - DO NO use markdown.
1866
+ - DO NOT include extra text.
1867
+
1868
+ Return JSON ONLY in this format:
1869
+ {
1870
+ "decision": "correct_sql | not_correct_sql",
1871
+ "confidence": "high | medium | low",
1872
+ "reason": "provide an explanation here"
1873
+ }
1874
+ """
1875
+
1876
+ prompt = f"""
1877
+ Original question:
1878
+ {question}
1879
+
1880
+ Original SQL:
1881
+ {original_sql}
1882
+
1883
+ User feedback:
1884
+ {user_feedback}
1885
+
1886
+ Interpreted intent:
1887
+ {intent_info}
1888
+
1889
+ Schema context:
1890
+ {rag_context}
1891
+
1892
+ Below is the validation evidence.
1893
+ """
1894
+
1895
+ resp = llm.invoke(system_prompt + "\n\n" + prompt + "\n\n" + evidence_md)
1896
+
1897
+ parsed = safe_json_load(resp.content)
1898
+
1899
+ if not parsed:
1900
+ decision = {
1901
+ "decision": "correct_sql",
1902
+ "confidence": "low",
1903
+ "reason": "LLM response was not valid JSON"
1904
+ }
1905
+ else:
1906
+ decision = parsed
1907
+
1908
+
1909
+ log_pipeline(
1910
+ "DECISION_LLM_DONE",
1911
+ f"decision={decision.get('decision')} | confidence={decision.get('confidence')} | reason ={decision.get('reason')}"
1912
+ )
1913
+
1914
+ return decision
1915
+
1916
+
1917
+ # %%
1918
+ def explain_validation_with_llm(
1919
+ question: str,
1920
+ feedback: str,
1921
+ original_df: pd.DataFrame,
1922
+ validation_payload: dict,
1923
+ schema_context: str,
1924
+ ) -> str:
1925
+ """
1926
+ Business explanation of validation results.
1927
+ """
1928
+
1929
+ log_pipeline("EXPLAIN_START")
1930
+
1931
+ evidence_md = (
1932
+ "## Pipeline: Feedback --> Validation -> Explanation\n\n"
1933
+ "### Baseline — Original Result\n"
1934
+ )
1935
+ evidence_md += original_df.to_markdown(index=False)
1936
+
1937
+ for i, chk in enumerate(validation_payload.get("context", []), 1):
1938
+ evidence_md += f"\n\n### Context Check {i}: {chk['label']}\n"
1939
+ evidence_md += chk["df"].to_markdown(index=False)
1940
+
1941
+ for i, chk in enumerate(validation_payload.get("equivalence", []), 1):
1942
+ evidence_md += f"\n\n### Verification Check {i}: {chk['label']}\n"
1943
+ evidence_md += chk["df"].to_markdown(index=False)
1944
+
1945
+ system_prompt = """
1946
+ You are a senior data analyst explaining results to a business user.
1947
+
1948
+ Rules:
1949
+ - DO NOT mention SQL mechanics
1950
+ - Compare numbers explicitly
1951
+ - Explain trends year-over-year.
1952
+ - Explain what the actual numbers are and what it means for the business.
1953
+ - If the user is concerned about the SQL or the numbers in their feedback, based on verification and context checks, explain the results to them.
1954
+ """
1955
+
1956
+ prompt = f"""
1957
+ Original question:
1958
+ {question}
1959
+
1960
+ User feedback:
1961
+ {feedback}
1962
+
1963
+ Schema of the data:
1964
+ {schema_context}
1965
+ """
1966
+
1967
+ resp = llm.invoke(system_prompt + "\n\n" + prompt + "\n\n" + evidence_md)
1968
+
1969
+ log_pipeline("EXPLAIN_DONE")
1970
+
1971
+ return resp.content.strip()
1972
+
1973
+
1974
+ # %%
1975
+
1976
+
1977
+ # %%
1978
+
1979
+
1980
+ # %%
1981
+ def feedback_pipeline_interactive(
1982
+ feedback_rating: str,
1983
+ feedback_comment: str,
1984
+ last_sql: str,
1985
+ last_rag_context: str,
1986
+ last_question: str,
1987
+ last_answer_md: str,
1988
+ last_df_state: dict,
1989
+ feedback_sql: str,
1990
+ attempts_left: int,
1991
+ ):
1992
+ """
1993
+ ALWAYS returns EXACTLY 10 values
1994
+ NO booleans
1995
+ followup_signal ∈ {"FOLLOWUP", "NONE"}
1996
+ """
1997
+
1998
+ last_df = state_to_df(last_df_state)
1999
+ rating = (feedback_rating or "").strip().lower()
2000
+ comment = (feedback_comment or "").strip()
2001
+ attempts_left = max(0, int(attempts_left or 0))
2002
+
2003
+ # ---------- INVALID RATING ----------
2004
+ if rating not in {"correct", "wrong"}:
2005
+ return (
2006
+ last_answer_md,
2007
+ last_df,
2008
+ last_sql,
2009
+ last_rag_context,
2010
+ last_question,
2011
+ last_answer_md,
2012
+ df_to_state(last_df),
2013
+ "NONE",
2014
+ "",
2015
+ attempts_left,
2016
+ )
2017
+
2018
+ # ---------- CORRECT ----------
2019
+ if rating == "correct":
2020
+ update_cache_on_feedback(
2021
+ question=last_question,
2022
+ original_doc_md=find_cached_doc_by_sql(
2023
+ last_question, last_sql, get_sql_cache_store()
2024
+ ),
2025
+ user_marked_good=True,
2026
+ llm_corrected_sql=None,
2027
+ llm_corrected_answer_md=None,
2028
+ store=get_sql_cache_store(),
2029
+ )
2030
+
2031
+ md = "✅ **Confirmed correct by user**\n\n" + last_answer_md
2032
+ return (
2033
+ md,
2034
+ last_df,
2035
+ last_sql,
2036
+ last_rag_context,
2037
+ last_question,
2038
+ md,
2039
+ df_to_state(last_df),
2040
+ "NONE",
2041
+ "",
2042
+ attempts_left,
2043
+ )
2044
+
2045
+ # ---------- WRONG ----------
2046
+ attempts_left = max(0, attempts_left - 1)
2047
+
2048
+ if not is_feedback_sufficient(comment):
2049
+ return (
2050
+ last_answer_md,
2051
+ last_df,
2052
+ last_sql,
2053
+ last_rag_context,
2054
+ last_question,
2055
+ last_answer_md,
2056
+ df_to_state(last_df),
2057
+ "FOLLOWUP",
2058
+ build_followup_prompt_for_user(comment),
2059
+ attempts_left,
2060
+ )
2061
+
2062
+ # ---------- VALIDATION ----------
2063
+ intent_info = interpret_feedback_intent(last_question, comment)
2064
+
2065
+ validation = run_validation_queries(
2066
+ intent_info=intent_info,
2067
+ question=last_question,
2068
+ original_sql=last_sql,
2069
+ user_feedback=comment,
2070
+ rag_context=last_rag_context,
2071
+ )
2072
+
2073
+ decision = decide_after_validation_with_llm(
2074
+ question=last_question,
2075
+ original_sql=last_sql,
2076
+ user_feedback=comment,
2077
+ intent_info=intent_info,
2078
+ original_df=last_df,
2079
+ validation_payload=validation,
2080
+ rag_context=last_rag_context,
2081
+ )
2082
+
2083
+ # ---------- EXPLAIN ----------
2084
+ if decision.get("decision") == "correct_sql":
2085
+ explanation = explain_validation_with_llm(
2086
+ question=last_question,
2087
+ feedback=comment,
2088
+ original_df=last_df,
2089
+ validation_payload=validation,
2090
+ schema_context=last_rag_context,
2091
+ )
2092
+
2093
+ return (
2094
+ explanation,
2095
+ last_df,
2096
+ last_sql,
2097
+ last_rag_context,
2098
+ last_question,
2099
+ explanation,
2100
+ df_to_state(last_df),
2101
+ "NONE",
2102
+ "",
2103
+ attempts_left,
2104
+ )
2105
+
2106
+ # ---------- SQL CORRECTION ----------
2107
+ corrected_sql, explanation = review_and_correct_sql_with_llm(
2108
+ question=last_question,
2109
+ generated_sql=last_sql,
2110
+ user_feedback_comment=comment,
2111
+ validation_payload=validation,
2112
+ decision_reason=decision.get("reason", ""),
2113
+ rag_context=last_rag_context,
2114
+ )
2115
+
2116
+ df_new, err = execute_sql(corrected_sql, conn)
2117
+
2118
+ final_md = "**SQL corrected**\n\n" + summarize_results(
2119
+ question=last_question,
2120
+ sql=corrected_sql,
2121
+ df=df_new if not err else None,
2122
+ rag_context=last_rag_context,
2123
+ error=err,
2124
+ )
2125
+
2126
+ return (
2127
+ final_md,
2128
+ df_new if not err else pd.DataFrame(),
2129
+ corrected_sql,
2130
+ last_rag_context,
2131
+ last_question,
2132
+ final_md,
2133
+ df_to_state(df_new if not err else pd.DataFrame()),
2134
+ "NONE",
2135
+ "",
2136
+ attempts_left,
2137
+ )
2138
+
2139
+
2140
+ # %%
2141
+
2142
+
2143
+ # %%
2144
+ import gradio as gr
2145
+
2146
+ # -------------------------------
2147
+ # Helpers
2148
+ # -------------------------------
2149
+ def attempts_text(attempts: int) -> str:
2150
+ if attempts <= 0:
2151
+ return "**Feedback exhausted. Please ask a new question.**"
2152
+ return f"**Feedback attempts remaining: {attempts}**"
2153
+
2154
+
2155
+ # -------------------------------
2156
+ # CHAT TURN
2157
+ # -------------------------------
2158
+ def chat_turn(user_input, history, state):
2159
+ history = history or []
2160
+
2161
+ history.append({"role": "user", "content": user_input})
2162
+ history.append({"role": "assistant", "content": "🔎 Thinking…"})
2163
+
2164
+ (
2165
+ answer_md,
2166
+ _df,
2167
+ sql,
2168
+ rag,
2169
+ q,
2170
+ ans_state,
2171
+ df_state,
2172
+ attempts,
2173
+ attempts_md,
2174
+ debug_md,
2175
+ ) = backend_pipeline(user_input)
2176
+
2177
+ history.pop()
2178
+ history.append({"role": "assistant", "content": answer_md})
2179
+
2180
+ new_state = {
2181
+ "last_sql": sql,
2182
+ "last_rag": rag,
2183
+ "last_question": q,
2184
+ "last_answer": ans_state,
2185
+ "last_df": df_state,
2186
+ "attempts": attempts,
2187
+ }
2188
+
2189
+ return history, new_state, attempts_md, debug_md
2190
+
2191
+
2192
+ # -------------------------------
2193
+ # FEEDBACK TURN
2194
+ # -------------------------------
2195
+ def feedback_turn(feedback_rating, feedback_text, history, state):
2196
+ history = history or []
2197
+
2198
+ # ---------- Attempts exhausted ----------
2199
+ if state["attempts"] <= 0:
2200
+ history.append({
2201
+ "role": "assistant",
2202
+ "content": "Feedback attempts are exhausted. Please ask a new question."
2203
+ })
2204
+ return history, state, attempts_text(0)
2205
+
2206
+ # ---------- BAD without text (consume attempt) ----------
2207
+ if feedback_rating == "wrong" and not (feedback_text or "").strip():
2208
+ new_attempts = max(0, state["attempts"] - 1)
2209
+
2210
+ history.append({
2211
+ "role": "assistant",
2212
+ "content": "Please provide details before submitting negative feedback."
2213
+ })
2214
+
2215
+ new_state = dict(state)
2216
+ new_state["attempts"] = new_attempts
2217
+
2218
+ return history, new_state, attempts_text(new_attempts)
2219
+
2220
+ # ---------- Normal feedback ----------
2221
+ history.append({
2222
+ "role": "user",
2223
+ "content": f"{feedback_rating.upper()} feedback"
2224
+ })
2225
+ history.append({
2226
+ "role": "assistant",
2227
+ "content": "🧪 Validating feedback…"
2228
+ })
2229
+
2230
+ (
2231
+ answer_md,
2232
+ _,
2233
+ sql_new,
2234
+ rag_new,
2235
+ q_new,
2236
+ ans_state,
2237
+ df_state,
2238
+ followup_flag,
2239
+ followup_prompt,
2240
+ attempts_new,
2241
+ ) = feedback_pipeline_interactive(
2242
+ feedback_rating=feedback_rating,
2243
+ feedback_comment=feedback_text,
2244
+ last_sql=state["last_sql"],
2245
+ last_rag_context=state["last_rag"],
2246
+ last_question=state["last_question"],
2247
+ last_answer_md=state["last_answer"],
2248
+ last_df_state=state["last_df"],
2249
+ feedback_sql="",
2250
+ attempts_left=state["attempts"],
2251
+ )
2252
+
2253
+ history.pop()
2254
+
2255
+ history.append({
2256
+ "role": "assistant",
2257
+ "content": followup_prompt if followup_flag == "FOLLOWUP" else answer_md
2258
+ })
2259
+
2260
+ new_state = {
2261
+ "last_sql": sql_new,
2262
+ "last_rag": rag_new,
2263
+ "last_question": q_new,
2264
+ "last_answer": ans_state,
2265
+ "last_df": df_state,
2266
+ "attempts": attempts_new,
2267
+ }
2268
+
2269
+ return history, new_state, attempts_text(attempts_new)
2270
+
2271
+
2272
+ # -------------------------------
2273
+ # UI
2274
+ # -------------------------------
2275
+ with gr.Blocks(analytics_enabled=False) as demo:
2276
+ gr.Markdown("# 🧠 Analytics Assistant Chatbot")
2277
+
2278
+ chat = gr.Chatbot(height=520)
2279
+
2280
+ attempts_md = gr.Markdown(value=attempts_text(4))
2281
+
2282
+ show_debug = gr.Checkbox(label="Show SQL / Cache info", value=False)
2283
+ debug_panel = gr.Markdown(visible=False)
2284
+
2285
+ state = gr.State({
2286
+ "last_sql": "",
2287
+ "last_rag": "",
2288
+ "last_question": "",
2289
+ "last_answer": "",
2290
+ "last_df": {},
2291
+ "attempts": 4,
2292
+ })
2293
+
2294
+ user_input = gr.Textbox(
2295
+ placeholder="Ask a question…",
2296
+ lines=1,
2297
+ show_label=False,
2298
+ )
2299
+
2300
+ feedback_input = gr.Textbox(
2301
+ placeholder="Details (required if result is wrong)…",
2302
+ lines=2,
2303
+ show_label=False,
2304
+ )
2305
+
2306
+ # Buttons (small, right aligned)
2307
+ with gr.Row():
2308
+ gr.Column(scale=6)
2309
+ with gr.Column(scale=2, min_width=110):
2310
+ good_btn = gr.Button("👍 Good", size="sm")
2311
+ with gr.Column(scale=2, min_width=110):
2312
+ bad_btn = gr.Button("👎 Bad", size="sm")
2313
+
2314
+ # Toggle debug panel
2315
+ show_debug.change(
2316
+ lambda show, md: gr.update(value=md, visible=show),
2317
+ inputs=[show_debug, debug_panel],
2318
+ outputs=debug_panel,
2319
+ )
2320
+
2321
+ # Question submit
2322
+ user_input.submit(
2323
+ chat_turn,
2324
+ inputs=[user_input, chat, state],
2325
+ outputs=[chat, state, attempts_md, debug_panel],
2326
+ queue=False,
2327
+ )
2328
+
2329
+ # GOOD feedback
2330
+ good_btn.click(
2331
+ feedback_turn,
2332
+ inputs=[gr.State("correct"), feedback_input, chat, state],
2333
+ outputs=[chat, state, attempts_md],
2334
+ queue=False,
2335
+ )
2336
+
2337
+ # BAD feedback
2338
+ bad_btn.click(
2339
+ feedback_turn,
2340
+ inputs=[gr.State("wrong"), feedback_input, chat, state],
2341
+ outputs=[chat, state, attempts_md],
2342
+ queue=False,
2343
+ )
2344
+
2345
+
2346
+ # %%
2347
+ if __name__ == "__main__":
2348
+ demo.launch()
2349
+
2350
+ # %%
2351
+
2352
+
2353
+
chroma_data/0dc4ec7f-ca6e-471f-98b2-a1ecde7a7a9c/data_level0.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ec427570acc2045faa9e33f1b89b427829972c23df62f550a667a1b3d8879a44
3
+ size 321200
chroma_data/0dc4ec7f-ca6e-471f-98b2-a1ecde7a7a9c/header.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:03cb3ac86f3e5bcb15e88b9bf99f760ec6b33e31d64a699e129b49868db6d733
3
+ size 100
chroma_data/0dc4ec7f-ca6e-471f-98b2-a1ecde7a7a9c/length.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4c0067e7e4324ab80a0473b92555c8b8e18d0383cc233b9f525d8b27408afe46
3
+ size 400
chroma_data/0dc4ec7f-ca6e-471f-98b2-a1ecde7a7a9c/link_lists.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
3
+ size 0
chroma_data/5854ff5a-66bc-4201-8b7e-e10789f5d49b/data_level0.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3c091632ed740d531e335e0f8489951175efdaf91a33f8c62590bb5522c6aa6b
3
+ size 321200
chroma_data/5854ff5a-66bc-4201-8b7e-e10789f5d49b/header.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:03cb3ac86f3e5bcb15e88b9bf99f760ec6b33e31d64a699e129b49868db6d733
3
+ size 100
chroma_data/5854ff5a-66bc-4201-8b7e-e10789f5d49b/length.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d406be09720a4254c0ac8672936ade60cc49c87cecd07777b05be8a7b1c49e63
3
+ size 400
chroma_data/5854ff5a-66bc-4201-8b7e-e10789f5d49b/link_lists.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
3
+ size 0
chroma_data/chroma.sqlite3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b00ef5507d319cefc63198a020ac32d325e1b7b18c6034127a139a597497e956
3
+ size 4485120
data/olist_customers_dataset.csv ADDED
The diff for this file is too large to render. See raw diff
 
data/olist_geolocation_dataset.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b514f6fc991b9566aeba02aa5d67e2c3630f034b60a0e05aa0d082a3b66d88d6
3
+ size 61273883
data/olist_order_items_dataset.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0bc4d068c4fe38cbb01bd90e8746e3c613fe7b4baef75fab7b0e329701c3e279
3
+ size 15438671
data/olist_order_payments_dataset.csv ADDED
The diff for this file is too large to render. See raw diff
 
data/olist_order_reviews_dataset.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:012b61c7593e34f51fa614efdf802b9c7056ce6aae5307ddb93236e7cfc797d7
3
+ size 14451670
data/olist_orders_dataset.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8df58ef3d2d7e9944010f7beecd9b75367f5588ec6e3c91cec19ae3345ef9ecf
3
+ size 17654914
data/olist_products_dataset.csv ADDED
The diff for this file is too large to render. See raw diff
 
data/olist_sellers_dataset.csv ADDED
The diff for this file is too large to render. See raw diff
 
data/product_category_name_translation.csv ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ product_category_name,product_category_name_english
2
+ beleza_saude,health_beauty
3
+ informatica_acessorios,computers_accessories
4
+ automotivo,auto
5
+ cama_mesa_banho,bed_bath_table
6
+ moveis_decoracao,furniture_decor
7
+ esporte_lazer,sports_leisure
8
+ perfumaria,perfumery
9
+ utilidades_domesticas,housewares
10
+ telefonia,telephony
11
+ relogios_presentes,watches_gifts
12
+ alimentos_bebidas,food_drink
13
+ bebes,baby
14
+ papelaria,stationery
15
+ tablets_impressao_imagem,tablets_printing_image
16
+ brinquedos,toys
17
+ telefonia_fixa,fixed_telephony
18
+ ferramentas_jardim,garden_tools
19
+ fashion_bolsas_e_acessorios,fashion_bags_accessories
20
+ eletroportateis,small_appliances
21
+ consoles_games,consoles_games
22
+ audio,audio
23
+ fashion_calcados,fashion_shoes
24
+ cool_stuff,cool_stuff
25
+ malas_acessorios,luggage_accessories
26
+ climatizacao,air_conditioning
27
+ construcao_ferramentas_construcao,construction_tools_construction
28
+ moveis_cozinha_area_de_servico_jantar_e_jardim,kitchen_dining_laundry_garden_furniture
29
+ construcao_ferramentas_jardim,costruction_tools_garden
30
+ fashion_roupa_masculina,fashion_male_clothing
31
+ pet_shop,pet_shop
32
+ moveis_escritorio,office_furniture
33
+ market_place,market_place
34
+ eletronicos,electronics
35
+ eletrodomesticos,home_appliances
36
+ artigos_de_festas,party_supplies
37
+ casa_conforto,home_confort
38
+ construcao_ferramentas_ferramentas,costruction_tools_tools
39
+ agro_industria_e_comercio,agro_industry_and_commerce
40
+ moveis_colchao_e_estofado,furniture_mattress_and_upholstery
41
+ livros_tecnicos,books_technical
42
+ casa_construcao,home_construction
43
+ instrumentos_musicais,musical_instruments
44
+ moveis_sala,furniture_living_room
45
+ construcao_ferramentas_iluminacao,construction_tools_lights
46
+ industria_comercio_e_negocios,industry_commerce_and_business
47
+ alimentos,food
48
+ artes,art
49
+ moveis_quarto,furniture_bedroom
50
+ livros_interesse_geral,books_general_interest
51
+ construcao_ferramentas_seguranca,construction_tools_safety
52
+ fashion_underwear_e_moda_praia,fashion_underwear_beach
53
+ fashion_esporte,fashion_sport
54
+ sinalizacao_e_seguranca,signaling_and_security
55
+ pcs,computers
56
+ artigos_de_natal,christmas_supplies
57
+ fashion_roupa_feminina,fashio_female_clothing
58
+ eletrodomesticos_2,home_appliances_2
59
+ livros_importados,books_imported
60
+ bebidas,drinks
61
+ cine_foto,cine_photo
62
+ la_cuisine,la_cuisine
63
+ musica,music
64
+ casa_conforto_2,home_comfort_2
65
+ portateis_casa_forno_e_cafe,small_appliances_home_oven_and_coffee
66
+ cds_dvds_musicais,cds_dvds_musicals
67
+ dvds_blu_ray,dvds_blu_ray
68
+ flores,flowers
69
+ artes_e_artesanato,arts_and_craftmanship
70
+ fraldas_higiene,diapers_and_hygiene
71
+ fashion_roupa_infanto_juvenil,fashion_childrens_clothes
72
+ seguros_e_servicos,security_and_services
requirements.txt ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core
2
+ pandas==2.2.2
3
+ numpy==1.26.4
4
+ matplotlib==3.9.0
5
+
6
+ # LangChain and Groq
7
+ langchain==0.3.8
8
+ langchain-community==0.3.2
9
+ langchain-groq==0.2.1
10
+
11
+ # Vector Store (Chroma)
12
+ chromadb==0.5.18
13
+
14
+ # Embeddings
15
+ sentence-transformers==3.2.1
16
+
17
+ # UI
18
+ gradio==6.2.0
19
+
20
+ # Support libs
21
+ pydantic==2.9.2
22
+ tabulate==0.9.0
23
+ pyyaml==6.0.2
24
+
25
+ # Optional
26
+ tqdm==4.66.5