"""SQLite storage for conversations, messages, and feedback. Schema: - conversations: per-user chat sessions with auto-generated titles - messages: every user/assistant turn with citations - feedback: thumbs up/down + optional comment per assistant message For HF Spaces free tier the DB lives on container-local disk and is wiped when the Space sleeps/restarts. For real persistence: enable HF Persistent Storage and set CHROMA_DIR=/data/* (the same volume holds the SQLite file). """ from __future__ import annotations import json import sqlite3 import threading import uuid from contextlib import contextmanager from dataclasses import dataclass from datetime import datetime from pathlib import Path from app.core.config import settings _LOCK = threading.Lock() _DB_PATH = Path(settings.chroma_dir).parent / "qdb.db" @dataclass class Conversation: id: str user_email: str title: str created_at: str updated_at: str message_count: int = 0 @dataclass class Message: id: str conversation_id: str role: str # 'user' or 'assistant' content: str citations: list[dict] created_at: str feedback: int | None = None # +1, -1, or None @contextmanager def _conn(): _DB_PATH.parent.mkdir(parents=True, exist_ok=True) c = sqlite3.connect(str(_DB_PATH)) c.row_factory = sqlite3.Row try: yield c c.commit() finally: c.close() def init_db() -> None: """Create tables if they don't exist. Safe to call repeatedly.""" with _LOCK, _conn() as c: c.executescript( """ CREATE TABLE IF NOT EXISTS conversations ( id TEXT PRIMARY KEY, user_email TEXT NOT NULL, title TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_conv_user ON conversations(user_email, updated_at DESC); CREATE TABLE IF NOT EXISTS messages ( id TEXT PRIMARY KEY, conversation_id TEXT NOT NULL, role TEXT NOT NULL, content TEXT NOT NULL, citations TEXT, created_at TEXT NOT NULL, FOREIGN KEY (conversation_id) REFERENCES conversations(id) ON DELETE CASCADE ); CREATE INDEX IF NOT EXISTS idx_msg_conv ON messages(conversation_id, created_at); CREATE TABLE IF NOT EXISTS feedback ( id TEXT PRIMARY KEY, message_id TEXT NOT NULL, user_email TEXT NOT NULL, rating INTEGER NOT NULL, comment TEXT, created_at TEXT NOT NULL, UNIQUE(message_id, user_email), FOREIGN KEY (message_id) REFERENCES messages(id) ON DELETE CASCADE ); """ ) # ---------------- Conversations ---------------- def create_conversation(user_email: str, title: str = "محادثة جديدة") -> str: cid = str(uuid.uuid4()) now = datetime.utcnow().isoformat() with _LOCK, _conn() as c: c.execute( "INSERT INTO conversations (id, user_email, title, created_at, updated_at) VALUES (?, ?, ?, ?, ?)", (cid, user_email, title, now, now), ) return cid def update_conversation_title(conversation_id: str, title: str) -> None: with _LOCK, _conn() as c: c.execute( "UPDATE conversations SET title=?, updated_at=? WHERE id=?", (title[:100], datetime.utcnow().isoformat(), conversation_id), ) def list_conversations(user_email: str, limit: int = 50) -> list[Conversation]: with _LOCK, _conn() as c: rows = c.execute( """ SELECT c.*, (SELECT COUNT(*) FROM messages m WHERE m.conversation_id=c.id) AS cnt FROM conversations c WHERE user_email=? ORDER BY updated_at DESC LIMIT ? """, (user_email, limit), ).fetchall() return [ Conversation( id=r["id"], user_email=r["user_email"], title=r["title"], created_at=r["created_at"], updated_at=r["updated_at"], message_count=r["cnt"], ) for r in rows ] def delete_conversation(conversation_id: str) -> None: with _LOCK, _conn() as c: c.execute("DELETE FROM conversations WHERE id=?", (conversation_id,)) # ---------------- Messages ---------------- def add_message( conversation_id: str, role: str, content: str, citations: list[dict] | None = None, ) -> str: mid = str(uuid.uuid4()) now = datetime.utcnow().isoformat() with _LOCK, _conn() as c: c.execute( "INSERT INTO messages (id, conversation_id, role, content, citations, created_at) VALUES (?, ?, ?, ?, ?, ?)", (mid, conversation_id, role, content, json.dumps(citations or [], ensure_ascii=False), now), ) c.execute("UPDATE conversations SET updated_at=? WHERE id=?", (now, conversation_id)) return mid def get_messages(conversation_id: str) -> list[Message]: with _LOCK, _conn() as c: rows = c.execute( """ SELECT m.*, (SELECT rating FROM feedback f WHERE f.message_id=m.id LIMIT 1) AS rating FROM messages m WHERE conversation_id=? ORDER BY created_at """, (conversation_id,), ).fetchall() out: list[Message] = [] for r in rows: try: cites = json.loads(r["citations"]) if r["citations"] else [] except json.JSONDecodeError: cites = [] out.append( Message( id=r["id"], conversation_id=r["conversation_id"], role=r["role"], content=r["content"], citations=cites, created_at=r["created_at"], feedback=r["rating"], ) ) return out def get_recent_turns(conversation_id: str, limit: int = 6) -> list[dict]: """Return the last N user/assistant pairs as plain dicts for prompting.""" msgs = get_messages(conversation_id) return [{"role": m.role, "content": m.content} for m in msgs[-limit:]] # ---------------- Feedback ---------------- def set_feedback(message_id: str, user_email: str, rating: int, comment: str = "") -> None: """rating: +1 (👍) or -1 (👎). Re-rating same message overwrites.""" fid = str(uuid.uuid4()) now = datetime.utcnow().isoformat() with _LOCK, _conn() as c: c.execute( """ INSERT INTO feedback (id, message_id, user_email, rating, comment, created_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(message_id, user_email) DO UPDATE SET rating=excluded.rating, comment=excluded.comment, created_at=excluded.created_at """, (fid, message_id, user_email, rating, comment, now), ) # ---------------- Analytics ---------------- def total_conversations() -> int: with _LOCK, _conn() as c: return c.execute("SELECT COUNT(*) FROM conversations").fetchone()[0] def total_messages() -> int: with _LOCK, _conn() as c: return c.execute("SELECT COUNT(*) FROM messages").fetchone()[0] def feedback_summary() -> dict: with _LOCK, _conn() as c: pos = c.execute("SELECT COUNT(*) FROM feedback WHERE rating > 0").fetchone()[0] neg = c.execute("SELECT COUNT(*) FROM feedback WHERE rating < 0").fetchone()[0] return {"positive": pos, "negative": neg, "total": pos + neg} def top_questions(limit: int = 20) -> list[tuple[str, int]]: """Return user questions grouped by content (case-sensitive for now).""" with _LOCK, _conn() as c: rows = c.execute( """ SELECT content, COUNT(*) AS n FROM messages WHERE role='user' GROUP BY content ORDER BY n DESC, content LIMIT ? """, (limit,), ).fetchall() return [(r["content"], r["n"]) for r in rows] def low_rated_messages(limit: int = 20) -> list[Message]: """Assistant messages with at least one negative rating.""" with _LOCK, _conn() as c: rows = c.execute( """ SELECT m.*, MIN(f.rating) AS rating FROM messages m JOIN feedback f ON f.message_id = m.id WHERE m.role='assistant' AND f.rating < 0 GROUP BY m.id ORDER BY m.created_at DESC LIMIT ? """, (limit,), ).fetchall() out = [] for r in rows: try: cites = json.loads(r["citations"]) if r["citations"] else [] except json.JSONDecodeError: cites = [] out.append(Message( id=r["id"], conversation_id=r["conversation_id"], role=r["role"], content=r["content"], citations=cites, created_at=r["created_at"], feedback=r["rating"], )) return out