tbels89 commited on
Commit
f80362a
·
1 Parent(s): 552936e

v1.0 new modular format

Browse files
Files changed (12) hide show
  1. api_client.py +56 -0
  2. app.py +39 -464
  3. curriculum.py +34 -0
  4. database.py +109 -0
  5. generator.py +1 -0
  6. get_csv.py +36 -0
  7. logging_config.py +25 -0
  8. prompt.py +75 -0
  9. retriever.py +15 -1
  10. session.py +21 -0
  11. summarizer.py +71 -0
  12. token_counter.py +48 -0
api_client.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # api_client.py
2
+
3
+ from logging_config import logger
4
+ from token_counter import count_tokens
5
+ from openai import OpenAI
6
+ import streamlit as st
7
+
8
+ # Model selection (add settings here and log)
9
+ MODEL_NAME = "gpt-4o-mini"
10
+ temperature = 0.3
11
+ logger.info(f"Selected model: {MODEL_NAME}, temperature: {temperature}")
12
+
13
+ def send_query_to_llm(messages):
14
+ """
15
+ Send the constructed messages to the LLM and get a response.
16
+
17
+ Args:
18
+ messages (list): List of dictionaries forming the prompt for the LLM.
19
+
20
+ Returns:
21
+ str: The assistant's response or a fallback message if an error occurs.
22
+ """
23
+ try:
24
+ # Count input tokens
25
+ token_data = count_tokens(messages, "o200k_base")
26
+ logger.info(f"Input prompt tokens: {token_data['total']}")
27
+ logger.info(f"Token breakdown (input): {token_data['by_role']}")
28
+
29
+ # Initialize OpenAI client
30
+ client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"])
31
+
32
+ # Send prompt to LLM
33
+ logger.info(f"Sending query to model: {MODEL_NAME}")
34
+ completion = client.chat.completions.create(
35
+ model=MODEL_NAME,
36
+ messages=messages,
37
+ temperature=temperature
38
+ )
39
+
40
+ # Extract assistant's response
41
+ assistant_response = completion.choices[0].message.content
42
+ #logger.info(f"Assistant response: {assistant_response}")
43
+
44
+ # Count output tokens
45
+ output_token_data = count_tokens([{"role": "assistant", "content": assistant_response}], "o200k_base")
46
+ logger.info(f"Assistant response output tokens: {output_token_data['total']}")
47
+
48
+ return assistant_response
49
+
50
+ except KeyError as e:
51
+ logger.error(f"Missing key in secrets or configuration: {e}")
52
+ return "Configuration error: Missing required API key or settings."
53
+
54
+ except Exception as e:
55
+ logger.error(f"Error communicating with OpenAI: {e}")
56
+ return "I'm sorry, I couldn't process your request at the moment."
app.py CHANGED
@@ -1,490 +1,49 @@
1
  # app.py
2
- # v0.3
3
 
 
4
  import streamlit as st
5
  import sqlite3
6
  from datetime import datetime
7
- from retriever import Retriever
8
- from openai import OpenAI
9
- import logging
10
- from logging.handlers import RotatingFileHandler
11
- from transformers import pipeline
12
- import tiktoken
13
- import os
14
- import uuid
15
- import json
16
- import pandas as pd
17
 
18
  # -----------------------
19
  # Configuration and Setup
20
  # -----------------------
21
 
22
- # Ensure the log file exists
23
- LOG_FILE_PATH = "./logs/app.log"
24
-
25
- if not os.path.exists(LOG_FILE_PATH):
26
- with open(LOG_FILE_PATH, 'w') as log_file:
27
- log_file.write("") # Create an empty file
28
-
29
  # Setup logging
30
- logging.basicConfig(
31
- level=logging.INFO,
32
- format='%(asctime)s %(levelname)s:%(name)s:%(funcName)s:%(message)s',
33
- handlers=[
34
- RotatingFileHandler(LOG_FILE_PATH, maxBytes=5*1024*1024, backupCount=3),
35
- logging.StreamHandler()
36
- ]
37
- )
38
- logger = logging.getLogger(__name__)
39
-
40
- # Test logging
41
  logger.info(f"Logging setup initialized successfully at {datetime.now().isoformat()}.")
42
 
