# database.py import sqlite3 import os from logging_config import logger from datetime import datetime from session import get_session_id DB_NAME = "/tmp/conversations.db" def init_db(DB_NAME): """Initialize the SQLite database if it doesn't exist.""" logger.info(f"Initializing database at: {DB_NAME}") try: # Ensure the directory for the database file exists db_directory = os.path.dirname(DB_NAME) if not os.path.exists(db_directory): logger.info(f"Directory {db_directory} does not exist. Creating it.") os.makedirs(db_directory) # Ensure database file exists if not os.path.exists(DB_NAME): logger.info(f"{DB_NAME} not found. Creating a new database file.") open(DB_NAME, 'w').close() # Create an empty file # Connect to the database and initialize the table conn = sqlite3.connect(DB_NAME) c = conn.cursor() c.execute(''' CREATE TABLE IF NOT EXISTS conversations ( id INTEGER PRIMARY KEY AUTOINCREMENT, role TEXT NOT NULL, content TEXT NOT NULL, timestamp TEXT NOT NULL, session_id TEXT NOT NULL ) ''') conn.commit() logger.info("Conversations table ensured/created successfully.") except sqlite3.Error as e: logger.error(f"Error initializing database: {e}") raise finally: if 'conn' in locals(): conn.close() logger.info("Database connection closed.") def add_message(role, content, session_id): #added session_id here see if impacts functionality """ Add a message (user/assistant) to the database. Args: role (str): Role of the message sender (e.g., 'user', 'assistant'). content (str): Content of the message. """ session_id = get_session_id() logger.info(f"Adding message: role={role}, session_id={session_id}, content length={len(content)}") # Validate inputs if not role or not isinstance(role, str): logger.error("Invalid role provided. Must be a non-empty string.") raise ValueError("Role must be a non-empty string.") if not content or not isinstance(content, str): logger.error("Invalid content provided. Must be a non-empty string.") raise ValueError("Content must be a non-empty string.") try: with sqlite3.connect(DB_NAME) as conn: c = conn.cursor() # Insert the message c.execute("INSERT INTO conversations (role, content, timestamp, session_id) VALUES (?, ?, ?, ?)", (role, content, datetime.now().isoformat(), session_id)) conn.commit() # Retrieve the ID of the inserted row message_id = c.lastrowid logger.info(f"Message successfully added: id={message_id}, role={role}, content length={len(content)}") except sqlite3.Error as e: logger.error(f"Error adding message to database: {e}") raise def load_messages(session_id):#added session_id checking for functionality """ Load all messages from the database, filter by session ID. Returns: list: A list of dictionaries with each message's role and content. """ session_id = get_session_id() logger.info(f"Loading messages for session_id={session_id}") try: with sqlite3.connect(DB_NAME) as conn: c = conn.cursor() c.execute( "SELECT role, content FROM conversations WHERE session_id = ? ORDER BY id ASC", (session_id,) ) rows = c.fetchall() # Transform rows into a list of dictionaries messages = [{"role": r, "content": cnt} for (r, cnt) in rows] logger.info(f"Successfully loaded {len(messages)} messages from the database.") return messages except sqlite3.Error as e: logger.error(f"Error loading messages from database: {e}") raise