Spaces:
Sleeping
Sleeping
added session id for conversation history
Browse files
app.py
CHANGED
|
@@ -11,6 +11,8 @@ from logging.handlers import RotatingFileHandler
|
|
| 11 |
from transformers import pipeline
|
| 12 |
import tiktoken
|
| 13 |
import os
|
|
|
|
|
|
|
| 14 |
|
| 15 |
# -----------------------
|
| 16 |
# Configuration and Setup
|
|
@@ -76,6 +78,20 @@ DB_NAME = "./logs/conversations.db"
|
|
| 76 |
# Helper Functions
|
| 77 |
# -----------------------
|
| 78 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
def init_db():
|
| 80 |
"""Initialize the SQLite database if it doesn't exist."""
|
| 81 |
logger.info(f"Initializing database at: {DB_NAME}")
|
|
@@ -93,7 +109,8 @@ def init_db():
|
|
| 93 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 94 |
role TEXT NOT NULL,
|
| 95 |
content TEXT NOT NULL,
|
| 96 |
-
timestamp TEXT NOT NULL
|
|
|
|
| 97 |
)
|
| 98 |
''')
|
| 99 |
conn.commit()
|
|
@@ -114,8 +131,9 @@ def add_message(role, content):
|
|
| 114 |
role (str): Role of the message sender (e.g., 'user', 'assistant').
|
| 115 |
content (str): Content of the message.
|
| 116 |
"""
|
| 117 |
-
|
| 118 |
-
|
|
|
|
| 119 |
# Validate inputs
|
| 120 |
if not role or not isinstance(role, str):
|
| 121 |
logger.error("Invalid role provided. Must be a non-empty string.")
|
|
@@ -129,8 +147,8 @@ def add_message(role, content):
|
|
| 129 |
c = conn.cursor()
|
| 130 |
|
| 131 |
# Insert the message
|
| 132 |
-
c.execute("INSERT INTO conversations (role, content, timestamp) VALUES (?, ?, ?)",
|
| 133 |
-
(role, content, datetime.now().isoformat()))
|
| 134 |
conn.commit()
|
| 135 |
|
| 136 |
# Retrieve the ID of the inserted row
|
|
@@ -143,17 +161,21 @@ def add_message(role, content):
|
|
| 143 |
|
| 144 |
def load_messages():
|
| 145 |
"""
|
| 146 |
-
Load all messages from the database.
|
| 147 |
|
| 148 |
Returns:
|
| 149 |
list: A list of dictionaries with each message's role and content.
|
| 150 |
"""
|
| 151 |
-
|
|
|
|
| 152 |
|
| 153 |
try:
|
| 154 |
with sqlite3.connect(DB_NAME) as conn:
|
| 155 |
c = conn.cursor()
|
| 156 |
-
c.execute(
|
|
|
|
|
|
|
|
|
|
| 157 |
rows = c.fetchall()
|
| 158 |
|
| 159 |
# Transform rows into a list of dictionaries
|
|
@@ -254,6 +276,8 @@ def build_prompt(user_query, retrieved_chunks, messages):
|
|
| 254 |
socratic_guide = st.secrets["SOCRATIC_GUIDE"]
|
| 255 |
prometheus_prompt = st.secrets["PROMETHEUS_PROMPT"]
|
| 256 |
logger.info("Successfully loaded system prompts from secrets.")
|
|
|
|
|
|
|
| 257 |
except KeyError as e:
|
| 258 |
logger.error(f"Missing key in secrets.toml: {e}")
|
| 259 |
raise ValueError(f"Missing secret key: {e}")
|
|
@@ -399,7 +423,12 @@ def send_query_to_llm(messages):
|
|
| 399 |
# Streamlit UI
|
| 400 |
# -----------------------
|
| 401 |
|
| 402 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 403 |
|
| 404 |
@st.cache_resource
|
| 405 |
def load_retriever():
|
|
|
|
| 11 |
from transformers import pipeline
|
| 12 |
import tiktoken
|
| 13 |
import os
|
| 14 |
+
import uuid
|
| 15 |
+
import hashlib
|
| 16 |
|
| 17 |
# -----------------------
|
| 18 |
# Configuration and Setup
|
|
|
|
| 78 |
# Helper Functions
|
| 79 |
# -----------------------
|
| 80 |
|
| 81 |
+
def get_session_id():
|
| 82 |
+
"""
|
| 83 |
+
Generate a session ID using either IP address (hashed) or a UUID.
|
| 84 |
+
This ensures user-specific chat sessions.
|
| 85 |
+
"""
|
| 86 |
+
if session_id not in st.session_state:
|
| 87 |
+
# Log session initialization
|
| 88 |
+
logger.info("Session ID not found in session state. Generating a new session ID.")
|
| 89 |
+
# Fallback to UUID if IP-based identification isn't implemented
|
| 90 |
+
st.session_state.session_id = str(uuid.uuid4())
|
| 91 |
+
session_id = st.session_state.session_id
|
| 92 |
+
logger.info(f"Session ID: {session_id}")
|
| 93 |
+
return session_id
|
| 94 |
+
|
| 95 |
def init_db():
|
| 96 |
"""Initialize the SQLite database if it doesn't exist."""
|
| 97 |
logger.info(f"Initializing database at: {DB_NAME}")
|
|
|
|
| 109 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 110 |
role TEXT NOT NULL,
|
| 111 |
content TEXT NOT NULL,
|
| 112 |
+
timestamp TEXT NOT NULL,
|
| 113 |
+
session_id TEXT NOT NULL
|
| 114 |
)
|
| 115 |
''')
|
| 116 |
conn.commit()
|
|
|
|
| 131 |
role (str): Role of the message sender (e.g., 'user', 'assistant').
|
| 132 |
content (str): Content of the message.
|
| 133 |
"""
|
| 134 |
+
session_id = get_session_id()
|
| 135 |
+
logger.info(f"Adding message: role={role}, session_id={session_id}, content length={len(content)}")
|
| 136 |
+
|
| 137 |
# Validate inputs
|
| 138 |
if not role or not isinstance(role, str):
|
| 139 |
logger.error("Invalid role provided. Must be a non-empty string.")
|
|
|
|
| 147 |
c = conn.cursor()
|
| 148 |
|
| 149 |
# Insert the message
|
| 150 |
+
c.execute("INSERT INTO conversations (role, content, timestamp, session_id) VALUES (?, ?, ?, ?)",
|
| 151 |
+
(role, content, datetime.now().isoformat(), session_id))
|
| 152 |
conn.commit()
|
| 153 |
|
| 154 |
# Retrieve the ID of the inserted row
|
|
|
|
| 161 |
|
| 162 |
def load_messages():
|
| 163 |
"""
|
| 164 |
+
Load all messages from the database, filter by session ID.
|
| 165 |
|
| 166 |
Returns:
|
| 167 |
list: A list of dictionaries with each message's role and content.
|
| 168 |
"""
|
| 169 |
+
session_id = get_session_id()
|
| 170 |
+
logger.info(f"Loading messages for session_id={session_id}")
|
| 171 |
|
| 172 |
try:
|
| 173 |
with sqlite3.connect(DB_NAME) as conn:
|
| 174 |
c = conn.cursor()
|
| 175 |
+
c.execute(
|
| 176 |
+
"SELECT role, content FROM conversations WHERE session_id = ? ORDER BY id ASC",
|
| 177 |
+
(session_id,)
|
| 178 |
+
)
|
| 179 |
rows = c.fetchall()
|
| 180 |
|
| 181 |
# Transform rows into a list of dictionaries
|
|
|
|
| 276 |
socratic_guide = st.secrets["SOCRATIC_GUIDE"]
|
| 277 |
prometheus_prompt = st.secrets["PROMETHEUS_PROMPT"]
|
| 278 |
logger.info("Successfully loaded system prompts from secrets.")
|
| 279 |
+
logger.info(f"Socratic guide:\n{socratic_guide}")
|
| 280 |
+
logger.info(f"Prometheus prompt:\n{prometheus_prompt}")
|
| 281 |
except KeyError as e:
|
| 282 |
logger.error(f"Missing key in secrets.toml: {e}")
|
| 283 |
raise ValueError(f"Missing secret key: {e}")
|
|
|
|
| 423 |
# Streamlit UI
|
| 424 |
# -----------------------
|
| 425 |
|
| 426 |
+
try:
|
| 427 |
+
init_db() # Ensure DB is ready
|
| 428 |
+
logger.info("DB initialized successfully.")
|
| 429 |
+
except Exception as e:
|
| 430 |
+
logger.error(f"Failed to initialize DB: {e}")
|
| 431 |
+
raise ValueError("Failed to initialize DB.")
|
| 432 |
|
| 433 |
@st.cache_resource
|
| 434 |
def load_retriever():
|