43
- def load_curriculum(file_path):
44
- """
45
- Reads the curriculum text file and returns its content as a string.
46
-
47
- Args:
48
- file_path (str): Path to the text file.
49
-
50
- Returns:
51
- str: Contents of the text file.
52
- """
53
- logger.info(f"Attempting to load curriculum from: {file_path}")
54
-
55
- try:
56
- with open(file_path, 'r', encoding='utf-8') as file:
57
- content = file.read().strip()
58
- logger.info(f"Successfully loaded curriculum. Content length: {len(content)} characters.")
59
- return content
60
- except FileNotFoundError:
61
- logger.error(f"The curriculum file '{file_path}' does not exist.")
62
- return "Curriculum file not found. Please ensure the file is in the specified location."
63
- except Exception as e:
64
- logger.error(f"Error reading the curriculum file: {e}")
65
- return "An error occurred while loading the curriculum."
66
-
67
- # Define curriculum file path and load summary
68
- CURRICULUM_FILE_PATH = './data/curriculum.txt'
69
- logger.info(f"Initializing curriculum loading from path: {CURRICULUM_FILE_PATH}")
70
- CURRICULUM_SUMMARY = load_curriculum(CURRICULUM_FILE_PATH)
71
- logger.info("Curriculum loading complete.")
72
-
73
- # Set up model, retriever chunks, conversation db
74
- MODEL_NAME = "gpt-4o-mini"
75
- TOP_K = 3 # number of chunks to retrieve
76
- DB_NAME = "/tmp/conversations.db"
77
-
78
- # -----------------------
79
- # Helper Functions
80
- # -----------------------
81
-
82
- def get_session_id():
83
- """
84
- Generate a session ID using a UUID and store it in Streamlit's session state.
85
- Ensures user-specific chat sessions.
86
- """
87
- if "session_id" not in st.session_state:
88
- # Log session initialization
89
- logger.info("Session ID not found in session state. Generating a new session ID.")
90
- # Generate a new UUID and assign it to session state
91
- st.session_state["session_id"] = str(uuid.uuid4())
92
- logger.info(f"Generated new session ID: {st.session_state['session_id']}")
93
- else:
94
- logger.info(f"Using existing session ID: {st.session_state['session_id']}")
95
-
96
- # Return the session ID from session state
97
- return st.session_state["session_id"]
98
-
99
-
100
- def init_db():
101
- """Initialize the SQLite database if it doesn't exist."""
102
- logger.info(f"Initializing database at: {DB_NAME}")
103
- try:
104
- # Ensure the directory for the database file exists
105
- db_directory = os.path.dirname(DB_NAME)
106
- if not os.path.exists(db_directory):
107
- logger.info(f"Directory {db_directory} does not exist. Creating it.")
108
- os.makedirs(db_directory)
109
-
110
- # Ensure database file exists
111
- if not os.path.exists(DB_NAME):
112
- logger.info(f"{DB_NAME} not found. Creating a new database file.")
113
- open(DB_NAME, 'w').close() # Create an empty file
114
-
115
- # Connect to the database and initialize the table
116
- conn = sqlite3.connect(DB_NAME)
117
- c = conn.cursor()
118
- c.execute('''
119
- CREATE TABLE IF NOT EXISTS conversations (
120
- id INTEGER PRIMARY KEY AUTOINCREMENT,
121
- role TEXT NOT NULL,
122
- content TEXT NOT NULL,
123
- timestamp TEXT NOT NULL,
124
- session_id TEXT NOT NULL
125
- )
126
- ''')
127
- conn.commit()
128
- logger.info("Conversations table ensured/created successfully.")
129
- except sqlite3.Error as e:
130
- logger.error(f"Error initializing database: {e}")
131
- raise
132
- finally:
133
- if 'conn' in locals():
134
- conn.close()
135
- logger.info("Database connection closed.")
136
-
137
- def add_message(role, content):
138
- """
139
- Add a message (user/assistant) to the database.
140
-
141
- Args:
142
- role (str): Role of the message sender (e.g., 'user', 'assistant').
143
- content (str): Content of the message.
144
- """
145
- session_id = get_session_id()
146
- logger.info(f"Adding message: role={role}, session_id={session_id}, content length={len(content)}")
147
-
148
- # Validate inputs
149
- if not role or not isinstance(role, str):
150
- logger.error("Invalid role provided. Must be a non-empty string.")
151
- raise ValueError("Role must be a non-empty string.")
152
- if not content or not isinstance(content, str):
153
- logger.error("Invalid content provided. Must be a non-empty string.")
154
- raise ValueError("Content must be a non-empty string.")
155
-
156
- try: #these are being logged but are not being passed to database
157
- with sqlite3.connect(DB_NAME) as conn:
158
- c = conn.cursor()
159
-
160
- # Insert the message
161
- c.execute("INSERT INTO conversations (role, content, timestamp, session_id) VALUES (?, ?, ?, ?)",
162
- (role, content, datetime.now().isoformat(), session_id))
163
- conn.commit()
164
-
165
- # Retrieve the ID of the inserted row
166
- message_id = c.lastrowid
167
- logger.info(f"Message successfully added: id={message_id}, role={role}, content length={len(content)}")
168
- except sqlite3.Error as e:
169
- logger.error(f"Error adding message to database: {e}")
170
- raise
171
-
172
-
173
- def load_messages():
174
- """
175
- Load all messages from the database, filter by session ID.
176
-
177
- Returns:
178
- list: A list of dictionaries with each message's role and content.
179
- """
180
- session_id = get_session_id()
181
- logger.info(f"Loading messages for session_id={session_id}")
182
-
183
- try:
184
- with sqlite3.connect(DB_NAME) as conn:
185
- c = conn.cursor()
186
- c.execute(
187
- "SELECT role, content FROM conversations WHERE session_id = ? ORDER BY id ASC",
188
- (session_id,)
189
- )
190
- rows = c.fetchall()
191
-
192
- # Transform rows into a list of dictionaries
193
- messages = [{"role": r, "content": cnt} for (r, cnt) in rows]
194
- logger.info(f"Successfully loaded {len(messages)} messages from the database.")
195
- return messages
196
- except sqlite3.Error as e:
197
- logger.error(f"Error loading messages from database: {e}")
198
- raise
199
-
200
-
201
- @st.cache_resource
202
- def load_summarizer():
203
- """
204
- Load and cache the summarization pipeline.
205
- Designed for a CPU-only environment and uses Hugging Face-hosted models.
206
- """
207
- try:
208
- logger.info("Loading summarizer model on CPU...")
209
-
210
- # Initialize summarization pipeline on CPU
211
- summarizer = pipeline("summarization", model="facebook/bart-large-cnn", device=-1)
212
-
213
- logger.info("Summarizer model loaded successfully.")
214
- return summarizer
215
- except Exception as e:
216
- logger.error(f"Failed to load summarizer pipeline: {e}")
217
- st.error("The summarization model could not be loaded. Please try again later.")
218
- return None
219
-
220
- # Load summarizer model
221
- summarizer = load_summarizer()
222
-
223
-
224
- def truncate_and_summarize(messages, max_length=2500, min_length=250, recent_messages=20):
225
- """
226
- If conversation too long, summarize older messages.
227
-
228
- Args:
229
- messages (list): List of message dictionaries.
230
- max_length (int): Maximum length for the summary.
231
- min_length (int): Minimum length for the summary.
232
- recent_messages (int): Number of recent messages to keep intact.
233
-
234
- Returns:
235
- list: Updated list of messages with older ones summarized.
236
- """
237
- logger.info(f"Checking if summarization is needed. Total messages: {len(messages)}")
238
-
239
- if len(messages) <= recent_messages:
240
- logger.info("No summarization needed; message count within limit.")
241
- return messages
242
-
243
- # Split older and recent messages
244
- older = messages[:-recent_messages]
245
- recent = messages[-recent_messages:]
246
-
247
- # Combine older messages
248
- conversation_text = "\n".join([f"{m['role']}: {m['content']}" for m in older])
249
- summary_input = ("Summarize the following conversation concisely to act as assistant's memory:\n\n"
250
- + conversation_text)
251
-
252
- if summarizer:
253
- try:
254
- # Perform summarization
255
- logger.info("Performing summarization of older messages.")
256
- summary_result = summarizer(summary_input, max_length=max_length, min_length=min_length, do_sample=False)
257
- summary_text = summary_result[0]['summary_text'].strip()
258
- logger.info("Successfully summarized older conversation.")
259
-
260
- # Prepend the summarized message
261
- summarized = [{"role": "system", "content": "Summary of previous conversation: " + summary_text}]
262
- return summarized + recent
263
- except Exception as e:
264
- logger.error(f"Error during summarization: {e}")
265
- logger.warning("Returning messages without summarization.")
266
-
267
- logger.warning("Summarizer not available. Returning messages without summarization.")
268
- return messages
269
-
270
-
271
- def build_prompt(user_query, retrieved_chunks, messages):
272
- """
273
- Build the prompt for the LLM:
274
- - Include system prompts from secrets
275
- - Include the curriculum summary
276
- - Summarize older conversation history
277
- - Add retrieved chunks as system context
278
- - Include user query at the end
279
- """
280
- logger.info("Building prompt for the model.")
281
-
282
- # Summarize older messages if needed
283
- messages = truncate_and_summarize(messages)
284
-
285
- # Load system prompts from secrets
286
- try:
287
- socratic_guide = st.secrets["SOCRATIC_GUIDE"]
288
- prometheus_prompt = st.secrets["PROMETHEUS_PROMPT"]
289
- logger.info("Successfully loaded system prompts from secrets.")
290
- except KeyError as e:
291
- logger.error(f"Missing key in secrets.toml: {e}")
292
- raise ValueError(f"Missing secret key: {e}")
293
-
294
- # Initialize the prompt messages
295
- prompt_messages = []
296
-
297
- # Add the Socratic guide to the prompt
298
- prompt_messages.append({"role": "system", "content": socratic_guide})
299
-
300
- # Add the placeholder prompt to the prompt
301
- prompt_messages.append({"role": "system", "content": prometheus_prompt})
302
-
303
- # Include the curriculum summary
304
- curriculum_instructions = f"""
305
- Here are the learning goals for this class based on the TDSB's Curriculum. Ensure that your responses are aligned with these goals:\n
306
- {CURRICULUM_SUMMARY}
307
- """
308
- prompt_messages.append({"role": "system", "content": curriculum_instructions})
309
-
310
- # Add conversation history
311
- for m in messages:
312
- prompt_messages.append({"role": m["role"], "content": m["content"]})
313
-
314
- # Add retrieved chunks as system context
315
- if retrieved_chunks:
316
- chunks_text = "\n".join([f"Page {c['page_num']}:\n{c['content']}" for c in retrieved_chunks])
317
- retrieved_content_instruction = (
318
- "guide students toward understanding through thought-provoking questions while recognizing when they need factual clarity or binary responses to build foundational knowledge."
319
- "Your challenge is to discern when a student requires immediate factual support and when they are ready for open-ended exploration that fosters critical thinking, but have keep a slightly higher inclination to ask questions and provoke thought."
320
- "You must use the retrieved content to guide and position your responses and follow-up questions, relying solely on this information as your source of truth."
321
- "Do not use any other prior or external knowledge or make assumptions beyond the retrieved content provided below to respond to user queries. if the content is insufficient to answer the question, tell the student to consider consulting alternative resources. This dynamic approach ensures students develop both essential knowledge and the ability to reason critically and independently."
322
- "Retrieved chunks:"
323
- )
324
- prompt_messages.append({"role": "system", "content": retrieved_content_instruction + "\n" + chunks_text})
325
-
326
-
327
- # Add the user's query
328
- prompt_messages.append({"role": "user", "content": user_query})
329
-
330
- # Count tokens in the final prompt
331
- try:
332
- token_data = count_tokens(prompt_messages)
333
- logger.info(f"Total tokens for prompt: {token_data['total']}")
334
- logger.info(f"Token breakdown by role: {token_data['by_role']}")
335
- except Exception as e:
336
- logger.error(f"Error counting tokens: {e}")
337
- raise ValueError("Failed to count tokens for the prompt.")
338
-
339
- #logger.info("Prompt successfully built. Prompt messages: %s", json.dumps(prompt_messages, indent=4))
340
- return prompt_messages
341
-
342
-
343
- #Token counter
344
- def count_tokens(messages, encoding_name="o200k_base"):
345
- """
346
- Count the total number of tokens in a list of messages, including system prompts.
347
-
348
- Args:
349
- messages (list): List of message dictionaries with 'role' and 'content' keys.
350
- encoding_name (str): Encoding name for tokenization (default: "o200k_base").
351
-
352
- Returns:
353
- dict: Dictionary containing the total token count and a breakdown by role.
354
- """
355
- try:
356
- enc = tiktoken.get_encoding(encoding_name)
357
- logger.info(f"Using encoding: {encoding_name}")
358
- except Exception as e:
359
- logger.error(f"Failed to get encoding '{encoding_name}': {e}")
360
- raise ValueError(f"Invalid encoding: {encoding_name}")
361
-
362
- total_tokens = 0
363
- token_breakdown = {}
364
-
365
- try:
366
- for m in messages:
367
- if not isinstance(m, dict) or "role" not in m or "content" not in m:
368
- logger.error(f"Invalid message format: {m}")
369
- raise ValueError("Each message must be a dictionary with 'role' and 'content' keys.")
370
-
371
- # Encode role and content
372
- role_tokens = len(enc.encode(m["role"]))
373
- content_tokens = len(enc.encode(m["content"]))
374
- message_tokens = role_tokens + content_tokens
375
-
376
- # Add to totals
377
- total_tokens += message_tokens
378
- token_breakdown[m["role"]] = token_breakdown.get(m["role"], 0) + message_tokens
379
-
380
- logger.info(f"Token count completed. Total tokens: {total_tokens}")
381
- logger.info(f"Token breakdown by role: {token_breakdown}")
382
- return {"total": total_tokens, "by_role": token_breakdown}
383
- except Exception as e:
384
- logger.error(f"Error counting tokens: {e}")
385
- raise
386
-
387
-
388
- def send_query_to_llm(messages):
389
- """
390
- Send the constructed messages to the LLM and get a response.
391
-
392
- Args:
393
- messages (list): List of dictionaries forming the prompt for the LLM.
394
-
395
- Returns:
396
- str: The assistant's response or a fallback message if an error occurs.
397
- """
398
- try:
399
- # Count input tokens
400
- token_data = count_tokens(messages, "o200k_base")
401
- logger.info(f"Input prompt tokens: {token_data['total']}")
402
- logger.info(f"Token breakdown (input): {token_data['by_role']}")
403
-
404
- # Initialize OpenAI client
405
- client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"])
406
-
407
- # Send prompt to LLM
408
- logger.info(f"Sending query to model: {MODEL_NAME}")
409
- completion = client.chat.completions.create(
410
- model=MODEL_NAME,
411
- messages=messages,
412
- temperature=0.3
413
- )
414
-
415
- # Extract assistant's response
416
- assistant_response = completion.choices[0].message.content
417
- #logger.info(f"Assistant response: {assistant_response}")
418
-
419
- # Count output tokens
420
- output_token_data = count_tokens([{"role": "assistant", "content": assistant_response}], "o200k_base")
421
- logger.info(f"Assistant response output tokens: {output_token_data['total']}")
422
-
423
- return assistant_response
424
-
425
- except KeyError as e:
426
- logger.error(f"Missing key in secrets or configuration: {e}")
427
- return "Configuration error: Missing required API key or settings."
428
-
429
- except Exception as e:
430
- logger.error(f"Error communicating with OpenAI: {e}")
431
- return "I'm sorry, I couldn't process your request at the moment."
432
-
433
-
434
  # -----------------------
