diff --git "a/app.py" "b/app.py" deleted file mode 100644--- "a/app.py" +++ /dev/null @@ -1,2731 +0,0 @@ -# %% -import os -import uuid -import sqlite3 -import datetime -import json -import re -import time -from typing import Dict, Any, List, Tuple, Optional -import hashlib - -import pandas as pd -from groq import Groq -from langchain_community.vectorstores import Chroma -from langchain_community.embeddings import HuggingFaceEmbeddings - -# %% -# 0. Global config - - -DB_PATH = "olist.db" -DATA_DIR = "data" - -# Groq Model -GROQ_MODEL_NAME = "llama-3.3-70b-versatile" - -GROQ_API_KEY = os.getenv("GROQ_API_KEY") -if not GROQ_API_KEY: - raise ValueError("GROQ_API_KEY not found.") - -groq_client = Groq(api_key=GROQ_API_KEY) - -# Embedding model -EMBED_MODEL_NAME = "sentence-transformers/all-mpnet-base-v2" - -# Logging paths -PROMPT_LOG_PATH = "prompt_logs.txt" -RUN_LOG_PATH = "run_logs.txt" - -# %% -# 1. Logging helpers - - -def log_prompt(tag: str, prompt: str) -> None: - """ - Append the full prompt to a log file, with a tag and timestamp. - """ - timestamp = datetime.datetime.now().isoformat(timespec="seconds") - header = f"\n\n================ {tag} @ {timestamp} ================\n" - with open(PROMPT_LOG_PATH, "a", encoding="utf-8") as f: - f.write(header) - f.write(prompt) - f.write("\n================ END PROMPT ================\n") - - -def log_run_event(tag: str, content: str) -> None: - """ - Append model response, final SQL, and error info into a run log. - """ - timestamp = datetime.datetime.now().isoformat(timespec="seconds") - header = f"\n\n================ {tag} @ {timestamp} ================\n" - with open(RUN_LOG_PATH, "a", encoding="utf-8") as f: - f.write(header) - f.write(content) - f.write("\n================ END EVENT ================\n") - - - -# %% -# 2. Feedback table + helpers - -def init_feedback_table(conn: sqlite3.Connection) -> None: - """ - Create (or upgrade) a table to capture user feedback on model answers. - """ - conn.execute(""" - CREATE TABLE IF NOT EXISTS user_feedback ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - created_at TEXT NOT NULL, - question TEXT NOT NULL, - generated_sql TEXT, - model_answer TEXT, - rating TEXT CHECK(rating IN ('good','bad')) NOT NULL, - comment TEXT, - corrected_sql TEXT - ) - """) - conn.commit() - - -def record_feedback( - conn: sqlite3.Connection, - question: str, - generated_sql: str, - model_answer: str, - rating: str, # "good" or "bad" - comment: Optional[str] = None, - corrected_sql: Optional[str] = None, -) -> None: - """ - Store user feedback about a particular model answer / SQL query. - If corrected_sql is provided, it is treated as an external correction. - """ - rating = rating.lower() - if rating not in ("good", "bad"): - raise ValueError("rating must be 'good' or 'bad'") - - ts = datetime.datetime.now().isoformat(timespec="seconds") - conn.execute( - """ - INSERT INTO user_feedback ( - created_at, question, generated_sql, model_answer, - rating, comment, corrected_sql - ) - VALUES (?, ?, ?, ?, ?, ?, ?) - """, - (ts, question, generated_sql, model_answer, rating, comment, corrected_sql), - ) - conn.commit() - - -def get_last_feedback_for_question( - conn: sqlite3.Connection, - question: str, -) -> Optional[Dict[str, Any]]: - """ - Return the most recent feedback row for this question (if any). - """ - cur = conn.cursor() - cur.execute( - """ - SELECT created_at, generated_sql, model_answer, - rating, comment, corrected_sql - FROM user_feedback - WHERE question = ? - ORDER BY created_at DESC - LIMIT 1 - """, - (question,), - ) - row = cur.fetchone() - if not row: - return None - - return { - "created_at": row[0], - "generated_sql": row[1], - "model_answer": row[2], - "rating": row[3], - "comment": row[4], - "corrected_sql": row[5], - } - - - -# %% -# 3. Database setup (from CSVs) - -def init_db() -> sqlite3.Connection: - """ - Load all CSVs from the data/ folder into a local SQLite DB. - Table names are derived from file names (without .csv). - """ - conn = sqlite3.connect(DB_PATH, check_same_thread=False) - - csv_files = [ - "olist_customers_dataset.csv", - "olist_orders_dataset.csv", - "olist_order_items_dataset.csv", - "olist_products_dataset.csv", - "olist_order_reviews_dataset.csv", - "olist_order_payments_dataset.csv", - "product_category_name_translation.csv", - "olist_sellers_dataset.csv", - "olist_geolocation_dataset.csv", - ] - - for fname in csv_files: - path = os.path.join(DATA_DIR, fname) - print(path) - if not os.path.exists(path): - print(f"CSV not found: {path} - skipping") - continue - - table_name = os.path.splitext(fname)[0] - print(f"Loading {path} into table {table_name}...") - df = pd.read_csv(path) - df.to_sql(table_name, conn, if_exists="replace", index=False) - - - init_feedback_table(conn) - - return conn - - -conn = init_db() - - - -# %% -# 4. Manual docs for Olist tables - -OLIST_DOCS: Dict[str, Dict[str, Any]] = { - "olist_customers_dataset": { - "description": "Customer master data, one row per customer_id (which can change over time for the same end-user).", - "columns": { - "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.", - "customer_unique_id": "Stable unique identifier for the end-user. A single customer_unique_id can map to multiple customer_id records over time.", - "customer_zip_code_prefix": "Customer ZIP/postal code prefix. Used to join with olist_geolocation_dataset.geolocation_zip_code_prefix.", - "customer_city": "Customer's city as captured at the time of the order or registration.", - "customer_state": "Customer's state (two-letter Brazilian state code, e.g. SP, RJ)." - } - }, - "olist_orders_dataset": { - "description": "Customer orders placed on the Olist marketplace, one row per order.", - "columns": { - "order_id": "Primary key. Unique identifier for each order. Used to join with items, payments, and reviews.", - "customer_id": "Foreign key to olist_customers_dataset.customer_id indicating who placed the order.", - "order_status": "Current lifecycle status of the order (e.g. created, shipped, delivered, canceled, unavailable).", - "order_purchase_timestamp": "Timestamp when the customer completed the purchase (event time for order placement).", - "order_approved_at": "Timestamp when the payment was approved by the system or financial gateway.", - "order_delivered_carrier_date": "Timestamp when the order was handed over by the seller to the carrier/logistics provider.", - "order_delivered_customer_date": "Timestamp when the carrier reported the order as delivered to the final customer.", - "order_estimated_delivery_date": "Estimated delivery date promised to the customer at checkout." - } - }, - "olist_order_items_dataset": { - "description": "Order line items, one row per product per order.", - "columns": { - "order_id": "Foreign key to olist_orders_dataset.order_id. Multiple order_items can belong to the same order.", - "order_item_id": "Sequential item number within an order (1, 2, 3, ...). Uniquely identifies a line inside an order.", - "product_id": "Foreign key to olist_products_dataset.product_id representing the purchased product.", - "seller_id": "Foreign key to olist_sellers_dataset.seller_id representing the seller that fulfilled this item.", - "shipping_limit_date": "Deadline for the seller to hand the item over to the carrier for shipping.", - "price": "Item price paid by the customer for this line (in BRL, not including freight).", - "freight_value": "Freight (shipping) cost attributed to this line item (in BRL)." - } - }, - "olist_products_dataset": { - "description": "Product catalog with physical and category attributes, one row per product.", - "columns": { - "product_id": "Primary key. Unique identifier for each product. Used to join with olist_order_items_dataset.product_id.", - "product_category_name": "Product category name in Portuguese. Join to product_category_name_translation.product_category_name for English.", - "product_name_lenght": "Number of characters in the product name (field name misspelled as 'lenght' in the original dataset).", - "product_description_lenght": "Number of characters in the product description (also misspelled as 'lenght').", - "product_photos_qty": "Number of product images associated with the listing.", - "product_weight_g": "Product weight in grams.", - "product_length_cm": "Product length in centimeters (package dimension).", - "product_height_cm": "Product height in centimeters (package dimension).", - "product_width_cm": "Product width in centimeters (package dimension)." - } - }, - "olist_order_reviews_dataset": { - "description": "Post-purchase customer reviews and satisfaction scores, one row per review.", - "columns": { - "review_id": "Primary key. Unique identifier for each review record.", - "order_id": "Foreign key to olist_orders_dataset.order_id for the reviewed order.", - "review_score": "Star rating given by the customer on a 1–5 scale (5 = very satisfied, 1 = very dissatisfied).", - "review_comment_title": "Optional short text title or summary of the review.", - "review_comment_message": "Optional detailed free-text comment describing the customer experience.", - "review_creation_date": "Date when the customer created the review.", - "review_answer_timestamp": "Timestamp when Olist or the seller responded to the review (if applicable)." - } - }, - "olist_order_payments_dataset": { - "description": "Payments associated with orders, one row per payment record (order can have multiple payments).", - "columns": { - "order_id": "Foreign key to olist_orders_dataset.order_id.", - "payment_sequential": "Sequence number for multiple payments of the same order (1 for first payment, 2 for second, etc.).", - "payment_type": "Payment method used (e.g. credit_card, boleto, voucher, debit_card).", - "payment_installments": "Number of installments chosen by the customer for this payment.", - "payment_value": "Monetary amount paid in this payment record (in BRL)." - } - }, - "product_category_name_translation": { - "description": "Lookup table mapping Portuguese product category names to English equivalents.", - "columns": { - "product_category_name": "Product category name in Portuguese as used in olist_products_dataset.", - "product_category_name_english": "Translated product category name in English." - } - }, - "olist_sellers_dataset": { - "description": "Seller master data, one row per seller operating on the Olist marketplace.", - "columns": { - "seller_id": "Primary key. Unique identifier for each seller. Used to join with olist_order_items_dataset.seller_id.", - "seller_zip_code_prefix": "Seller ZIP/postal code prefix, used to join with olist_geolocation_dataset.geolocation_zip_code_prefix.", - "seller_city": "City where the seller is located.", - "seller_state": "State where the seller is located (two-letter Brazilian state code)." - } - }, - "olist_geolocation_dataset": { - "description": "Geolocation reference data for ZIP code prefixes in Brazil, not unique per prefix.", - "columns": { - "geolocation_zip_code_prefix": "ZIP/postal code prefix, used to link customers and sellers via zip code.", - "geolocation_lat": "Latitude coordinate of the location.", - "geolocation_lng": "Longitude coordinate of the location.", - "geolocation_city": "City name for the location.", - "geolocation_state": "State code for the location (two-letter Brazilian state code)." - } - } -} - - - -# %% -# 5. Schema extractor + metadata YAML - -def extract_schema_metadata(connection: sqlite3.Connection) -> Dict[str, Any]: - """ - Introspect SQLite tables, columns and foreign key relationships. - """ - cursor = connection.cursor() - cursor.execute("SELECT name FROM sqlite_master WHERE type='table'") - tables = [row[0] for row in cursor.fetchall()] - - metadata: Dict[str, Any] = {"tables": {}} - - for table in tables: - cursor.execute(f"PRAGMA table_info('{table}')") - cols = cursor.fetchall() - - # Manual docs for the table - table_docs = OLIST_DOCS.get(table, {}) - table_desc: str = table_docs.get( - "description", - f"Table '{table}' from Olist dataset." - ) - column_docs: Dict[str, str] = table_docs.get("columns", {}) - - columns_meta: Dict[str, str] = {} - for c in cols: - col_name = c[1] - col_type = c[2] or "TEXT" - - if col_name in column_docs: - columns_meta[col_name] = column_docs[col_name] - else: - columns_meta[col_name] = f"Column '{col_name}' of type {col_type}" - - cursor.execute(f"PRAGMA foreign_key_list('{table}')") - fk_rows = cursor.fetchall() - relationships: List[str] = [] - for fk in fk_rows: - ref_table = fk[2] - from_col = fk[3] - to_col = fk[4] - relationships.append( - f"{table}.{from_col} → {ref_table}.{to_col} (foreign key)" - ) - - metadata["tables"][table] = { - "description": table_desc, - "columns": columns_meta, - "relationships": relationships, - } - - return metadata - - -schema_metadata = extract_schema_metadata(conn) - - -def build_schema_yaml(metadata: Dict[str, Any]) -> str: - """ - Render metadata dict into a YAML-style string. - """ - lines: List[str] = ["tables:"] - for tname, tinfo in metadata["tables"].items(): - lines.append(f" {tname}:") - desc = tinfo.get("description", "").replace('"', "'") - lines.append(f' description: "{desc}"') - lines.append(" columns:") - for col_name, col_desc in tinfo.get("columns", {}).items(): - col_desc_clean = col_desc.replace('"', "'") - lines.append(f' {col_name}: "{col_desc_clean}"') - rels = tinfo.get("relationships", []) - if rels: - lines.append(" relationships:") - for rel in rels: - rel_clean = rel.replace('"', "'") - lines.append(f' - "{rel_clean}"') - return "\n".join(lines) - - -schema_yaml = build_schema_yaml(schema_metadata) - - - -# %% -# 6. Build schema documents for RAG (taking samples from the table) - -def build_schema_documents( - connection: sqlite3.Connection, - schema_metadata: Dict[str, Any], - sample_rows: int = 5, -) -> Tuple[List[str], List[Dict[str, Any]]]: - """ - Build one rich RAG document per table, using schema_metadata. - - Each document includes: - - Table name - - Table description - - Columns with type + description - - Relationships (FKs) - - A few sample rows - """ - cursor = connection.cursor() - cursor.execute("SELECT name FROM sqlite_master WHERE type='table'") - tables = [row[0] for row in cursor.fetchall()] - - docs: List[str] = [] - metadatas: List[Dict[str, Any]] = [] - - for table in tables: - tmeta = schema_metadata["tables"][table] - table_desc = tmeta.get("description", "") - columns_meta = tmeta.get("columns", {}) - relationships = tmeta.get("relationships", []) - - # Use PRAGMA to get types, then enrich with descriptions - cursor.execute(f"PRAGMA table_info('{table}')") - cols = cursor.fetchall() - - col_lines = [] - for c in cols: - col_name = c[1] - col_type = c[2] or "TEXT" - col_desc = columns_meta.get(col_name, f"Column '{col_name}' of type {col_type}") - col_lines.append(f"- {col_name} ({col_type}): {col_desc}") - - # Sample rows - try: - sample_df = pd.read_sql_query( - f"SELECT * FROM '{table}' LIMIT {sample_rows}", - connection, - ) - sample_text = sample_df.to_markdown(index=False) - except Exception: - sample_text = "(could not fetch sample rows)" - - # Relationships block - rel_block = "" - if relationships: - rel_block = "Relationships:\n" + "\n".join( - f"- {rel}" for rel in relationships - ) + "\n" - - doc_text = ( - f"Table: {table}\n" - f"Description: {table_desc}\n\n" - f"Columns:\n" + "\n".join(col_lines) + "\n\n" - f"{rel_block}\n" - f"Example rows:\n{sample_text}\n" - ) - - docs.append(doc_text) - metadatas.append({ - "doc_type": "table_schema", - "table_name": table, - }) - - return docs, metadatas - - -# Build RAG texts + metadata -schema_docs, schema_doc_metas = build_schema_documents(conn, schema_metadata) - -RAG_TEXTS: List[str] = [] -RAG_METADATAS: List[Dict[str, Any]] = [] - -# 1) Per-table docs -RAG_TEXTS.extend(schema_docs) -RAG_METADATAS.extend(schema_doc_metas) - -# 2) Global YAML as a separate doc -RAG_TEXTS.append("SCHEMA_METADATA_YAML:\n" + schema_yaml) -RAG_METADATAS.append({"doc_type": "global_schema"}) - - -# %% -# 7. Build Chroma store + global RAG retriever - -def build_store_final() -> Tuple[Chroma, Any]: - """ - Build the production RAG store with fixed embedding model. - """ - embedding_model = HuggingFaceEmbeddings(model_name=EMBED_MODEL_NAME) - - collection_name = f"olist_schema_all_mpnet_{uuid.uuid4().hex[:8]}" - - store = Chroma.from_texts( - RAG_TEXTS, - embedding_model, - metadatas=RAG_METADATAS, - collection_name=collection_name, - persist_directory=None, # in-memory - ) - - retriever = store.as_retriever( - search_kwargs={ - "k": 3, - "filter": {"doc_type": "table_schema"}, - } - ) - - return store, retriever - -rag_store, rag_retriever = build_store_final() - - -# %% -# 7b. SQL cache vector store (question --> SQL + answer_md) - -SQL_CACHE_COLLECTION = "sql_cache_mpnet" -SQL_CACHE_PERSIST_DIR = "sql_cache_chroma" # directory on disk for cached SQL - -sql_cache_store: Optional[Chroma] = None - -def get_sql_cache_store() -> Chroma: - """ - Return a Chroma store dedicated to caching - confirmed-good (question, sql, answer_md) triples. - """ - global sql_cache_store - - if sql_cache_store is not None: - return sql_cache_store - - embedding_model = HuggingFaceEmbeddings(model_name=EMBED_MODEL_NAME) - - # This will create the collection the first time, and reload it on later runs - sql_cache_store = Chroma( - collection_name=SQL_CACHE_COLLECTION, - embedding_function=embedding_model, - persist_directory=SQL_CACHE_PERSIST_DIR, - ) - return sql_cache_store - - - -# %% -def sanitize_metadata_for_chroma(metadata: dict) -> dict: - """ - Ensure metadata values are simple primitives (str/int/float/bool). - - None -> "" (empty string) - - bool/int/float left as-is - - other types -> str(value) - Returns a shallow-copied dict safe for Chroma metadata. - """ - if not isinstance(metadata, dict): - return {} - - safe = {} - for k, v in metadata.items(): - # skip keys that are None or empty key - if k is None: - continue - # Primitives allowed: str, int, float, bool - if v is None: - safe[k] = "" - elif isinstance(v, (str, int, float, bool)): - safe[k] = v - else: - # convert lists/dicts/objects to string representation - try: - safe[k] = str(v) - except Exception: - safe[k] = "" - return safe - - -# %% -# Helper: normalize question - -def normalize_question_text(q: str) -> str: - if not q: - return "" - q = q.strip().lower() - q = re.sub(r"[^\w\s]", " ", q) - q = re.sub(r"\s+", " ", q).strip() - return q - -# Helper: compute success rate -def compute_success_rate(md: dict) -> float: - sc = md.get("success_count", 0) or 0 - tf = md.get("total_feedbacks", 0) or 0 - if tf <= 0: - return 0.0 - return float(sc) / float(tf) - -# Insert initial cache entry (no feedback yet) -def cache_sql_answer_initial(question: str, sql: str, answer_md: str, store=None, extra_metadata: dict = None): - """ - Insert a cached entry when you run a query and want to cache it regardless of feedback. - initial metrics: views=1, success_count=0, total_feedbacks=0, success_rate=0.0 - """ - if store is None: - store = get_sql_cache_store() - - ident = uuid.uuid4().hex - norm = normalize_question_text(question) - md = { - "id": ident, - "normalized_question": norm, - "sql": sql, - "answer_md": answer_md, - "saved_at": time.time(), - "views": 1, - "success_count": 0, - "total_feedbacks": 0, - "success_rate": 0.0, - } - if extra_metadata: - md.update(extra_metadata) - - # Use your store's API; typical Chroma-like: - store.add_texts([question], metadatas=[md]) - return ident - - -# Find existing canonical doc by normalized question (small neighborhood) - -def find_existing_by_normalized(question: str, store=None, k=4): - if store is None: - store = get_sql_cache_store() - norm = normalize_question_text(question) - try: - results = store.similarity_search_with_score(question, k=k) - except Exception: - return [] # fallback empty - matches = [] - for doc, dist in results: - doc_text = doc.page_content or "" - doc_norm = normalize_question_text(doc_text) - if doc_norm == norm: - md = doc.metadata or {} - matches.append((doc, float(dist), md)) - return matches # list of (doc, dist, metadata) - - -# %% -import time -import logging -from typing import Optional, List, Dict, Any -from difflib import SequenceMatcher - -_logger = logging.getLogger(__name__) - -# ------------------------------------------------------------------------- -# Utility helpers -# ------------------------------------------------------------------------- - -def _now_ts() -> float: - return time.time() - -def similarity_score(a: str, b: str) -> float: - return SequenceMatcher(None, (a or ""), (b or "")).ratio() - -# ------------------------------------------------------------------------- -# Persist helper — MUST BE defined before any caching functions call it -# ------------------------------------------------------------------------- - -def _maybe_persist_store(store): - """ - Try to persist Chroma / LangChain store using the APIs available. - Returns True if succeed, False otherwise. - """ - try: - # Chroma via LangChain wrapper - if hasattr(store, "persist"): - store.persist() - return True - - # Direct collection object - coll = getattr(store, "_collection", None) - if coll is not None: - if hasattr(coll, "persist"): - coll.persist() - return True - if hasattr(coll, "flush"): - coll.flush() - return True - - # Chroma client fallback - if hasattr(store, "client") and hasattr(store.client, "persist"): - store.client.persist() - return True - - except Exception as e: - _logger.warning(f"Persist failed: {e}") - - return False - -# ------------------------------------------------------------------------- -# Cache insert / update -# ------------------------------------------------------------------------- - -def cache_sql_answer_dedup( - question: str, - sql: str, - answer_md: str, - metadata: Optional[dict] = None, - store=None, -) -> Dict[str, Any]: - """ - Upsert or append a cached (question, sql, answer_md) into the vector store. - Uses deterministic cache_id to avoid duplicates (passed as `ids` where supported). - """ - if store is None: - store = get_sql_cache_store() - - meta = dict(metadata or {}) - meta.setdefault("good_count", int(meta.get("good_count", 0))) - meta.setdefault("bad_count", int(meta.get("bad_count", 0))) - meta.setdefault("total_feedbacks", int(meta.get("total_feedbacks", meta.get("good_count", 0) + meta.get("bad_count", 0)))) - if meta["total_feedbacks"] > 0: - meta.setdefault("success_rate", float(meta.get("success_rate", meta.get("good_count", 0) / meta["total_feedbacks"]))) - else: - meta.setdefault("success_rate", float(meta.get("success_rate", 1.0))) - meta.setdefault("views", int(meta.get("views", 0))) - meta.setdefault("saved_at", meta.get("saved_at", _now_ts())) - - cache_id = generate_cache_id(question, sql) - metadata_to_store = {"sql": sql, "answer_md": answer_md, "cache_id": cache_id, **meta} - - safe_metadata = sanitize_metadata_for_chroma(metadata_to_store) - payload = {"question": question, "sql": sql, "answer_md": answer_md, "metadata": meta} - - try: - # LangChain-Chroma wrapper supports ids param for add_texts - if hasattr(store, "add_texts"): - # Try to provide ids argument if supported - try: - store.add_texts([question], metadatas=[safe_metadata], ids=[cache_id]) - except TypeError: - # older wrappers may not accept ids — fall back to add_texts (will duplicate but we included cache_id in metadata) - store.add_texts([question], metadatas=[safe_metadata]) - _maybe_persist_store(store) - return payload - - # Raw collection access - coll = getattr(store, "_collection", None) - if coll is not None: - # When using raw chroma collection, use add with ids if supported - if hasattr(coll, "add"): - try: - coll.add(ids=[cache_id], documents=[question], metadatas=[safe_metadata]) - except TypeError: - # some coll.add variants accept different signature - coll.add(documents=[question], metadatas=[safe_metadata]) - _maybe_persist_store(store) - return payload - - # Fallback: add_documents (LangChain Document) - if hasattr(store, "add_documents"): - from langchain.schema import Document - doc = Document(page_content=question, metadata=safe_metadata) - store.add_documents([doc]) - _maybe_persist_store(store) - return payload - - except Exception as e: - _logger.exception("cache_sql_answer_dedup: failed to write to store: %s", e) - raise - - raise RuntimeError("cache_sql_answer_dedup: unsupported vector store API") - - -# ------------------------------------------------------------------------- -# Find exact cached entry (question + SQL) -# ------------------------------------------------------------------------- - -def find_cached_doc_by_sql(question: str, sql: str, store=None) -> Optional[Dict[str, Any]]: - """ - Find a cached document matching question + sql. Returns a dict including 'id' (cache_id) - """ - if store is None: - store = get_sql_cache_store() - cache_id = generate_cache_id(question, sql) - try: - # best-effort: search for exact cache_id in stored metadatas - coll = getattr(store, "_collection", None) - if coll is not None and hasattr(coll, "get"): - raw = coll.get(ids=[cache_id]) if hasattr(coll, "get") else None - # coll.get(ids=[...]) may return a structure; try to read metadatas - try: - # some Chroma versions accept get(ids=[...]) and return metadatas/documents - if raw: - # Try to inspect returned documents/metadatas - docs = raw.get("documents", []) - metas = raw.get("metadatas", []) - if metas: - md = metas[0] if metas else {} - doc_text = docs[0] if docs else question - return {"id": cache_id, "question": doc_text, "sql": md.get("sql"), "answer_md": md.get("answer_md"), "metadata": md} - except Exception: - pass - - # fallback: similarity search and match exact sql - if hasattr(store, "similarity_search_with_score"): - results = store.similarity_search_with_score(question, k=10) - for doc, score in results: - md = doc.metadata or {} - if (md.get("sql") or "").strip() == (sql or "").strip(): - # determine id: prefer md.cache_id if present, else None - doc_id = md.get("cache_id") or md.get("id") or getattr(doc, "id", None) - md["cache_id"] = md.get("cache_id", doc_id) - return {"id": doc_id, "question": doc.page_content, "sql": md.get("sql"), "answer_md": md.get("answer_md"), "metadata": md} - except Exception as e: - _logger.exception("find_cached_doc_by_sql error: %s", e) - return None - - -# ------------------------------------------------------------------------- -# Retrieve cached answers ranked primarily by success rate -# ------------------------------------------------------------------------- - -import re -import unicodedata - -def normalize_text(s: str) -> str: - """ - Lowercase, strip accents, remove punctuation (simple), collapse spaces. - This helps make stored question text and user queries more comparable. - """ - if not s: - return "" - # normalize unicode, lowercase - s2 = unicodedata.normalize("NFKD", s).encode("ascii", "ignore").decode("ascii", "ignore") - s2 = s2.lower() - # replace punctuation with space - s2 = re.sub(r"[^\w\s]", " ", s2) - # collapse whitespace - s2 = re.sub(r"\s+", " ", s2).strip() - return s2 - -def generate_cache_id(question: str, sql: str) -> str: - """ - Deterministic cache id used for Chroma document id. - Uses normalized question + sql to avoid duplicates for same logic. - """ - q = normalize_text(question or "") - s = (sql or "").strip() - key = (q + "||" + s).encode("utf-8") - return hashlib.sha1(key).hexdigest() - - -def retrieve_cached_sql_answers_ranked( - question: str, - k: int = 5, - max_distance: float = 0.25, - store=None, - allow_fallback: bool = True, -) -> List[Dict[str, Any]]: - """ - Improved retrieval: - - normalize the question and try similarity search - - if no candidate within max_distance, and allow_fallback==True: - return top-k raw candidates (no distance filter) so UI can still show matches - Returns list of dicts: {sql, answer_md, distance, matched_question, metadata} - """ - if store is None: - store = get_sql_cache_store() - - q_norm = normalize_text(question) - candidates: List[Dict[str, Any]] = [] - - def _collect_results(raw_results): - out = [] - for doc, score in raw_results: - # Try to interpret score: if it's in [ -1 .. 1 ], we'll treat as similarity; else fallback treat as distance - try: - sc = float(score) - except Exception: - sc = None - - # heuristics: - # - if sc is None -> use large distance - # - if sc between -1 and 1 -> consider as similarity (cosine-ish) -> distance = 1 - sc - # - else treat sc as a distance already - if sc is None: - distance = 1.0 - else: - if -1.0 <= sc <= 1.0: - distance = max(0.0, 1.0 - sc) - else: - distance = float(sc) - - md = doc.metadata or {} - meta = dict(md) - meta.setdefault("good_count", int(meta.get("good_count", 0))) - meta.setdefault("bad_count", int(meta.get("bad_count", 0))) - meta.setdefault("total_feedbacks", int(meta.get("total_feedbacks", meta.get("good_count", 0) + meta.get("bad_count", 0)))) - meta.setdefault("success_rate", float(meta.get("success_rate", 1.0 if meta.get("total_feedbacks", 0) == 0 else meta.get("success_rate", 1.0)))) - meta.setdefault("views", int(meta.get("views", 0))) - meta.setdefault("saved_at", meta.get("saved_at", _now_ts())) - - out.append({ - "sql": md.get("sql"), - "answer_md": md.get("answer_md"), - "distance": distance, - "matched_question": doc.page_content, - "metadata": meta, - }) - return out - - try: - # Try normalized query first (if normalization changed anything) - raw = None - if q_norm and q_norm != (question or ""): - try: - raw = store.similarity_search_with_score(q_norm, k=max(k, 10)) - except Exception: - raw = None - - if not raw: - # fallback to original question text - try: - raw = store.similarity_search_with_score(question, k=max(k, 10)) - except Exception: - raw = None - - if raw: - candidates = _collect_results(raw) - except Exception as e: - _logger.exception("retrieve_cached_sql_answers_ranked: vector search failed: %s", e) - candidates = [] - - # Sort candidates by (success_rate desc, distance asc) - candidates.sort(key=lambda c: (-float(c.get("metadata", {}).get("success_rate", 1.0)), float(c.get("distance", 1.0)))) - - # Filter by distance first (strict behavior) - filtered = [c for c in candidates if c.get("distance", 1.0) <= max_distance] - - if filtered: - return filtered[:k] - - # If no candidate passed the strict filter: - if allow_fallback: - # Return top-k raw candidates (so UI shows matches even if distance is high) - return candidates[:k] - else: - return [] - - - -# ------------------------------------------------------------------------- -# Increment views -# ------------------------------------------------------------------------- - -def increment_cache_views(metadata: dict, store=None) -> bool: - """ - Increment 'views' for a matched cached entry. Uses cache_id if available. - Best-effort; if cache_id missing, tries to locate by sql and add a new doc with same cache_id. - """ - if not metadata: - return False - if store is None: - store = get_sql_cache_store() - - sql = metadata.get("sql") - cache_id = metadata.get("cache_id") or metadata.get("id") or (generate_cache_id(metadata.get("question",""), sql) if sql else None) - if not cache_id: - return False - - try: - coll = getattr(store, "_collection", None) - # Build new metadata (increase views) - new_md = dict(metadata) - new_md["views"] = int(new_md.get("views", 0)) + 1 - - # sanitize new metadata - safe_metadata = sanitize_metadata_for_chroma({"sql": sql, "answer_md": new_md.get("answer_md", ""), **new_md, "cache_id": cache_id}) - - # Preferred: use raw collection.update (if present) - if coll is not None and hasattr(coll, "update"): - # coll.update expects ids and metadatas - try: - coll.update(ids=[cache_id], metadatas=[safe_metadata]) - _maybe_persist_store(store) - return True - except Exception: - # if update failed, fallback to add_texts with id (to avoid total duplication) - pass - - # Fallback: add_texts with ids (LangChain wrapper) - if hasattr(store, "add_texts"): - try: - store.add_texts([metadata.get("question") or ""], metadatas=[safe_metadata], ids=[cache_id]) - _maybe_persist_store(store) - return True - except TypeError: - # older wrapper, try without ids (will duplicate) - store.add_texts([metadata.get("question") or ""], metadatas=[safe_metadata]) - _maybe_persist_store(store) - return True - - except Exception as e: - _logger.exception("increment_cache_views error: %s", e) - return False - - - - - -# Update metrics on feedback - -def update_cache_on_feedback( - question: str, - original_doc_md: Optional[Dict[str, Any]], - user_marked_good: bool, - llm_corrected_sql: Optional[str], - llm_corrected_answer_md: Optional[str], - store=None, -) -> None: - """ - Update cache entries after user feedback. - - Update original doc metadata by cache_id when possible. - - Insert corrected SQL as a new doc with deterministic cache_id if provided. - """ - if store is None: - store = get_sql_cache_store() - - try: - # Determine original doc and its cache_id - if original_doc_md: - md = dict(original_doc_md.get("metadata", {}) or {}) - cache_id = md.get("cache_id") or md.get("id") or original_doc_md.get("id") or generate_cache_id(original_doc_md.get("question") or question, md.get("sql") or "") - # update counters - if user_marked_good: - md["good_count"] = int(md.get("good_count", 0)) + 1 - else: - md["bad_count"] = int(md.get("bad_count", 0)) + 1 - md["total_feedbacks"] = int(md.get("total_feedbacks", 0)) + 1 - md["success_rate"] = float(md.get("good_count", 0)) / float(md["total_feedbacks"]) if md["total_feedbacks"] > 0 else 1.0 - md["saved_at"] = md.get("saved_at", _now_ts()) - md.setdefault("views", int(md.get("views", 0))) - md["cache_id"] = cache_id - - safe_metadata = sanitize_metadata_for_chroma({"sql": md.get("sql"), "answer_md": md.get("answer_md",""), **md}) - - coll = getattr(store, "_collection", None) - # Try to update by id - if coll is not None and hasattr(coll, "update"): - try: - coll.update(ids=[cache_id], metadatas=[safe_metadata]) - _maybe_persist_store(store) - except Exception: - # fallback add with id if update fails - try: - if hasattr(store, "add_texts"): - store.add_texts([original_doc_md.get("question") or question], metadatas=[safe_metadata], ids=[cache_id]) - _maybe_persist_store(store) - except Exception: - _logger.exception("update_cache_on_feedback: fallback add_texts failed") - else: - # langchain wrapper - try: - if hasattr(store, "add_texts"): - store.add_texts([original_doc_md.get("question") or question], metadatas=[safe_metadata], ids=[cache_id]) - _maybe_persist_store(store) - except Exception: - _logger.exception("update_cache_on_feedback: add_texts failed") - else: - # no original doc: find best candidate and bump - candidates = retrieve_cached_sql_answers_ranked(question, k=5, max_distance=0.25, store=store) - if candidates: - top = candidates[0] - md = dict(top.get("metadata", {})) - cache_id = md.get("cache_id") or generate_cache_id(top.get("matched_question") or question, top.get("sql") or "") - if user_marked_good: - md["good_count"] = int(md.get("good_count", 0)) + 1 - else: - md["bad_count"] = int(md.get("bad_count", 0)) + 1 - md["total_feedbacks"] = int(md.get("total_feedbacks", 0)) + 1 - md["success_rate"] = float(md.get("good_count", 0)) / float(md["total_feedbacks"]) if md["total_feedbacks"] > 0 else 1.0 - md["cache_id"] = cache_id - safe_metadata = sanitize_metadata_for_chroma({"sql": top.get("sql"), "answer_md": top.get("answer_md",""), **md}) - try: - if hasattr(store, "add_texts"): - store.add_texts([top.get("matched_question")], metadatas=[safe_metadata], ids=[cache_id]) - _maybe_persist_store(store) - except Exception: - _logger.exception("update_cache_on_feedback: fallback add_texts failed.") - except Exception: - _logger.exception("update_cache_on_feedback failed overall.") - - # If there is a corrected SQL, insert as new deterministic entry (cache_id derived from corrected sql) - if llm_corrected_sql and llm_corrected_answer_md: - new_cache_id = generate_cache_id(question, llm_corrected_sql) - new_meta = { - "good_count": 1, - "bad_count": 0, - "total_feedbacks": 1, - "success_rate": 1.0, - "views": 1, - "saved_at": _now_ts(), - "cache_id": new_cache_id, - } - try: - cache_sql_answer_dedup(question, llm_corrected_sql, llm_corrected_answer_md, metadata=new_meta, store=store) - except Exception: - _logger.exception("update_cache_on_feedback: failed to cache corrected SQL.") - - - -# %% -# ### 8. Groq LLM via LangChain - -from langchain_groq import ChatGroq -import re -import gradio as gr - -llm = ChatGroq(model=GROQ_MODEL_NAME, groq_api_key=GROQ_API_KEY) - - -# %% -def get_rag_context(question: str) -> str: - """ - Retrieve the most relevant schema documents for the question. - """ - docs = rag_retriever.invoke(question) - return "\n\n---\n\n".join(d.page_content for d in docs) - -def clean_sql(sql: str) -> str: - sql = sql.strip() - if "```" in sql: - sql = sql.replace("```sql", "").replace("```", "").strip() - return sql - -def extract_sql_from_markdown(text: str) -> str: - """ - Extract the first ```sql ... ``` block from LLM output. - If not found, return the whole text. - """ - match = re.search(r"```sql(.*?)```", text, flags=re.DOTALL | re.IGNORECASE) - if match: - return match.group(1).strip() - return text.strip() - -def extract_explanation_after_marker(text: str, marker: str = "EXPLANATION:") -> str: - """ - After the given marker, return the rest of the text as explanation. - """ - idx = text.upper().find(marker.upper()) - if idx == -1: - return text.strip() - return text[idx + len(marker):].strip() - -# 6b. General / descriptive questions - -GENERAL_DESC_KEYWORDS = [ - "what is this dataset about", - "what is this data about", - "describe this dataset", - "describe the dataset", - "dataset overview", - "data overview", - "summary of the dataset", - "explain this dataset", -] - - -def is_general_question(question: str) -> bool: - """ - Detect high-level descriptive questions where we should answer - directly from schema context instead of generating SQL. - """ - q = question.lower().strip() - return any(key in q for key in GENERAL_DESC_KEYWORDS) - - -def answer_general_question(question: str) -> str: - """ - Use the RAG schema docs to generate a rich, high-level description - of the Olist dataset for conceptual questions. - """ - rag_context = get_rag_context(question) - - system_instructions = """ -You are a data documentation expert. - -You will be given: -- Schema documentation for the Olist dataset (tables, descriptions, columns, relationships). -- A high-level user question like "what is this dataset about?". - -Your job: -- Write a clear, structured overview of the dataset. -- Explain the main entities (customers, orders, items, products, sellers, payments, reviews, geolocation). -- Mention typical analysis use-cases (delivery performance, customer behavior, seller performance, product/category analysis, etc.). -- Target a data analyst seeing the dataset for the first time. - -Do NOT write SQL. Answer in Markdown. -""" - - prompt = ( - system_instructions - + "\n\n=== SCHEMA CONTEXT ===\n" - + rag_context - + "\n\n=== USER QUESTION ===\n" - + question - + "\n\nDetailed dataset overview:" - ) - - log_prompt("GENERAL_DATASET_QUESTION", prompt) - - response = llm.invoke(prompt) - log_run_event("RAW_MODEL_RESPONSE_GENERAL_DATASET", response.content) - - return response.content.strip() - - -# %% -# ### 9. SQL execution / validation - -def execute_sql(sql: str, connection: sqlite3.Connection) -> Tuple[Optional[pd.DataFrame], Optional[str]]: - """ - Execute SQL on SQLite and return a DataFrame, else return an error. - """ - try: - df = pd.read_sql_query(sql, connection) - return df, None - except Exception as e: - return None, str(e) - -def validate_sql(sql: str, connection: sqlite3.Connection) -> Tuple[bool, Optional[str]]: - """ - Basic SQL validator: - - Uses EXPLAIN QUERY PLAN to detect syntax or schema issues. - """ - try: - cursor = connection.cursor() - cursor.execute(f"EXPLAIN QUERY PLAN {sql}") - return True, None - except Exception as e: - return False, str(e) - -# %% -# ### 10. SQL Generation + Repair with LLM (feedback-aware) - -def build_sql_review_prompt( - question: str, - generated_sql: str, - user_feedback_comment: str, - rag_context: str, -) -> str: - """ - Prompt to let the LLM compare its SQL with the user's feedback, - decide if the join/logic is wrong, and produce a corrected SQL + explanation. - - We explicitly allow the model to say: - - "query was already correct, user mistaken" OR - - "query was wrong, here is the fix". - """ - prompt = f""" -You previously generated the following SQL for a SQLite database: - -```sql -{generated_sql} - -The user now says this query is WRONG and provided this feedback: -"{user_feedback_comment}" - -TASKS: - - Compare the SQL with the database schema (given in the context) and the user's feedback. - - Decide whether the query is actually correct or incorrect. - Make sure that the user clearly specifies why they think it is incorrect. - It can be if they are unsatisfied with the numbers, or the logic is incorrect, or SQL is invalid etc. - If any reason is not clearly specified, return the previous result as it is. - - If it is already correct, keep it unchanged and explain why the user might be mistaken. - - If it is incorrect (e.g., wrong joins, missing filters, wrong aggregation), fix it. - - Produce a corrected SQL query that better answers the question. - - If the original query is already correct, just repeat the same SQL. - - Explain in a few sentences WHO is correct (you or the user) and WHY. - -DATABASE SCHEMA (partial, from RAG): -{rag_context} - -User question: -{question} - -Return your answer in this format: - -CORRECTED_SQL: - --- your (possibly unchanged) SQL here -SELECT ... - -EXPLANATION: -Your explanation here, clearly stating whether: - - the original query was correct or not, and - - how your corrected SQL addresses the issue (or why it didn't need changes). - """ - return prompt.strip() - - -# %% -# Review and Correct SQL based on Feedback - -def review_and_correct_sql_with_llm( - question: str, - generated_sql: str, - user_feedback_comment: str, - rag_context: str, -) -> Tuple[str, str]: - """ - Ask the LLM to compare its SQL with user's feedback, decide what is wrong (or not), - and propose a corrected SQL (possibly unchanged) + explanation. - - Returns: - corrected_sql, explanation - """ - prompt = build_sql_review_prompt( - question=question, - generated_sql=generated_sql, - user_feedback_comment=user_feedback_comment, - rag_context=rag_context, - ) - - log_prompt("SQL_REVIEW_FEEDBACK", prompt) - response = llm.invoke(prompt) - log_run_event("RAW_MODEL_RESPONSE_SQL_REVIEW", response.content) - - # Try to extract SQL; if none, fall back to original - extracted_sql = extract_sql_from_markdown(response.content) - corrected_sql = clean_sql(extracted_sql) if extracted_sql else generated_sql - if not corrected_sql.strip(): - corrected_sql = generated_sql - - explanation = extract_explanation_after_marker( - response.content, - marker="EXPLANATION:", - ) - return corrected_sql, explanation - -# %% -# Generate SQL - -def generate_sql(question: str, rag_context: str) -> str: - """ - Generate SQL using LLM, but also pull in any past user feedback - (corrected SQL) for this question as external guidance. - """ - # External correction from past feedback, if any - last_fb = get_last_feedback_for_question(conn, question) - if last_fb and last_fb.get("corrected_sql"): - previous_feedback_block = f""" -EXTERNAL USER FEEDBACK FROM PAST RUNS: - -Previous generated SQL: -{last_fb['generated_sql']} - -Corrected SQL (preferred reference): -{last_fb['corrected_sql']} - -User comment & prior explanation: -{last_fb.get('comment') or '(none)'} - -You must avoid repeating the same mistake and should follow the logic of -the corrected SQL when appropriate, while still reasoning from the schema. -""" - else: - previous_feedback_block = "" - - system_instructions = f""" -You are a senior data analyst writing SQL for a SQLite database. - -You will be given: - -- A description of available tables, columns, and relationships (schema + YAML metadata). -- A natural language question from the user. - -Your job: - -- Write ONE valid SQLite SQL query that answers the question. -- ONLY use tables and columns that exist in the schema_context. -- Use correct JOINS (Left, Right, Inner, Outer, Full Outer etc.) with ON conditions. -- Do not use DROP, INSERT, UPDATE, DELETE or other destructive operations. -- Always use floating-point division for percentage calculations using 1.0 * numerator / denominator, - and round to 2 decimals when appropriate. - -{previous_feedback_block} -""" - - prompt = ( - system_instructions - + "\n\n=== RAG CONTEXT ===\n" - + rag_context - + "\n\n=== USER QUESTION ===\n" - + question - + "\n\nSQL query:" - ) - - log_prompt("SQL_GENERATION", prompt) - response = llm.invoke(prompt) - log_run_event("RAW_MODEL_RESPONSE_SQL_GENERATION", response.content) - - sql = clean_sql(response.content) - return sql - - -# %% -# Repair SQL - -def repair_sql( - question: str, - rag_context: str, - bad_sql: str, - error_message: str, -) -> str: - """ - Ask the LLM to correct a failing SQL query. - """ - system_instructions = """ -You are a senior data analyst fixing an existing SQL query for a SQLite database. - -You will be given: - -- Schema context (tables, columns, relationships). -- The user's question. -- A previously generated SQL query that failed. -- The SQLite error message. - -Your job: - -- Diagnose why the query failed. -- Rewrite ONE valid SQLite SQL query that answers the question. -- ONLY use tables and columns that exist in the schema_context. -- Use correct JOINS (Left, Right, Inner, Outer, Full Outer etc.) with ON conditions. -- Do not use DROP, INSERT, UPDATE, DELETE or other destructive operations. -- Return ONLY the corrected SQL query, no explanation or markdown. -""" - - prompt = ( - system_instructions - + "\n\n=== RAG CONTEXT ===\n" - + rag_context - + "\n\n=== USER QUESTION ===\n" - + question - + "\n\n=== PREVIOUS (FAILING) SQL ===\n" - + bad_sql - + "\n\n=== SQLITE ERROR ===\n" - + error_message - + "\n\nCorrected SQL query:" - ) - - log_prompt("SQL_REPAIR", prompt) - response = llm.invoke(prompt) - log_run_event("RAW_MODEL_RESPONSE_SQL_REPAIR", response.content) - - sql = clean_sql(response.content) - return sql - - -# %% -### 11. Result summarization - -def summarize_results( - question: str, - sql: str, - df: Optional[pd.DataFrame], - rag_context: str, - error: Optional[str] = None, -) -> str: - """ - Ask the LLM to produce a concise, human-readable answer. - """ - system_instructions = """ - You are a senior data analyst. - - You will be given: - - The user's question. - The final SQL that was executed. - A small preview of the query result (as a Markdown table, if available). - Optional error information if the query failed. - - Your job: - - Provide a clear, concise answer in Markdown. - If the result is numeric / aggregated, explain what it means in business terms. - If there was an error, explain it simply and suggest how the user could rephrase. - Do NOT show raw SQL unless it is helpful to the user. - """ - - # Build a markdown table preview if we have data - if df is not None and not df.empty: - preview_rows = min(len(df), 50) - df_preview_md = df.head(preview_rows).to_markdown(index=False) - else: - df_preview_md = "(no rows returned)" - - prompt = ( - system_instructions - + "\n\n=== USER QUESTION ===\n" - + question - + "\n\n=== EXECUTED SQL ===\n" - + sql - + "\n\n=== QUERY RESULT PREVIEW ===\n" - + df_preview_md - + "\n\n=== RAG CONTEXT (schema) ===\n" - + rag_context - ) - - if error: - prompt += "\n\n=== ERROR ===\n" + error - - # Logging helpers assumed to exist - log_prompt("RESULT_SUMMARY", prompt) - - response = llm.invoke(prompt) - log_run_event("RAW_MODEL_RESPONSE_RESULT_SUMMARY", response.content) - - return response.content.strip() - - -# %% -def backend_pipeline(question: str): - """ - Cache-first backend. - - Returns 13 items expected by the UI: - (answer_md, df_preview, sql_used, rag_context, question_echo, - answer_md_state, df_state, - cached_matches, dropdown_choices, dropdown_visible, - attempts_left, attempts_text, cached_stats_update) - - Behavior: - - Normalize + search cache (with allow_fallback=True). - - If cached candidates present: show primary & dropdown of alternatives (even if low similarity). - - If no cache: run LLM -> validate -> exec -> summarize -> cache result (best-effort). - """ - # Basic guards - if not question or not question.strip(): - return ( - "Please type a question.", - pd.DataFrame(), - "", "", "", "", pd.DataFrame(), - [], [], False, - 4, "**Feedback attempts remaining: 4**", - gr.update(value="", visible=False), - ) - - # Reset attempts for a fresh question (per your desired UX) - attempts_left = 4 - attempts_text = f"**Feedback attempts remaining: {attempts_left}**" - - # Short-circuit for general Qs - if is_general_question(question): - overview_md = answer_general_question(question) - return ( - overview_md, - pd.DataFrame(), - "", - "", - question, - overview_md, - pd.DataFrame(), - [], [], False, - attempts_left, - attempts_text, - gr.update(value="", visible=False), - ) - - # ---------------------------- - # Step 0: Try cache (normalized + fallback) - # ---------------------------- - try: - cached_matches = retrieve_cached_sql_answers_ranked( - question, k=6, max_distance=0.25, allow_fallback=True, store=get_sql_cache_store() - ) - except Exception as e: - log_run_event("CACHE_LOOKUP_ERROR", str(e)) - cached_matches = [] - - # If we have cached candidates (possibly fallback), use them - if cached_matches: - # normalize metadata & ensure defaults - for cm in cached_matches: - md = cm.setdefault("metadata", {}) - md.setdefault("good_count", int(md.get("good_count", 0))) - md.setdefault("bad_count", int(md.get("bad_count", 0))) - md.setdefault("total_feedbacks", int(md.get("total_feedbacks", md.get("good_count", 0) + md.get("bad_count", 0)))) - md.setdefault("success_rate", float(md.get("success_rate", 1.0 if md.get("total_feedbacks", 0) == 0 else md.get("success_rate", 1.0)))) - md.setdefault("views", int(md.get("views", 0))) - md.setdefault("saved_at", md.get("saved_at", _now_ts())) - - primary = cached_matches[0] - rag_context = get_rag_context(question) - - # Label primary hit type depending on distance - dist = float(primary.get("distance", 1.0)) - hit_type = "⚡ Cache Hit (Primary)" if dist <= 0.25 else "⚡ Cache Hit (Primary - low similarity / fallback)" - - header = ( - f"### {hit_type}\n" - f"Reused cached result (distance={dist:.4f})\n" - f"Matched question: \"{primary.get('matched_question','')}\"\n\n---\n\n" - ) - answer_md = header + (primary.get("answer_md") or "") - - # Re-run the SQL to reconstruct the DataFrame for display - try: - df_primary, exec_error = execute_sql(primary.get("sql") or "", conn) - if exec_error: - df_primary = pd.DataFrame() - answer_md += f"\n\n⚠️ Error re-running cached SQL: `{exec_error}`" - except Exception as e: - df_primary = pd.DataFrame() - answer_md += f"\n\n⚠️ Exception re-running cached SQL: `{e}`" - - # Best-effort increment views - try: - increment_cache_views(primary.get("metadata") or {}, store=get_sql_cache_store()) - except Exception: - pass - - # Build dropdown label list: show primary + alternatives with stats - dropdown_choices = [] - for idx, m in enumerate(cached_matches): - md = m.get("metadata", {}) - dist_i = float(m.get("distance", 1.0)) - sr = float(md.get("success_rate", 1.0) or 1.0) - tf = int(md.get("total_feedbacks", 0) or 0) - views = int(md.get("views", 0) or 0) - saved_at = md.get("saved_at") - try: - saved_at_s = __import__("datetime").datetime.fromtimestamp(float(saved_at)).strftime("%Y-%m-%d %H:%M") if saved_at else "unknown" - except Exception: - saved_at_s = str(saved_at or "unknown") - prefix = "Primary" if idx == 0 else f"Alt {idx}" - label = f"{idx}. {prefix}: {m.get('matched_question','')} (dist={dist_i:.4f}, sr={sr:.2f}, fb={tf}, views={views}, saved={saved_at_s})" - dropdown_choices.append(label) - - dropdown_visible = len(dropdown_choices) > 0 - - # Primary stats markdown - pmd = primary.get("metadata", {}) - sr = float(pmd.get("success_rate", 1.0) or 1.0) - tf = int(pmd.get("total_feedbacks", 0) or 0) - views = int(pmd.get("views", 0) or 0) - saved_at = pmd.get("saved_at") - try: - saved_at_s = __import__("datetime").datetime.fromtimestamp(float(saved_at)).strftime("%Y-%m-%d %H:%M") if saved_at else "unknown" - except Exception: - saved_at_s = str(saved_at or "unknown") - - primary_stats_md = ( - f"**Primary cached entry stats**\n\n" - f"- **Success rate:** {sr:.2f} \n" - f"- **Total feedbacks:** {tf} \n" - f"- **Views:** {views} \n" - f"- **Saved at:** {saved_at_s} \n\n" - f"**SQL preview:**\n\n```sql\n{primary.get('sql')}\n```\n" - ) - cached_stats_update = gr.update(value=primary_stats_md, visible=True) - - # Return the cached-primary result (UI will also populate dropdown with alternatives) - return ( - answer_md, - df_primary, - primary.get("sql") or "", - rag_context, - question, - answer_md, - df_primary, - cached_matches, - dropdown_choices, - dropdown_visible, - attempts_left, - attempts_text, - cached_stats_update, - ) - - # ---------------------------- - # Step 1: No cache -> normal LLM flow - # ---------------------------- - rag_context = get_rag_context(question) - sql = generate_sql(question, rag_context) - original_sql = sql - - # Validate and attempt single auto-repair - is_valid, validation_error = validate_sql(sql, conn) - repaired = False - if not is_valid and validation_error: - repaired_sql = repair_sql(question, rag_context, sql, validation_error) - repaired_valid, repaired_error = validate_sql(repaired_sql, conn) - if repaired_valid: - sql = repaired_sql - repaired = True - log_run_event("SQL_REPAIR_SUCCESS", f"Original SQL:\n{original_sql}\n\nRepaired SQL:\n{sql}") - validation_error = None - else: - log_run_event("SQL_REPAIR_FAILED", f"Original SQL:\n{original_sql}\nRepaired SQL:\n{repaired_sql}\nError:{repaired_error}") - validation_error = repaired_error or validation_error - - log_run_event("FINAL_SQL", sql) - - # Execute - df, exec_error = (None, None) - if validation_error: - exec_error = validation_error - log_run_event("EXECUTION_SKIPPED_DUE_TO_VALIDATION_ERROR", f"SQL:\n{sql}\nValidation error:\n{validation_error}") - else: - df, exec_error = execute_sql(sql, conn) - if exec_error: - log_run_event("EXECUTION_ERROR", f"SQL:\n{sql}\nExecution error:\n{exec_error}") - else: - rows = 0 if df is None else len(df) - log_run_event("EXECUTION_SUCCESS", f"SQL:\n{sql}\nRows returned: {rows}") - - # Summarize - summary_text = summarize_results(question=question, sql=sql, df=df, rag_context=rag_context, error=exec_error) - - # SQL debug - sql_status_lines = [] - if exec_error: - sql_status_lines.append("There was an error running the SQL.") - sql_status_lines.append(f"**Error:** `{exec_error}`") - else: - sql_status_lines.append("Query ran successfully.") - if repaired: - sql_status_lines.append("_Note: The original SQL was corrected by the assistant (auto-repair step)._") - sql_status_lines.append("\n**Final SQL used:**\n") - sql_status_lines.append(f"```sql\n{sql}\n```") - sql_debug_md = "\n".join(sql_status_lines) - - df_preview = df if (df is not None and exec_error is None) else pd.DataFrame() - answer_md = summary_text + "\n\n---\n\n" + sql_debug_md - - # Cache the executed result (best-effort). Mark default metadata: success_rate=1.0, total_feedbacks=0, views=1 - if exec_error is None: - try: - meta = {"success_rate": 1.0, "total_feedbacks": 0, "views": 1, "saved_at": _now_ts()} - cache_sql_answer_dedup(question, sql, answer_md, metadata=meta, store=get_sql_cache_store()) - except Exception: - _logger.exception("backend_pipeline: caching of run failed.") - - return ( - answer_md, - df_preview, - sql, - rag_context, - question, - answer_md, - df_preview, - [], [], False, - attempts_left, - attempts_text, - gr.update(value="", visible=False), - ) - - -# %% -def _looks_like_sql(text: str) -> bool: - """Quick heuristic: does text contain SQL keywords / SELECT ?""" - if not text: - return False - return bool(re.search(r"\bselect\b|\bfrom\b|\bwhere\b|\bjoin\b|\bgroup by\b|\border by\b", text, flags=re.I)) - - -def is_feedback_sufficient(feedback_text: str) -> bool: - """ - Heuristic to decide whether the user's free-text feedback is actionable. - - Returns True if: - - length >= 20 characters AND contains a signal word (e.g., 'filter', 'year', 'should', 'instead', 'missing', 'wrong', digits), - OR - - it looks like SQL (user pasted corrected SQL), - OR - - length >= 60 characters (long feedback). - """ - if not feedback_text: - return False - - text = feedback_text.strip() - if len(text) >= 60: - return True - - if _looks_like_sql(text): - return True - - # look for signal words that indicate specificity - signal_words = [ - "filter", "where", "year", "month", "should", "instead", "expected", - "wrong", "missing", "aggregate", "sum", "avg", "count", "distinct", - "join", "left join", "inner join", "group by", "order by", "date", - "range", "exclude", "include", "only" - ] - lower = text.lower() - signals = sum(1 for w in signal_words if w in lower) - if signals >= 1 and len(text) >= 20: - return True - - # short hits like "numbers look off" are insufficient - return False - - -def build_followup_prompt_for_user(sample_feedback: str = "") -> str: - """ - Deterministic follow-up question to ask the user when feedback is vague. - Returns a friendly prompt that the UI can display to the user. - """ - base = ( - "Thanks — I need a bit more detail to act on this feedback.\n\n" - "Please tell me one (or more) of the following so I can check and correct the result:\n\n" - "1. Which part looks wrong — the **numbers**, the **aggregation** (sum/count/avg),\n" - " the **time range** (year/month), or the **filters** applied?\n" - "2. If you expected a different number, what was the expected number (and how was it computed)?\n" - "3. If you have a corrected SQL snippet, paste it (I can run and compare it).\n\n" - "Examples you can copy-paste:\n" - ) - examples = ( - "- \"I think the query should count DISTINCT customer_unique_id, not customer_id.\"\n" - "- \"This looks off for year 2018 — I expected the count for 2018 to be ~40k.\"\n" - "- \"Please exclude canceled orders (order_status = 'canceled').\"\n" - "- \"SELECT COUNT(DISTINCT customer_unique_id) FROM olist_customers_dataset;\"\n" - ) - hint = "\nIf you prefer, just paste a corrected SQL snippet and I'll run it and compare." - prompt = base + examples + hint - if sample_feedback: - prompt = f"I saw your feedback: \"{sample_feedback}\"\n\n" + prompt - return prompt - - - -# %% -def feedback_pipeline_interactive( - feedback_rating: str, - feedback_comment: str, - last_sql: str, - last_rag_context: str, - last_question: str, - last_answer_md: str, - last_df: pd.DataFrame, - feedback_sql: Optional[str] = None, - attempts_left: Optional[int] = 4, -) -> tuple: - """ - Interactive feedback flow used by Gradio UI. Returns tuple: - (message, df_out, last_sql_new, last_rag_new, last_q_new, last_answer_new, last_df_new, - awaiting_more_feedback(bool), followup_prompt(str), updated_attempts(int)) - Behavior: - - If rating == 'correct': increments cache success, stores as good; does not decrement attempts. - - If rating == 'wrong': - - initial wrong decrements attempts by 1. - - if comment too short -> ask follow-up (awaiting_more_feedback=True) - - else -> call LLM review, possibly corrected_sql; run corrected SQL; update cache via update_cache_on_feedback - """ - # normalize - rating = (feedback_rating or "").strip().lower() - comment = (feedback_comment or "").strip() if feedback_comment is not None else "" - - # guard - if not last_question or not last_sql: - msg = "No previous query found to attach feedback to. Please run a question first." - return (msg, pd.DataFrame(), last_sql, last_rag_context, last_question, last_answer_md, last_df, False, "", attempts_left) - - # Ensure attempts_left int - try: - attempts_left = int(attempts_left) if attempts_left is not None else 4 - except Exception: - attempts_left = 4 - - # Validate rating - if rating not in ("correct", "wrong"): - msg = last_answer_md + "\n\n---\n\n(Please choose 'Correct' or 'Wrong' before submitting feedback.)" - return (msg, last_df, last_sql, last_rag_context, last_question, last_answer_md, last_df, False, "", attempts_left) - - # CASE: Correct -> update cache metrics but DO NOT decrement attempts - if rating == "correct": - # find original doc best-effort - try: - original_doc = find_cached_doc_by_sql(last_question, last_sql, store=get_sql_cache_store()) - except Exception: - original_doc = None - - try: - update_cache_on_feedback( - question=last_question, - original_doc_md=original_doc, - user_marked_good=True, - llm_corrected_sql=None, - llm_corrected_answer_md=None, - store=get_sql_cache_store(), - ) - except Exception: - _logger.exception("feedback_pipeline_interactive: update_cache_on_feedback failed for correct") - - try: - record_feedback(conn=conn, question=last_question, generated_sql=last_sql, model_answer=last_answer_md, rating="good", comment=comment or None, corrected_sql=None) - except Exception: - _logger.exception("feedback_pipeline_interactive: record_feedback failed for correct") - - msg = last_answer_md + "\n\n---\n\n Feedback recorded as GOOD and cache updated." - return (msg, last_df, last_sql, last_rag_context, last_question, last_answer_md, last_df, False, "", attempts_left) - - # CASE: Wrong -> decrement attempts (initial wrong counts) - updated_attempts = max(0, attempts_left - 1) - - # If insufficient detail, ask follow-up (preserve full previous answer in UI) - if not comment or len(comment) < 20: - followup_prompt = ( - "Thanks — I need a bit more detail to act on that feedback.\n\n" - "Please tell the assistant what exactly seems wrong: e.g. 'Wrong year filter (should be 2018)', " - "'Missing DISTINCT', 'Join condition seems incorrect', or paste the SQL you think is right." - ) - # return with awaiting_more_feedback True and the preserved last_answer_md so UI can keep showing it - return (last_answer_md, last_df, last_sql, last_rag_context, last_question, last_answer_md, last_df, True, followup_prompt, updated_attempts) - - # Sufficient detail: call LLM reviewer to propose corrected SQL (or confirm original) - try: - original_doc = find_cached_doc_by_sql(last_question, last_sql, store=get_sql_cache_store()) - except Exception: - original_doc = None - - corrected_sql, explanation = review_and_correct_sql_with_llm( - question=last_question, - generated_sql=last_sql, - user_feedback_comment=comment, - rag_context=last_rag_context, - ) - - # If LLM did not provide SQL, keep the original - if not corrected_sql or not corrected_sql.strip(): - corrected_sql = last_sql - - # Execute corrected SQL - df_corrected, exec_error = execute_sql(corrected_sql, conn) - if exec_error: - corrected_answer_core = summarize_results(question=last_question, sql=corrected_sql, df=None, rag_context=last_rag_context, error=exec_error) - df_out = pd.DataFrame() - else: - corrected_answer_core = summarize_results(question=last_question, sql=corrected_sql, df=df_corrected, rag_context=last_rag_context, error=None) - df_out = df_corrected if df_corrected is not None else pd.DataFrame() - - # Update cache: penalize original, add corrected (if different) - try: - update_cache_on_feedback( - question=last_question, - original_doc_md=original_doc, - user_marked_good=False, - llm_corrected_sql=corrected_sql if corrected_sql.strip() != last_sql.strip() else None, - llm_corrected_answer_md=(corrected_answer_core if corrected_sql.strip() != last_sql.strip() else None), - store=get_sql_cache_store(), - ) - except Exception: - _logger.exception("feedback_pipeline_interactive: update_cache_on_feedback failed for wrong") - - # record feedback in DB - try: - record_feedback(conn=conn, question=last_question, generated_sql=last_sql, model_answer=last_answer_md, rating="bad", comment=(comment or "") + "\n\nLLM explanation:\n" + (explanation or ""), corrected_sql=corrected_sql) - except Exception: - _logger.exception("feedback_pipeline_interactive: record_feedback save failed") - - # Build final message - corrected_answer_md = ( - corrected_answer_core - + "\n\n---\n\n" - + f"**Final corrected SQL used:**\n```sql\n{corrected_sql}\n```\n\n" - + "### LLM Review Explanation\n" - + (explanation or "") - ) - - return (corrected_answer_md, df_out, corrected_sql, last_rag_context, last_question, corrected_answer_md, df_out, False, "", updated_attempts) - - -# %% -def _on_cached_selection_impl(choice_label: str, cached_matches): - """ - Given the selected dropdown label and the cached_matches list (from backend_pipeline), - return the outputs expected by the Gradio change handler: - - Returns tuple: - (answer_md, df_sel, sel_sql, sel_question, last_answer_state, last_df_state, cached_stats_update) - - Expects dropdown label to start with an index like "0. Primary: ..." or "2. Alt 2: ...". - """ - # Safety checks - try: - if not choice_label or not cached_matches: - return "", pd.DataFrame(), "", "", "", pd.DataFrame(), gr.update(value="", visible=False) - - # extract index (leading integer before the first dot) - try: - idx = int(choice_label.split(".")[0]) - except Exception: - # invalid label format - return "", pd.DataFrame(), "", "", "", pd.DataFrame(), gr.update(value="", visible=False) - - # boundary check - if idx < 0 or idx >= len(cached_matches): - return "", pd.DataFrame(), "", "", "", pd.DataFrame(), gr.update(value="", visible=False) - - sel = cached_matches[idx] - sel_sql = sel.get("sql") or "" - sel_question = sel.get("matched_question") or "" - sel_answer_md = sel.get("answer_md") or "" - - # Re-run the SQL to reconstruct the DataFrame for the UI - try: - df_sel, exec_error = execute_sql(sel_sql, conn) - if exec_error: - # Execution failed — show error and empty table - df_sel = pd.DataFrame() - sel_answer_md = sel_answer_md + f"\n\n⚠️ Error re-running cached SQL: `{exec_error}`" - except Exception as e: - df_sel = pd.DataFrame() - sel_answer_md = sel_answer_md + f"\n\n⚠️ Exception re-running cached SQL: `{e}`" - - # Build cached-entry stats markdown (if metadata present) - md = sel.get("metadata") or {} - good = int(md.get("good_count", 0) or 0) - bad = int(md.get("bad_count", 0) or 0) - total_fb = int(md.get("total_feedbacks", good + bad) or (good + bad)) - sr = float(md.get("success_rate", 1.0) or 1.0) - views = int(md.get("views", 0) or 0) - saved_at = md.get("saved_at") - try: - saved_at_s = ( - __import__("datetime").datetime.fromtimestamp(float(saved_at)).strftime("%Y-%m-%d %H:%M") - if saved_at - else "unknown" - ) - except Exception: - saved_at_s = str(saved_at or "unknown") - - stats_md = ( - f"**Cached entry stats**\n\n" - f"- **Success rate:** {sr:.2f} \n" - f"- **Total feedbacks:** {total_fb} \n" - f"- **Good / Bad:** {good} / {bad} \n" - f"- **Views:** {views} \n" - f"- **Saved at:** {saved_at_s} \n\n" - f"**SQL preview:**\n\n```sql\n{sel_sql}\n```\n" - ) - - # Return values for Gradio outputs: - # answer_out (markdown), table_out (df), last_sql_state (str), last_question_state (str), - # last_answer_state (markdown), last_df_state (df), cached_stats_md (gr.update) - return sel_answer_md, df_sel, sel_sql, sel_question, sel_answer_md, df_sel, gr.update(value=stats_md, visible=True) - - except Exception as exc: - # Unexpected error -> return safe defaults and log (if you have a logger) - try: - _logger.exception("Error in _on_cached_selection_impl: %s", exc) - except Exception: - pass - return "", pd.DataFrame(), "", "", "", pd.DataFrame(), gr.update(value="", visible=False) - - -# %% -import gradio as gr -import pandas as pd -import datetime - -# Replace your current Gradio block with this whole cell. -# This cell expects the helper functions used in your project to be present. -# Helpers referenced (not defined here): backend_pipeline, execute_sql, -# get_sql_cache_store, find_cached_doc_by_sql, review_and_correct_sql_with_llm, -# update_cache_on_feedback, record_feedback, increment_cache_views, summarize_results, -# conn, _logger - -with gr.Blocks() as demo: - - gr.Markdown("# Olist Analytics Assistant (RAG + SQL + Interactive Feedback)\n\nAsk natural-language questions about the Olist dataset.") - - # Persistent state variables - last_sql_state = gr.State("") - last_rag_state = gr.State("") - last_question_state = gr.State("") - last_answer_state = gr.State("") # full previous answer markdown - last_df_state = gr.State(pd.DataFrame()) - - attempts_state = gr.State(4) - original_feedback_text_state = gr.State("") - - cached_matches_state = gr.State([]) - cached_matches_dropdown = gr.Dropdown(choices=[], label="Cached matches (primary + alternatives)", visible=False) - cached_stats_md = gr.Markdown("", visible=False) - - # Input / Output - with gr.Row(): - with gr.Column(scale=1): - question_in = gr.Textbox(label="Your question", placeholder="e.g. Total number of unique customers in 2017", lines=4) - submit_btn = gr.Button("Run") - with gr.Column(scale=2): - answer_out = gr.Markdown("Answer will appear here.") - table_out = gr.Dataframe(label="Result table") - - attempts_display = gr.Markdown("**Feedback attempts remaining: 4**") - - gr.Markdown("### Feedback on the last answer (mark and explain)") - - with gr.Row(): - with gr.Column(scale=2): - feedback_rating = gr.Radio(choices=["Correct", "Wrong"], label="Was the answer correct?", value=None) - feedback_comment = gr.Textbox(label="Explain what was wrong (mandatory for Wrong).", lines=3) - with gr.Column(scale=1): - feedback_btn = gr.Button("Submit feedback") - - # Follow-up UI (initially hidden) - followup_prompt_md = gr.Markdown("", visible=False) - with gr.Row(): - followup_input = gr.Textbox(label="Provide more detail (or paste an SQL you think is correct)", visible=False, lines=4) - with gr.Column(scale=1): - followup_submit_btn = gr.Button("Submit follow-up", visible=False) - - # ----------------------- - # Helper functions used for UI updates (only wiring / visibility) - # ----------------------- - - def _reset_feedback_ui(): - """Return a set of gr.update objects to reset the initial feedback controls and hide followup controls.""" - return ( - gr.update(value="", visible=True), # feedback_comment - gr.update(value=None, visible=True), # feedback_rating - gr.update(visible=True), # feedback_btn - gr.update(value="", visible=False), # followup_input - gr.update(visible=False), # followup_submit_btn - gr.update(value="", visible=False), # followup_prompt_md - ) - - # ----------------------- - # Run pipeline -> UI - # ----------------------- - def _run_query_and_return_ui(question): - """ - Calls backend_pipeline(question) and maps outputs to Gradio UI components. - Expected backend_pipeline return (13 items): - (answer_md, df_preview, sql_used, rag_context, q_echo, - answer_md_state, df_state, - cached_matches (list), dropdown_choices (list), dropdown_visible (bool), - attempts_left (int), attempts_text (str), cached_stats_update (gr.update or str)) - """ - # default reset values (so every new question shows initial feedback controls and hides followup) - feedback_comment_reset, feedback_rating_reset, feedback_btn_reset, followup_input_hide, followup_btn_hide, followup_prompt_hide = _reset_feedback_ui() - - try: - res = backend_pipeline(question) - except Exception as e: - # On error: show error and reset the UI - return ( - f"Error running pipeline: {e}", - pd.DataFrame(), - "", "", "", "", pd.DataFrame(), - [], gr.update(choices=[], visible=False), - 4, - "**Feedback attempts remaining: 4**", - gr.update(value="", visible=False), # cached_stats_update placeholder - feedback_comment_reset, - feedback_rating_reset, - feedback_btn_reset, - followup_input_hide, - followup_btn_hide, - followup_prompt_hide, - ) - - if not res or len(res) != 13: - return ( - "Error: backend_pipeline returned unexpected structure.", - pd.DataFrame(), - "", "", "", "", pd.DataFrame(), - [], gr.update(choices=[], visible=False), - 4, - "**Feedback attempts remaining: 4**", - gr.update(value="", visible=False), - feedback_comment_reset, - feedback_rating_reset, - feedback_btn_reset, - followup_input_hide, - followup_btn_hide, - followup_prompt_hide, - ) - - ( - answer_md, - df_preview, - sql_used, - rag_context, - q_echo, - answer_md_state, - df_state, - cached_matches, - dropdown_choices, - dropdown_visible, - attempts_left, - attempts_text, - cached_stats_update, - ) = res - - # prepare dropdown update object - dropdown_update = gr.update(choices=dropdown_choices or [], visible=bool(dropdown_visible)) - - # Reset the feedback UI to defaults (initial controls visible, followup hidden) - feedback_comment_reset, feedback_rating_reset, feedback_btn_reset, followup_input_hide, followup_btn_hide, followup_prompt_hide = _reset_feedback_ui() - - return ( - answer_md, # answer_out - df_preview, # table_out - sql_used, # last_sql_state - rag_context, # last_rag_state - q_echo, # last_question_state - answer_md_state, # last_answer_state - df_state, # last_df_state - cached_matches, # cached_matches_state - dropdown_update, # cached_matches_dropdown update - attempts_left, # attempts_state - attempts_text, # attempts_display - cached_stats_update, # cached_stats_md update - feedback_comment_reset, - feedback_rating_reset, - feedback_btn_reset, - followup_input_hide, - followup_btn_hide, - followup_prompt_hide, - ) - - # ----------------------- - # Dropdown selection of cached alternatives - # ----------------------- - def _on_cached_selection_impl(choice_label: str, cached_matches): - """ - When a cached alternative is selected, return: - (answer_md, df_sel, last_sql, last_question, last_answer_state, last_df_state, cached_stats_update) - """ - if not choice_label or not cached_matches: - return "", pd.DataFrame(), "", "", "", pd.DataFrame(), gr.update(value="", visible=False) - - # dropdown labels are "0. Primary: text" or "1. Alt 1: text", first token is index - try: - idx = int(choice_label.split(".")[0]) - except Exception: - return "", pd.DataFrame(), "", "", "", pd.DataFrame(), gr.update(value="", visible=False) - - if idx < 0 or idx >= len(cached_matches): - return "", pd.DataFrame(), "", "", "", pd.DataFrame(), gr.update(value="", visible=False) - - sel = cached_matches[idx] - sel_sql = sel.get("sql") or "" - sel_answer_md = sel.get("answer_md") or "" - - # re-run SQL to get table - try: - df_sel, exec_error = execute_sql(sel_sql, conn) - if exec_error: - df_sel = pd.DataFrame() - sel_answer_md = sel_answer_md + f"\n\n⚠️ Error re-running cached SQL: `{exec_error}`" - except Exception as e: - df_sel = pd.DataFrame() - sel_answer_md = sel_answer_md + f"\n\n⚠️ Exception re-running cached SQL: `{e}`" - - # Build stats from metadata (safe extraction) - md = sel.get("metadata") or {} - good = int(md.get("good_count", 0) or 0) - bad = int(md.get("bad_count", 0) or 0) - total_fb = int(md.get("total_feedbacks", good + bad) or (good + bad)) - sr = float(md.get("success_rate", 1.0) or 1.0) - views = int(md.get("views", 0) or 0) - saved_at = md.get("saved_at") - try: - saved_at_s = datetime.datetime.fromtimestamp(float(saved_at)).strftime("%Y-%m-%d %H:%M") if saved_at else "unknown" - except Exception: - saved_at_s = str(saved_at or "unknown") - - stats_md = ( - f"**Cached entry stats**\n\n" - f"- **Success rate:** {sr:.2f} \n" - f"- **Total feedbacks:** {total_fb} \n" - f"- **Good / Bad:** {good} / {bad} \n" - f"- **Views:** {views} \n" - f"- **Saved at:** {saved_at_s} \n\n" - f"**SQL preview:**\n\n```sql\n{sel_sql}\n```\n" - ) - - # try incrementing views (best-effort) - try: - increment_cache_views(sel.get("id"), store=get_sql_cache_store()) - except Exception: - # non-fatal - pass - - return sel_answer_md, df_sel, sel_sql, sel.get("matched_question") or "", sel_answer_md, df_sel, gr.update(value=stats_md, visible=True) - - # ----------------------- - # Initial feedback handler - # ----------------------- - def _submit_initial_feedback( - rating, - feedback_text, - last_sql, - last_rag, - last_question, - last_answer, - last_df, - attempts_left, - ): - """ - - Correct: update cache (no attempt decrement), return UI updates in exact order. - - Wrong: decrement attempts. If feedback_text is short -> show follow-up and HIDE initial inputs. - If feedback_text is sufficient -> call LLM immediately and show results/caching. - Returns values for: - (answer_out, table_out, last_sql_state, last_rag_state, last_question_state, - last_answer_state, last_df_state, original_feedback_text_state, followup_prompt_md, - followup_input, followup_submit_btn, attempts_state, attempts_display, - feedback_comment, feedback_rating, feedback_btn, followup_input, followup_submit_btn, followup_prompt_md) - Note: the last six correspond to UI updates to ensure visibility/state is consistent. - """ - rating_norm = (rating or "").strip().lower() - comment = (feedback_text or "").strip() - - # guard - if not last_question or not last_sql: - msg = "No previous query found to attach feedback to. Please run a question first." - # keep UI as-is but return a safe result and reset feedback - fb_comment_reset, fb_rating_reset, fb_btn_reset, fu_input_hide, fu_btn_hide, fu_prompt_hide = _reset_feedback_ui() - return ( - msg, pd.DataFrame(), - last_sql, last_rag, last_question, last_answer, last_df, - "", "", gr.update(visible=False), gr.update(visible=False), - attempts_left, f"**Feedback attempts remaining: {attempts_left}**", - fb_comment_reset, fb_rating_reset, fb_btn_reset, fu_input_hide, fu_btn_hide, fu_prompt_hide, - ) - - if rating_norm not in ("correct", "wrong"): - msg = last_answer + "\n\n---\n\n(Please choose 'Correct' or 'Wrong' before submitting feedback.)" - fb_comment_reset, fb_rating_reset, fb_btn_reset, fu_input_hide, fu_btn_hide, fu_prompt_hide = _reset_feedback_ui() - return ( - msg, last_df, last_sql, last_rag, last_question, last_answer, last_df, - "", "", gr.update(visible=False), gr.update(visible=False), - attempts_left, f"**Feedback attempts remaining: {attempts_left}**", - fb_comment_reset, fb_rating_reset, fb_btn_reset, fu_input_hide, fu_btn_hide, fu_prompt_hide, - ) - - # CASE: Correct -> update cache, do not decrement attempts - if rating_norm == "correct": - try: - original_doc_md = find_cached_doc_by_sql(last_question, last_sql, store=get_sql_cache_store()) - except Exception: - original_doc_md = None - - try: - update_cache_on_feedback( - question=last_question, - original_doc_md=original_doc_md, - user_marked_good=True, - llm_corrected_sql=None, - llm_corrected_answer_md=None, - store=get_sql_cache_store(), - ) - except Exception: - _logger.exception("update_cache_on_feedback failed for correct feedback") - - # persist to relational feedback log - try: - record_feedback( - conn=conn, - question=last_question, - generated_sql=last_sql, - model_answer=last_answer, - rating="good", - comment=comment or None, - corrected_sql=None, - ) - except Exception: - _logger.exception("record_feedback failed for correct feedback") - - msg = last_answer + "\n\n---\n\n Feedback recorded as GOOD and cache updated." - fb_comment_reset, fb_rating_reset, fb_btn_reset, fu_input_hide, fu_btn_hide, fu_prompt_hide = _reset_feedback_ui() - return ( - msg, last_df, - last_sql, last_rag, last_question, last_answer, last_df, - "", "", gr.update(visible=False), gr.update(visible=False), - attempts_left, f"**Feedback attempts remaining: {attempts_left}**", - fb_comment_reset, fb_rating_reset, fb_btn_reset, fu_input_hide, fu_btn_hide, fu_prompt_hide, - ) - - # CASE: Wrong -> decrement attempts immediately - updated_attempts = max(0, attempts_left - 1) - - # If comment is too short -> ask follow-up: hide initial feedback controls and show follow-up - if not comment or len(comment) < 20: - followup_prompt = ( - "Thanks — I need a bit more detail to act on that feedback.\n\n" - "Please tell the assistant what exactly seems wrong: e.g. 'Wrong year filter (should be 2018)', " - "'Missing DISTINCT', 'Join condition seems incorrect', or paste the SQL you think is right." - ) - preserved_answer = last_answer or "" - answer_display_text = ( - preserved_answer - + "\n\n---\n\n📝 **More detail needed. Please answer the follow-up question below.**\n\n" - + followup_prompt - ) - - # Hide initial controls, show follow-up controls - fb_comment_hide = gr.update(value="", visible=False) - fb_rating_hide = gr.update(value=None, visible=False) - fb_btn_hide = gr.update(visible=False) - fu_input_show = gr.update(value="", visible=True) - fu_btn_show = gr.update(visible=True) - fu_prompt_show = gr.update(value=followup_prompt, visible=True) - - return ( - answer_display_text, last_df, - last_sql, last_rag, last_question, last_answer, last_df, - comment or "", followup_prompt, - fu_input_show, fu_btn_show, - updated_attempts, f"**Feedback attempts remaining: {updated_attempts}**", - fb_comment_hide, fb_rating_hide, fb_btn_hide, fu_input_show, fu_btn_show, fu_prompt_show, - ) - - # Otherwise: comment is sufficient -> run LLM reviewer immediately - try: - original_doc_md = find_cached_doc_by_sql(last_question, last_sql, store=get_sql_cache_store()) - except Exception: - original_doc_md = None - - corrected_sql, explanation = review_and_correct_sql_with_llm( - question=last_question, - generated_sql=last_sql, - user_feedback_comment=comment, - rag_context=last_rag, - ) - - df_corrected, exec_error = execute_sql(corrected_sql, conn) - if exec_error: - corrected_answer_core = summarize_results(question=last_question, sql=corrected_sql, df=None, rag_context=last_rag, error=exec_error) - df_final = pd.DataFrame() - else: - corrected_answer_core = summarize_results(question=last_question, sql=corrected_sql, df=df_corrected, rag_context=last_rag, error=None) - df_final = df_corrected if df_corrected is not None else pd.DataFrame() - - # update cache with corrected SQL (best-effort) - try: - update_cache_on_feedback( - question=last_question, - original_doc_md=original_doc_md, - user_marked_good=False, - llm_corrected_sql=corrected_sql, - llm_corrected_answer_md=corrected_answer_core, - store=get_sql_cache_store(), - ) - except Exception: - _logger.exception("update_cache_on_feedback failed in immediate wrong path") - - # log feedback - try: - record_feedback( - conn=conn, - question=last_question, - generated_sql=last_sql, - model_answer=last_answer, - rating="bad", - comment=comment + "\n\nLLM explanation:\n" + (explanation or ""), - corrected_sql=corrected_sql, - ) - except Exception: - _logger.exception("record_feedback failed for wrong immediate flow") - - corrected_answer_md = ( - corrected_answer_core - + "\n\n---\n\n" - + f"**Final corrected SQL used:**\n```sql\n{corrected_sql}\n```\n\n" - + "### LLM Review Explanation\n" - + (explanation or "") - ) - - fb_comment_reset, fb_rating_reset, fb_btn_reset, fu_input_hide, fu_btn_hide, fu_prompt_hide = _reset_feedback_ui() - - return ( - corrected_answer_md, df_final, - corrected_sql, last_rag, last_question, corrected_answer_md, df_final, - "", "", gr.update(visible=False), gr.update(visible=False), - updated_attempts, f"**Feedback attempts remaining: {updated_attempts}**", - fb_comment_reset, fb_rating_reset, fb_btn_reset, fu_input_hide, fu_btn_hide, fu_prompt_hide, - ) - - # ----------------------- - # Follow-up handler - # ----------------------- - def _submit_followup_feedback( - followup_text, - rating, - original_feedback_text, - last_sql, - last_rag, - last_question, - last_answer, - last_df, - attempts_left, - ): - """ - Follow-up attempt: merges original feedback + followup_text; consumes an attempt. - If still insufficient and attempts remain -> request another follow-up. - Otherwise run LLM reviewer and update cache. - """ - rating_norm = (rating or "").strip().lower() - merged_comment = "\n".join([original_feedback_text or "", followup_text or ""]).strip() - - # guard - if not last_question or not last_sql: - msg = "No previous query found to attach feedback to. Please run a question first." - fb_comment_reset, fb_rating_reset, fb_btn_reset, fu_input_hide, fu_btn_hide, fu_prompt_hide = _reset_feedback_ui() - return ( - msg, pd.DataFrame(), - last_sql, last_rag, last_question, last_answer, last_df, - "", "", gr.update(visible=False), gr.update(visible=False), - attempts_left, f"**Feedback attempts remaining: {attempts_left}**", - fb_comment_reset, fb_rating_reset, fb_btn_reset, fu_input_hide, fu_btn_hide, fu_prompt_hide, - ) - - # follow-up consumes an attempt - updated_attempts = max(0, attempts_left - 1) - - # If still short and attempts remain -> ask again - if not merged_comment or len(merged_comment) < 20: - if updated_attempts > 0: - preserved_answer = last_answer or "" - answer_display_text = ( - preserved_answer - + "\n\n---\n\n📝 I still need a bit more detail. Please make your follow-up more specific. Examples: " - "'Wrong year (should be 2018)', 'Missing DISTINCT', 'Join condition should be X', or paste the SQL you think is correct." - ) - # keep followup visible, hide initial - fb_comment_hide = gr.update(value="", visible=False) - fb_rating_hide = gr.update(value=None, visible=False) - fb_btn_hide = gr.update(visible=False) - return ( - answer_display_text, last_df, - last_sql, last_rag, last_question, last_answer, last_df, - merged_comment, "Please clarify (examples shown above).", - gr.update(visible=True), gr.update(visible=True), - updated_attempts, f"**Feedback attempts remaining: {updated_attempts}**", - fb_comment_hide, fb_rating_hide, fb_btn_hide, gr.update(visible=True), gr.update(visible=True), gr.update(value="Please clarify (examples shown above).", visible=True), - ) - # else: attempts exhausted -> continue to run reviewer with what we have - - # Run LLM reviewer with merged_comment - try: - original_doc_md = find_cached_doc_by_sql(last_question, last_sql, store=get_sql_cache_store()) - except Exception: - original_doc_md = None - - corrected_sql, explanation = review_and_correct_sql_with_llm( - question=last_question, - generated_sql=last_sql, - user_feedback_comment=merged_comment, - rag_context=last_rag, - ) - - df_corrected, exec_error = execute_sql(corrected_sql, conn) - if exec_error: - corrected_answer_core = summarize_results(question=last_question, sql=corrected_sql, df=None, rag_context=last_rag, error=exec_error) - df_final = pd.DataFrame() - else: - corrected_answer_core = summarize_results(question=last_question, sql=corrected_sql, df=df_corrected, rag_context=last_rag, error=None) - df_final = df_corrected if df_corrected is not None else pd.DataFrame() - - # attempt to update cache - try: - update_cache_on_feedback( - question=last_question, - original_doc_md=original_doc_md, - user_marked_good=False, - llm_corrected_sql=corrected_sql, - llm_corrected_answer_md=corrected_answer_core, - store=get_sql_cache_store(), - ) - except Exception: - _logger.exception("update_cache_on_feedback failed in follow-up path") - - # record feedback log - try: - record_feedback( - conn=conn, - question=last_question, - generated_sql=last_sql, - model_answer=last_answer, - rating="bad", - comment=(merged_comment or "") + "\n\nLLM explanation:\n" + (explanation or ""), - corrected_sql=corrected_sql, - ) - except Exception: - _logger.exception("record_feedback failed in follow-up path") - - corrected_answer_md = ( - corrected_answer_core - + "\n\n---\n\n" - + f"**Final corrected SQL used:**\n```sql\n{corrected_sql}\n```\n\n" - + "### LLM Review Explanation\n" - + (explanation or "") - ) - - # After follow-up completes, show initial controls again (cleared) and hide followup - fb_comment_reset, fb_rating_reset, fb_btn_reset, fu_input_hide, fu_btn_hide, fu_prompt_hide = _reset_feedback_ui() - - return ( - corrected_answer_md, df_final, - corrected_sql, last_rag, last_question, corrected_answer_md, df_final, - "", "", gr.update(visible=False), gr.update(visible=False), - updated_attempts, f"**Feedback attempts remaining: {updated_attempts}**", - fb_comment_reset, fb_rating_reset, fb_btn_reset, fu_input_hide, fu_btn_hide, fu_prompt_hide, - ) - - # ----------------------- - # Wire events (outputs ordering must match function returns) - # ----------------------- - submit_btn.click( - fn=_run_query_and_return_ui, - inputs=[question_in], - outputs=[ - answer_out, - table_out, - last_sql_state, - last_rag_state, - last_question_state, - last_answer_state, - last_df_state, - cached_matches_state, - cached_matches_dropdown, - attempts_state, - attempts_display, - cached_stats_md, - # extra UI resets (must match _run_query_and_return_ui extra returns) - feedback_comment, - feedback_rating, - feedback_btn, - followup_input, - followup_submit_btn, - followup_prompt_md, - ], - ) - - cached_matches_dropdown.change( - fn=_on_cached_selection_impl, - inputs=[cached_matches_dropdown, cached_matches_state], - outputs=[answer_out, table_out, last_sql_state, last_question_state, last_answer_state, last_df_state, cached_stats_md], - ) - - feedback_btn.click( - fn=_submit_initial_feedback, - inputs=[ - feedback_rating, - feedback_comment, - last_sql_state, - last_rag_state, - last_question_state, - last_answer_state, - last_df_state, - attempts_state, - ], - outputs=[ - answer_out, - table_out, - last_sql_state, - last_rag_state, - last_question_state, - last_answer_state, - last_df_state, - original_feedback_text_state, - followup_prompt_md, - followup_input, - followup_submit_btn, - attempts_state, - attempts_display, - # UI updates returned at the end of function: - feedback_comment, - feedback_rating, - feedback_btn, - followup_input, - followup_submit_btn, - followup_prompt_md, - ], - ) - - followup_submit_btn.click( - fn=_submit_followup_feedback, - inputs=[ - followup_input, - feedback_rating, - original_feedback_text_state, - last_sql_state, - last_rag_state, - last_question_state, - last_answer_state, - last_df_state, - attempts_state, - ], - outputs=[ - answer_out, - table_out, - last_sql_state, - last_rag_state, - last_question_state, - last_answer_state, - last_df_state, - original_feedback_text_state, - followup_prompt_md, - followup_input, - followup_submit_btn, - attempts_state, - attempts_display, - # UI updates returned at the end of function: - feedback_comment, - feedback_rating, - feedback_btn, - followup_input, - followup_submit_btn, - followup_prompt_md, - ], - ) -app = demo - - -# %% -if __name__ == "__main__": - import os - demo.launch( - server_name = "0.0.0.0", - server_port = int(os.getenv("PORT", 7860)) - ) -