import pandas as pd import streamlit as st from typing import Optional, Callable, Any, Dict import logging logger = logging.getLogger(__name__) def _ensure_table(get_conn: Callable[[], Any]) -> None: try: with get_conn() as conn: conn.execute( """ CREATE TABLE IF NOT EXISTS chat_conversations ( id INTEGER PRIMARY KEY AUTOINCREMENT, chat_id INTEGER, user_id INTEGER, question TEXT, answer TEXT, kind TEXT, sql TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """ ) conn.commit() except Exception as e: logger.warning("ensure_table failed: %s", e) def save_conversation(get_conn: Callable[[], Any], chat_id: Optional[int], user_id: Optional[int], question: str, out: Dict): """Persist a Q/A turn into chat_conversations and enforce last-10 per user.""" try: _ensure_table(get_conn) # Derive assistant bubble text ans = None kind = None sql_text = None queries = list(out.get("queries") or []) primary = queries[0] if queries else {} for c in queries: if str(c.get("kind","")).lower() in ("non_sql","generic"): primary = c; break kind = (str(primary.get("kind") or "").lower() or None) df = primary.get("df") if isinstance(primary.get("df"), pd.DataFrame) else None if kind in ("non_sql","generic"): if isinstance(df, pd.DataFrame) and "message" in df.columns and not df.empty: try: ans = str(df["message"].iloc[0]) except Exception: ans = None if not ans: ans = (out.get("plan") or {}).get("explanation_display") elif kind == "select": try: n = 0 if df is None else int(len(df)) except Exception: n = 0 ans = f"Returned {n} row(s)." else: rows = None if isinstance(df, pd.DataFrame): for col in ("rows_affected","rows"): if col in df.columns and not df.empty: try: rows = int(df[col].iloc[0]); break except Exception: pass ans = "Query executed." if rows is None else f"Query executed. Rows affected: {rows}" for c in queries: t = (c.get("secured") or c.get("original") or "").strip() if t: sql_text = t; break with get_conn() as conn: conn.execute( "INSERT INTO chat_conversations (chat_id, user_id, question, answer, kind, sql) VALUES (?, ?, ?, ?, ?, ?)", (chat_id, user_id, question, ans, kind, sql_text) ) # enforce last 10 per user if user_id is not None: conn.execute( """ DELETE FROM chat_conversations WHERE user_id = ? AND id NOT IN ( SELECT id FROM chat_conversations WHERE user_id = ? ORDER BY id DESC LIMIT 10 ) """, (user_id, user_id) ) conn.commit() except Exception as e: logger.warning("save_conversation failed: %s", e) @st.cache_data(show_spinner=False, ttl=30) def get_recent_conversations(get_conn: Callable[[], Any], user_id: int, limit: int = 10) -> pd.DataFrame: try: _ensure_table(get_conn) with get_conn() as conn: return pd.read_sql_query( """ SELECT id, created_at, question, answer, kind FROM chat_conversations WHERE user_id = ? ORDER BY id DESC LIMIT ? """, conn, params=[user_id, int(limit)] ) except Exception as e: logger.warning("get_recent_conversations failed: %s", e) return pd.DataFrame(columns=["id","created_at","question","answer","kind"])