435
  # Streamlit UI
436
  # -----------------------
437
 
438
  try:
439
- init_db() # Ensure DB is ready
440
  logger.info("DB initialized successfully.")
441
 
442
- @st.cache_resource
443
- def load_retriever():
444
- try:
445
- retriever = Retriever()
446
- logger.info("Retriever initialized successfully.")
447
- return retriever
448
- except Exception as e:
449
- logger.error(f"Failed to initialize Retriever: {e}")
450
- return None
451
 
 
452
  retriever = load_retriever()
 
453
 
454
  # -----------------------
455
  # Download Chat History as CSV button
456
  # -----------------------
457
- def get_db_contents_as_csv():
458
- """
459
- Fetches the database contents for the current session as a CSV-formatted byte string.
460
- """
461
- session_id = get_session_id()
462
- logger.info(f"Fetching chat history for session_id={session_id} as CSV.")
463
-
464
- try:
465
- conn = sqlite3.connect(DB_NAME)
466
- query = "SELECT role, content, timestamp FROM conversations WHERE session_id = ? ORDER BY id ASC"
467
- df = pd.read_sql_query(query, conn, params=(session_id,))
468
- conn.close()
469
-
470
- if not df.empty:
471
- logger.info(f"Successfully fetched {len(df)} rows for session_id={session_id}.")
472
- return df.to_csv(index=False).encode('utf-8')
473
- else:
474
- logger.warning(f"No data found for session_id={session_id}. Returning empty result.")
475
- return None
476
- except sqlite3.Error as e:
477
- logger.error(f"Error reading database: {e}")
478
- st.error(f"Error reading database: {e}")
479
- return None
480
- except Exception as e:
481
- logger.error(f"Unexpected error while fetching database contents: {e}")
482
- st.error(f"Unexpected error: {e}")
483
- return None
484
 
