import os import json import uuid import pymysql from typing import Optional, List, Dict, Any from urllib.parse import urlparse # Default TiDB / MySQL URI provided DEFAULT_DB_URI = os.getenv( "DATABASE_URL", "mysql://5fxLTeA3XBn76L2.root:bxxGgvOPDMT7mAun@gateway01.ap-southeast-1.prod.aws.tidbcloud.com:4000/test" ) def get_connection(): parsed = urlparse(DEFAULT_DB_URI) user = parsed.username password = parsed.password host = parsed.hostname port = parsed.port or 4000 db = parsed.path.lstrip("/") or "test" return pymysql.connect( host=host, port=port, user=user, password=password, database=db, ssl_verify_cert=False, autocommit=True, charset="utf8mb4", cursorclass=pymysql.cursors.DictCursor ) def init_db(): try: conn = get_connection() with conn.cursor() as cursor: # Create users table (simple name and username) cursor.execute(""" CREATE TABLE IF NOT EXISTS users ( username VARCHAR(64) PRIMARY KEY, name VARCHAR(128) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); """) # Create sessions table cursor.execute(""" CREATE TABLE IF NOT EXISTS sessions ( id VARCHAR(64) PRIMARY KEY, username VARCHAR(64), title VARCHAR(255) NOT NULL, model VARCHAR(128), chapter_filter VARCHAR(128), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, INDEX (username) ); """) # Ensure username column exists in sessions if table already existed try: cursor.execute("ALTER TABLE sessions ADD COLUMN username VARCHAR(64);") except Exception: pass # Create messages table cursor.execute(""" CREATE TABLE IF NOT EXISTS messages ( id INT AUTO_INCREMENT PRIMARY KEY, session_id VARCHAR(64) NOT NULL, role VARCHAR(32) NOT NULL, content MEDIUMTEXT NOT NULL, thinking MEDIUMTEXT, findings JSON, citations JSON, `usage` JSON, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, INDEX (session_id) ); """) conn.close() print("TiDB database tables initialized successfully.") except Exception as e: print(f"Warning: Failed to initialize TiDB database: {e}") # Run schema setup init_db() def get_user(username: str) -> Optional[Dict[str, Any]]: username = username.strip().lower() try: conn = get_connection() with conn.cursor() as cursor: cursor.execute("SELECT username, name, created_at FROM users WHERE username = %s;", (username,)) user = cursor.fetchone() conn.close() return user except Exception as e: print(f"Error in get_user: {e}") return None def create_user(username: str, name: Optional[str] = None) -> Dict[str, Any]: username = username.strip().lower() disp_name = (name or username).strip() if not username: raise ValueError("Username cannot be empty") try: conn = get_connection() with conn.cursor() as cursor: cursor.execute("SELECT username, name, created_at FROM users WHERE username = %s;", (username,)) existing = cursor.fetchone() if existing: conn.close() raise ValueError(f"Username '@{username}' is already taken. Please choose another username.") cursor.execute("INSERT INTO users (username, name) VALUES (%s, %s);", (username, disp_name)) conn.close() return {"username": username, "name": disp_name} except ValueError: raise except Exception as e: print(f"Database error creating user: {e}") raise RuntimeError(f"Database error creating user: {e}") def get_or_create_user(username: str, name: Optional[str] = None) -> Dict[str, Any]: username = username.strip().lower() disp_name = (name or username).strip() try: conn = get_connection() with conn.cursor() as cursor: cursor.execute("SELECT username, name, created_at FROM users WHERE username = %s;", (username,)) user = cursor.fetchone() if not user: cursor.execute("INSERT INTO users (username, name) VALUES (%s, %s);", (username, disp_name)) user = {"username": username, "name": disp_name} else: if name and name != user.get("name"): cursor.execute("UPDATE users SET name = %s WHERE username = %s;", (disp_name, username)) user["name"] = disp_name conn.close() return user except Exception as e: print(f"Error in get_or_create_user: {e}") return {"username": username, "name": disp_name} def create_session(session_id: Optional[str] = None, username: Optional[str] = None, title: str = "New Chat", model: Optional[str] = None, chapter_filter: Optional[str] = "All") -> str: sid = session_id or str(uuid.uuid4())[:12] try: conn = get_connection() with conn.cursor() as cursor: cursor.execute(""" INSERT INTO sessions (id, username, title, model, chapter_filter) VALUES (%s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE updated_at = CURRENT_TIMESTAMP; """, (sid, username, title[:250], model, chapter_filter)) conn.close() except Exception as e: print(f"Error in create_session: {e}") return sid def update_session_title_if_default(session_id: str, new_title: str): try: conn = get_connection() with conn.cursor() as cursor: cursor.execute("SELECT title FROM sessions WHERE id = %s", (session_id,)) row = cursor.fetchone() if row and (row["title"] == "New Chat" or not row["title"]): cursor.execute("UPDATE sessions SET title = %s WHERE id = %s", (new_title[:250], session_id)) conn.close() except Exception as e: print(f"Error in update_session_title_if_default: {e}") def list_sessions(username: Optional[str] = None, limit: int = 50) -> List[Dict[str, Any]]: try: conn = get_connection() with conn.cursor() as cursor: if username: cursor.execute(""" SELECT id, username, title, model, chapter_filter, created_at, updated_at FROM sessions WHERE username = %s ORDER BY updated_at DESC LIMIT %s; """, (username.strip().lower(), limit)) else: cursor.execute(""" SELECT id, username, title, model, chapter_filter, created_at, updated_at FROM sessions ORDER BY updated_at DESC LIMIT %s; """, (limit,)) rows = cursor.fetchall() conn.close() # Convert timestamps to iso strings for r in rows: if r.get("created_at"): r["created_at"] = r["created_at"].isoformat() if r.get("updated_at"): r["updated_at"] = r["updated_at"].isoformat() return rows except Exception as e: print(f"Error in list_sessions: {e}") return [] def get_session(session_id: str) -> Optional[Dict[str, Any]]: try: conn = get_connection() with conn.cursor() as cursor: cursor.execute("SELECT id, username, title, model, chapter_filter, created_at, updated_at FROM sessions WHERE id = %s", (session_id,)) session = cursor.fetchone() if not session: conn.close() return None if session.get("created_at"): session["created_at"] = session["created_at"].isoformat() if session.get("updated_at"): session["updated_at"] = session["updated_at"].isoformat() cursor.execute(""" SELECT role, content, thinking, findings, citations, `usage`, created_at FROM messages WHERE session_id = %s ORDER BY id ASC; """, (session_id,)) messages = cursor.fetchall() for m in messages: if m.get("created_at"): m["created_at"] = m["created_at"].isoformat() for json_col in ["findings", "citations", "usage"]: if isinstance(m.get(json_col), str): try: m[json_col] = json.loads(m[json_col]) except Exception: pass session["messages"] = messages conn.close() return session except Exception as e: print(f"Error in get_session: {e}") return None def save_message( session_id: str, role: str, content: str, thinking: Optional[str] = None, findings: Optional[Any] = None, citations: Optional[Any] = None, usage: Optional[Any] = None ): try: conn = get_connection() with conn.cursor() as cursor: cursor.execute(""" INSERT INTO messages (session_id, role, content, thinking, findings, citations, `usage`) VALUES (%s, %s, %s, %s, %s, %s, %s); """, ( session_id, role, content, thinking, json.dumps(findings) if findings is not None else None, json.dumps(citations) if citations is not None else None, json.dumps(usage) if usage is not None else None, )) # Also update session updated_at cursor.execute("UPDATE sessions SET updated_at = CURRENT_TIMESTAMP WHERE id = %s;", (session_id,)) conn.close() except Exception as e: print(f"Error in save_message: {e}") def delete_session(session_id: str) -> bool: """Delete a session and all its messages. Returns True on success.""" try: conn = get_connection() with conn.cursor() as cursor: cursor.execute("DELETE FROM messages WHERE session_id = %s;", (session_id,)) cursor.execute("DELETE FROM sessions WHERE id = %s;", (session_id,)) conn.close() return True except Exception as e: print(f"Error in delete_session: {e}") return False def compact_session_messages(session_id: str, keep_last: int = 2) -> bool: """ Failsafe compaction: Condenses older messages in a session, keeping only the last `keep_last` user/assistant pairs plus a compact summary note. """ try: conn = get_connection() with conn.cursor() as cursor: cursor.execute(""" SELECT id, role, content FROM messages WHERE session_id = %s ORDER BY id ASC; """, (session_id,)) rows = cursor.fetchall() if len(rows) <= keep_last * 2: conn.close() return True # Keep the last keep_last * 2 rows keep_rows = rows[-(keep_last * 2):] keep_ids = [r["id"] for r in keep_rows] # Collect topic highlights from pruned user messages pruned_user_topics = [ r["content"][:60].strip() for r in rows[:-(keep_last * 2)] if r["role"] == "user" ] topics_summary = " • ".join(pruned_user_topics) if pruned_user_topics else "Earlier inquiries" # Delete older rows cursor.execute(""" DELETE FROM messages WHERE session_id = %s AND id NOT IN ({seq}); """.format(seq=",".join(["%s"] * len(keep_ids))), (session_id, *keep_ids)) # Insert an archived summary marker cursor.execute(""" INSERT INTO messages (session_id, role, content, thinking) VALUES (%s, %s, %s, %s); """, ( session_id, "assistant", f"🗜️ *[Conversation Compacted: Context preserved for {len(pruned_user_topics)} prior topics ({topics_summary}) to optimize token window and responsiveness]*", "Conversation history was compacted to prevent token overflow and context bleeding." )) cursor.execute("UPDATE sessions SET updated_at = CURRENT_TIMESTAMP WHERE id = %s;", (session_id,)) conn.close() return True except Exception as e: print(f"Error in compact_session_messages: {e}") return False