485
  st.sidebar.header("Download Your Chat History")
486
  if st.sidebar.button("Download History as CSV"):
487
- csv = get_db_contents_as_csv()
488
  if csv:
489
  st.sidebar.download_button(
490
  label="Download as CSV",
@@ -494,9 +53,12 @@ try:
494
  )
495
  else:
496
  st.sidebar.warning("No chat history available for download.")
 
 
497
  # -----------------------
498
 
499
- st.title("Prometheus v0.3 - Personal Tutor")
 
500
 
501
  # Instructions
502
  with st.expander("📋 Instructions", expanded=True):
@@ -504,17 +66,19 @@ try:
504
  """
505
  - Press **Enter** to submit your query.
506
  - Type **'quit'** to clear the conversation history.
507
- - Use the sidebar to download conversation history as a CSV file.
508
  - Textbook sources retrieved available in the sidebar.
509
  """
510
  )
 
511
 
512
  # Chat-like UI for conversation history
513
  st.subheader("💬 Conversation History")
514
- messages = load_messages()
515
  for m in messages:
516
  with st.chat_message(m['role']):
517
  st.markdown(m['content'])
 
518
 
519
  # Input area for user query
520
  if prompt := st.chat_input("Ask Prometheus... Type 'quit' to clear history."):
@@ -532,14 +96,17 @@ try:
532
  st.error("Failed to clear conversation history.")
533
  finally:
534
  conn.close()
 
535
  else:
536
  # Immediately display user message in the UI
537
  messages.append({"role": "user", "content": prompt.strip()})
538
  with st.chat_message("user"):
539
  st.markdown(prompt.strip())
 
540
 
541
  # Add user message to DB
542
- add_message("user", prompt.strip())
 
543
 
544
  # Retrieve chunks
545
  if retriever:
@@ -550,20 +117,25 @@ try:
550
  logger.warning("Retriever is not available.")
551
 
552
  # Load updated messages (including user query)
553
- messages = load_messages()
 
554
 
555
  # Build prompt
556
  llm_prompt = build_prompt(prompt.strip(), results, messages)
 
557
 
558
  # Call LLM
559
  assistant_response = send_query_to_llm(llm_prompt)
 
560
 
561
  # Add assistant response to DB
562
- add_message("assistant", assistant_response)
 
563
 
564
  # Display assistant response
565
  with st.chat_message("assistant"):
566
  st.markdown(assistant_response)
 
567
 
568
  # Display retrieved sources in the sidebar
569
  with st.sidebar:
@@ -572,8 +144,11 @@ try:
572
  for i, res in enumerate(results):
573
  st.markdown(f"- **Result {i+1}:** Page {res['page_num']}")
574
  st.code(res['content'])
 
575
  else:
576
  st.warning("No relevant sources found.")
 
 
577
  except Exception as e:
578
  logger.error(f"Failed to initialize DB: {e}")
579
  raise ValueError("Failed to initialize DB.")
 
1
  # app.py
2
+ # v1.0 - modular
3
 
4
+ # External
5
  import streamlit as st
6
  import sqlite3
7
  from datetime import datetime
8
+
9
+ # Internal
10
+ from logging_config import logger
11
+ from database import init_db, add_message, load_messages, DB_NAME
12
+ from retriever import load_retriever, TOP_K
13
+ from prompt import build_prompt
14
+ from api_client import send_query_to_llm
15
+ from get_csv import get_db_contents_as_csv
16
+ from session import get_session_id
 
17
 
18
  # -----------------------
19
  # Configuration and Setup
20
  # -----------------------
21
 
 
 
 
 
 
 
 
22
  # Setup logging
 
 
 
 
 
 
 
 
 
 
 
23
  logger.info(f"Logging setup initialized successfully at {datetime.now().isoformat()}.")
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  # -----------------------
26
  # Streamlit UI
27
  # -----------------------
28
 
29
  try:
30
+ init_db(DB_NAME) # Ensure DB is ready
31
  logger.info("DB initialized successfully.")
32
 
33
+ # Initialize session state
34
+ session_id = get_session_id()
 
 
 
 
 
 
 
35
 
36
+ # Load retriever
37
  retriever = load_retriever()
38
+ logger.info("Retriever initialized successfully.")
39
 
40
  # -----------------------
41
  # Download Chat History as CSV button
42
  # -----------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
  st.sidebar.header("Download Your Chat History")
45
  if st.sidebar.button("Download History as CSV"):
46
+ csv = get_db_contents_as_csv(session_id)
47
  if csv:
48
  st.sidebar.download_button(
49
  label="Download as CSV",
 
53
  )
54
  else:
55
  st.sidebar.warning("No chat history available for download.")
56
+ logger.info("No chat history available for download.")
57
+ logger.info("Download History as CSV button initialized successfully.")
58
  # -----------------------
59
 
60
+ st.title("Prometheus v1.0 - Personalized Canadian History Tutor")
61
+ logger.info("Streamlit title initialized successfully.")
62
 
63
  # Instructions
64
  with st.expander("📋 Instructions", expanded=True):
 
66
  """
67
  - Press **Enter** to submit your query.
68
  - Type **'quit'** to clear the conversation history.
69
+ - Use the sidebar button to download conversation history as a CSV file.
70
  - Textbook sources retrieved available in the sidebar.
71
  """
72
  )
73
+ logger.info("Instructions expanded successfully.")
74
 
75
  # Chat-like UI for conversation history
76
  st.subheader("💬 Conversation History")
77
+ messages = load_messages(session_id)
78
  for m in messages:
79
  with st.chat_message(m['role']):
80
  st.markdown(m['content'])
81
+ logger.info("Conversation history UI initialized successfully.")
82
 
83
  # Input area for user query
84
  if prompt := st.chat_input("Ask Prometheus... Type 'quit' to clear history."):
 
96
  st.error("Failed to clear conversation history.")
97
  finally:
98
  conn.close()
99
+ logger.info("DB connection closed.")
100
  else:
101
  # Immediately display user message in the UI
102
  messages.append({"role": "user", "content": prompt.strip()})
103
  with st.chat_message("user"):
104
  st.markdown(prompt.strip())
105
+ logger.info(f"User message displayed in UI")
106
 
107
  # Add user message to DB
108
+ add_message("user", prompt.strip(), session_id)
109
+ logger.info(f"User message added to DB")
110
 
111
  # Retrieve chunks
112
  if retriever:
 
117
  logger.warning("Retriever is not available.")
118
 
119
  # Load updated messages (including user query)
120
+ messages = load_messages(session_id)
121
+ logger.info("Updated messages loaded, including user query")
122
 
123
  # Build prompt
124
  llm_prompt = build_prompt(prompt.strip(), results, messages)
125
+ logger.info("Prompt built for api client")
126
 
127
  # Call LLM
128
  assistant_response = send_query_to_llm(llm_prompt)
129
+ logger.info("API client response received")
130
 
131
  # Add assistant response to DB
132
+ add_message("assistant", assistant_response, session_id)
133
+ logger.info("Assistant response added to DB")
134
 
135
  # Display assistant response
136
  with st.chat_message("assistant"):
137
  st.markdown(assistant_response)
138
+ logger.info("Assistant response displayed in UI")
139
 
140
  # Display retrieved sources in the sidebar
141
  with st.sidebar:
 
144
  for i, res in enumerate(results):
145
  st.markdown(f"- **Result {i+1}:** Page {res['page_num']}")
146
  st.code(res['content'])
147
+ logger.info(f"Sources displayed in sidebar")
148
  else:
149
  st.warning("No relevant sources found.")
150
+ logger.info("No relevant sources found.")
151
+
152
  except Exception as e:
153
  logger.error(f"Failed to initialize DB: {e}")
154
  raise ValueError("Failed to initialize DB.")
curriculum.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # curriculum.py
2
+
3
+ from logging_config import logger
4
+
5
+ # Function to load the curriculum
6
+ def load_curriculum(file_path):
7
+ """
8
+ Reads the curriculum text file and returns its content as a string.
9
+
10
+ Args:
11
+ file_path (str): Path to the text file.
12
+
13
+ Returns:
14
+ str: Contents of the text file.
15
+ """
16
+ logger.info(f"Attempting to load curriculum from: {file_path}")
17
+
18
+ try:
19
+ with open(file_path, 'r', encoding='utf-8') as file:
20
+ content = file.read().strip()
21
+ logger.info(f"Successfully loaded curriculum. Content length: {len(content)} characters.")
22
+ return content
23
+ except FileNotFoundError:
24
+ logger.error(f"The curriculum file '{file_path}' does not exist.")
25
+ return "Curriculum file not found."
26
+ except Exception as e:
27
+ logger.error(f"Error reading the curriculum file: {e}")
28
+ return "An error occurred while loading the curriculum."
29
+
30
+ # Define loaded curriculum as variable
31
+ CURRICULUM_FILE_PATH = './data/curriculum.txt'
32
+ logger.info(f"Initializing curriculum loading from path: {CURRICULUM_FILE_PATH}")
33
+ CURRICULUM_SUMMARY = load_curriculum(CURRICULUM_FILE_PATH)
34
+ logger.info("Curriculum loading complete.")
database.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # database.py
2
+
3
+ import sqlite3
4
+ import os
5
+ from logging_config import logger
6
+ from datetime import datetime
7
+ from session import get_session_id
8
+
9
+ DB_NAME = "/tmp/conversations.db"
10
+
11
+ def init_db(DB_NAME):
12
+ """Initialize the SQLite database if it doesn't exist."""
13
+ logger.info(f"Initializing database at: {DB_NAME}")
14
+ try:
15
+ # Ensure the directory for the database file exists
16
+ db_directory = os.path.dirname(DB_NAME)
17
+ if not os.path.exists(db_directory):
18
+ logger.info(f"Directory {db_directory} does not exist. Creating it.")
19
+ os.makedirs(db_directory)
20
+
21
+ # Ensure database file exists
22
+ if not os.path.exists(DB_NAME):
23
+ logger.info(f"{DB_NAME} not found. Creating a new database file.")
24
+ open(DB_NAME, 'w').close() # Create an empty file
25
+
26
+ # Connect to the database and initialize the table
27
+ conn = sqlite3.connect(DB_NAME)
28
+ c = conn.cursor()
29
+ c.execute('''
30
+ CREATE TABLE IF NOT EXISTS conversations (
31
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
32
+ role TEXT NOT NULL,
33
+ content TEXT NOT NULL,
34
+ timestamp TEXT NOT NULL,
35
+ session_id TEXT NOT NULL
36
+ )
37
+ ''')
38
+ conn.commit()
39
+ logger.info("Conversations table ensured/created successfully.")
40
+ except sqlite3.Error as e:
41
+ logger.error(f"Error initializing database: {e}")
42
+ raise
43
+ finally:
44
+ if 'conn' in locals():
45
+ conn.close()
46
+ logger.info("Database connection closed.")
47
+
48
+ def add_message(role, content, session_id): #added session_id here see if impacts functionality
49
+ """
50
+ Add a message (user/assistant) to the database.
51
+
52
+ Args:
53
+ role (str): Role of the message sender (e.g., 'user', 'assistant').
54
+ content (str): Content of the message.
55
+ """
56
+ session_id = get_session_id()
57
+ logger.info(f"Adding message: role={role}, session_id={session_id}, content length={len(content)}")
58
+
59
+ # Validate inputs
60
+ if not role or not isinstance(role, str):
61
+ logger.error("Invalid role provided. Must be a non-empty string.")
62
+ raise ValueError("Role must be a non-empty string.")
63
+ if not content or not isinstance(content, str):
64
+ logger.error("Invalid content provided. Must be a non-empty string.")
65
+ raise ValueError("Content must be a non-empty string.")
66
+
67
+ try:
68
+ with sqlite3.connect(DB_NAME) as conn:
69
+ c = conn.cursor()
70
+
71
+ # Insert the message
72
+ c.execute("INSERT INTO conversations (role, content, timestamp, session_id) VALUES (?, ?, ?, ?)",
73
+ (role, content, datetime.now().isoformat(), session_id))
74
+ conn.commit()
75
+
76
+ # Retrieve the ID of the inserted row
77
+ message_id = c.lastrowid
78
+ logger.info(f"Message successfully added: id={message_id}, role={role}, content length={len(content)}")
79
+ except sqlite3.Error as e:
80
+ logger.error(f"Error adding message to database: {e}")
81
+ raise
82
+
83
+
84
+ def load_messages(session_id):#added session_id checking for functionality
85
+ """
86
+ Load all messages from the database, filter by session ID.
87
+
88
+ Returns:
89
+ list: A list of dictionaries with each message's role and content.
90
+ """
91
+ session_id = get_session_id()
92
+ logger.info(f"Loading messages for session_id={session_id}")
93
+
94
+ try:
95
+ with sqlite3.connect(DB_NAME) as conn:
96
+ c = conn.cursor()
97
+ c.execute(
98
+ "SELECT role, content FROM conversations WHERE session_id = ? ORDER BY id ASC",
99
+ (session_id,)
100
+ )
101
+ rows = c.fetchall()
102
+
103
+ # Transform rows into a list of dictionaries
104
+ messages = [{"role": r, "content": cnt} for (r, cnt) in rows]
105
+ logger.info(f"Successfully loaded {len(messages)} messages from the database.")
106
+ return messages
107
+ except sqlite3.Error as e:
108
+ logger.error(f"Error loading messages from database: {e}")
109
+ raise
generator.py ADDED
@@ -0,0 +1 @@
 
 
1
+ #MARKED FOR DELETION
get_csv.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # get_csv.py
2
+
3
+ import streamlit as st
4
+ import sqlite3
5
+ import pandas as pd
6
+ from session import get_session_id
7
+ from logging_config import logger
8
+ from database import DB_NAME
9
+
10
+ def get_db_contents_as_csv(session_id):
11
+ """
12
+ Fetches the database contents for the current session as a CSV-formatted byte string.
13
+ """
14
+ session_id = get_session_id()
15
+ logger.info(f"Fetching chat history for session_id={session_id} as CSV.")
16
+
17
+ try:
18
+ conn = sqlite3.connect(DB_NAME)
19
+ query = "SELECT role, content, timestamp FROM conversations WHERE session_id = ? ORDER BY id ASC"
20
+ df = pd.read_sql_query(query, conn, params=(session_id,))
21
+ conn.close()
22
+
23
+ if not df.empty:
24
+ logger.info(f"Successfully fetched {len(df)} rows for session_id={session_id}.")
25
+ return df.to_csv(index=False).encode('utf-8')
26
+ else:
27
+ logger.warning(f"No data found for session_id={session_id}. Returning empty result.")
28
+ return None
29
+ except sqlite3.Error as e:
30
+ logger.error(f"Error reading database: {e}")
31
+ st.error(f"Error reading database: {e}")
32
+ return None
33
+ except Exception as e:
34
+ logger.error(f"Unexpected error while fetching database contents: {e}")
35
+ st.error(f"Unexpected error: {e}")
36
+ return None
logging_config.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # logging_config.py
2
+
3
+ import logging
4
+ from logging.handlers import RotatingFileHandler
5
+ import os
6
+
7
+ LOG_FILE_PATH = "./logs/app.log"
8
+
9
+ if not os.path.exists(LOG_FILE_PATH):
10
+ with open(LOG_FILE_PATH, 'w') as log_file:
11
+ log_file.write("") # Create an empty file
12
+
13
+ # Setup logging
14
+ logging.basicConfig(
15
+ level=logging.INFO,
16
+ format='%(asctime)s %(levelname)s:%(name)s:%(funcName)s:%(message)s',
17
+ handlers=[
18
+ RotatingFileHandler(LOG_FILE_PATH, maxBytes=5*1024*1024, backupCount=3),
19
+ logging.StreamHandler()
20
+ ]
21
+ )
22
+ logger = logging.getLogger(__name__)
23
+
24
+ # Test logging
25
+ logger.info("Logging setup initialized successfully.")
prompt.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from logging_config import logger
2
+ from summarizer import truncate_and_summarize
3
+ import streamlit as st
4
+ from curriculum import CURRICULUM_SUMMARY
5
+ from token_counter import count_tokens
6
+
7
+ # Function to build the prompt
8
+ def build_prompt(user_query, retrieved_chunks, messages):
9
+ """
10
+ Build the prompt for the LLM:
11
+ - Include system prompts from secrets
12
+ - Include the curriculum summary
13
+ - Summarize older conversation history
14
+ - Add retrieved chunks as system context
15
+ - Include user query at the end
16
+ """
17
+ logger.info("Building prompt for the model.")
18
+
19
+ # Summarize older messages if needed
20
+ messages = truncate_and_summarize(messages)
21
+
22
+ # Load system prompts from secrets
23
+ try:
24
+ socratic_guide = st.secrets["SOCRATIC_GUIDE"]
25
+ prometheus_prompt = st.secrets["PROMETHEUS_PROMPT"]
26
+ logger.info("Successfully loaded system prompts from secrets.")
27
+ except KeyError as e:
28
+ logger.error(f"Missing key in secrets.toml: {e}")
29
+ raise ValueError(f"Missing secret key: {e}")
30
+
31
+ # Initialize the prompt messages
32
+ prompt_messages = []
33
+
34
+ # Add the Socratic guide to the prompt
35
+ prompt_messages.append({"role": "system", "content": socratic_guide})
36
+
37
+ # Add the placeholder prompt to the prompt
38
+ prompt_messages.append({"role": "system", "content": prometheus_prompt})
39
+
40
+ # Include the curriculum summary
41
+ curriculum_instructions = f"""
42
+ Here are the learning goals for this class based on the TDSB's Curriculum. Ensure that your responses are aligned with these goals:\n
43
+ {CURRICULUM_SUMMARY}
44
+ """
45
+ prompt_messages.append({"role": "system", "content": curriculum_instructions})
46
+
47
+ # Add conversation history
48
+ for m in messages:
49
+ prompt_messages.append({"role": m["role"], "content": m["content"]})
50
+
51
+ # Add retrieved chunks as system context
52
+ if retrieved_chunks:
53
+ chunks_text = "\n".join([f"Page {c['page_num']}:\n{c['content']}" for c in retrieved_chunks])
54
+ retrieved_content_instruction = (
55
+ "Considering your previous instructions, you must use the retrieved content to guide and position your responses and follow-up questions, relying solely on this information as your source of truth."
56
+ "Do not use any other prior or external knowledge or make assumptions beyond the retrieved content provided below to respond to user queries. if the content is insufficient to answer the question, tell the student to consider consulting alternative resources. This dynamic approach ensures students develop both essential knowledge and the ability to reason critically and independently."
57
+ "Retrieved chunks:"
58
+ )
59
+ prompt_messages.append({"role": "system", "content": retrieved_content_instruction + "\n" + chunks_text})
60
+
61
+
62
+ # Add the user's query
63
+ prompt_messages.append({"role": "user", "content": user_query})
64
+
65
+ # Count tokens in the final prompt
66
+ try:
67
+ token_data = count_tokens(prompt_messages)
68
+ logger.info(f"Total tokens for prompt: {token_data['total']}")
69
+ logger.info(f"Token breakdown by role: {token_data['by_role']}")
70
+ except Exception as e:
71
+ logger.error(f"Error counting tokens: {e}")
72
+ raise ValueError("Failed to count tokens for the prompt.")
73
+
74
+ #logger.info("Prompt successfully built. Prompt messages: %s", json.dumps(prompt_messages, indent=4))
75
+ return prompt_messages
retriever.py CHANGED
@@ -3,7 +3,10 @@ import numpy as np
3
  import faiss
4
  import json
5
  from sentence_transformers import SentenceTransformer
 
 
6
 
 
7
  class Retriever:
8
  def __init__(self):
9
  # Load the embeddings and metadata
@@ -18,7 +21,7 @@ class Retriever:
18
  model_name = 'all-mpnet-base-v2' # Ensure this matches the model used during indexing
19
  self.model = SentenceTransformer(model_name)
20
 
21
- def retrieve(self, query, k=5, min_content_words=25):
22
  # Generate embedding for the query
23
  query_embedding = self.model.encode([query]).astype('float32')
24
 
@@ -47,6 +50,17 @@ class Retriever:
47
 
48
  return results[:k]
49
 
 
 
 
 
 
 
 
 
 
 
 
50
  """
51
  #for testing - removed for prod
52
  if __name__ == '__main__':
 
3
  import faiss
4
  import json
5
  from sentence_transformers import SentenceTransformer
6
+ import streamlit as st
7
+ from logging_config import logger
8
 
9
+ TOP_K = 3 # number of chunks to retrieve for sources sidebar
10
  class Retriever:
11
  def __init__(self):
12
  # Load the embeddings and metadata
 
21
  model_name = 'all-mpnet-base-v2' # Ensure this matches the model used during indexing
22
  self.model = SentenceTransformer(model_name)
23
 
24
+ def retrieve(self, query, k=TOP_K, min_content_words=25):
25
  # Generate embedding for the query
26
  query_embedding = self.model.encode([query]).astype('float32')
27
 
 
50
 
51
  return results[:k]
52
 
53
+ # Retrieval for streamlit
54
+ @st.cache_resource
55
+ def load_retriever():
56
+ try:
57
+ retriever = Retriever()
58
+ logger.info("Retriever initialized successfully.")
59
+ return retriever
60
+ except Exception as e:
61
+ logger.error(f"Failed to initialize Retriever: {e}")
62
+ return None
63
+
64
  """
65
  #for testing - removed for prod
66
  if __name__ == '__main__':
session.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # session.py
2
+
3
+ import streamlit as st
4
+ import uuid
5
+ from logging_config import logger
6
+
7
+ def get_session_id():
8
+ """
9
+ Generate a session ID using a UUID and store it in Streamlit's session state.
10
+ Ensures user-specific chat sessions.
11
+ """
12
+ if "session_id" not in st.session_state:
13
+ # Log session initialization
14
+ logger.info("Generating new session ID.")
15
+ # Generate a new UUID and assign it to session state
16
+ st.session_state["session_id"] = str(uuid.uuid4())
17
+ logger.info(f"New session ID: {st.session_state['session_id']}")
18
+ else:
19
+ logger.info(f"Using existing session ID: {st.session_state['session_id']}")
20
+ # Return the session ID from session state
21
+ return st.session_state["session_id"]
summarizer.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # summarizer.py
2
+
3
+ import streamlit as st
4
+ from transformers import pipeline
5
+ from logging_config import logger
6
+
7
+ @st.cache_resource
8
+ def load_summarizer():
9
+ """
10
+ Load and cache the summarization pipeline.
11
+ Designed for a CPU-only environment and uses Hugging Face-hosted models.
12
+ """
13
+ try:
14
+ logger.info("Loading summarizer model on CPU...")
15
+
16
+ # Initialize summarization pipeline on CPU
17
+ summarizer = pipeline("summarization", model="facebook/bart-large-cnn", device=-1)
18
+
19
+ logger.info("Summarizer model loaded successfully.")
20
+ return summarizer
21
+ except Exception as e:
22
+ logger.error(f"Failed to load summarizer pipeline: {e}")
23
+ st.error("The summarization model could not be loaded. Please try again later.")
24
+ return None
25
+
26
+ def truncate_and_summarize(messages, max_length=2500, min_length=250, recent_messages=20):
27
+ """
28
+ If conversation too long, summarize older messages.
29
+
30
+ Args:
31
+ messages (list): List of message dictionaries.
32
+ max_length (int): Maximum length for the summary.
33
+ min_length (int): Minimum length for the summary.
34
+ recent_messages (int): Number of recent messages to keep intact.
35
+
36
+ Returns:
37
+ list: Updated list of messages with older ones summarized.
38
+ """
39
+ logger.info(f"Checking if summarization is needed. Total messages: {len(messages)}")
40
+
41
+ if len(messages) <= recent_messages:
42
+ logger.info("No summarization needed; message count within limit.")
43
+ return messages
44
+
45
+ # Split older and recent messages
46
+ older = messages[:-recent_messages]
47
+ recent = messages[-recent_messages:]
48
+
49
+ # Combine older messages
50
+ conversation_text = "\n".join([f"{m['role']}: {m['content']}" for m in older])
51
+ summary_input = ("Summarize the following conversation concisely to act as assistant's memory:\n\n"
52
+ + conversation_text)
53
+
54
+ summarizer = load_summarizer()
55
+ if summarizer:
56
+ try:
57
+ # Perform summarization
58
+ logger.info("Performing summarization of older messages.")
59
+ summary_result = summarizer(summary_input, max_length=max_length, min_length=min_length, do_sample=False)
60
+ summary_text = summary_result[0]['summary_text'].strip()
61
+ logger.info("Successfully summarized older conversation.")
62
+
63
+ # Prepend the summarized message
64
+ summarized = [{"role": "system", "content": "Summary of previous conversation: " + summary_text}]
65
+ return summarized + recent
66
+ except Exception as e:
67
+ logger.error(f"Error during summarization: {e}")
68
+ logger.warning("Returning messages without summarization.")
69
+
70
+ logger.warning("Summarizer not available. Returning messages without summarization.")
71
+ return messages
token_counter.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # token_counter.py
2
+
3
+ import tiktoken
4
+ from logging_config import logger
5
+
6
+ encoding_model = "o200k_base"
7
+ def count_tokens(messages, encoding_name=encoding_model):
8
+ """
9
+ Count the total number of tokens in a list of messages, including system prompts.
10
+
11
+ Args:
12
+ messages (list): List of message dictionaries with 'role' and 'content' keys.
13
+ encoding_name (str): Encoding name for tokenization (default: "o200k_base").
14
+
15
+ Returns:
16
+ dict: Dictionary containing the total token count and a breakdown by role.
17
+ """
18
+ try:
19
+ enc = tiktoken.get_encoding(encoding_name)
20
+ logger.info(f"Using encoding: {encoding_name}")
21
+ except Exception as e:
22
+ logger.error(f"Failed to get encoding '{encoding_name}': {e}")
23
+ raise ValueError(f"Invalid encoding: {encoding_name}")
24
+
25
+ total_tokens = 0
26
+ token_breakdown = {}
27
+
28
+ try:
29
+ for m in messages:
30
+ if not isinstance(m, dict) or "role" not in m or "content" not in m:
31
+ logger.error(f"Invalid message format: {m}")
32
+ raise ValueError("Each message must be a dictionary with 'role' and 'content' keys.")
33
+
34
+ # Encode role and content
35
+ role_tokens = len(enc.encode(m["role"]))
36
+ content_tokens = len(enc.encode(m["content"]))
37
+ message_tokens = role_tokens + content_tokens
38
+
39
+ # Add to totals
40
+ total_tokens += message_tokens
41
+ token_breakdown[m["role"]] = token_breakdown.get(m["role"], 0) + message_tokens
42
+
43
+ logger.info(f"Token count completed. Total tokens: {total_tokens}")
44
+ logger.info(f"Token breakdown by role: {token_breakdown}")
45
+ return {"total": total_tokens, "by_role": token_breakdown}
46
+ except Exception as e:
47
+ logger.error(f"Error counting tokens: {e}")
48
+ raise