tbels89 commited on
Commit
2540499
·
1 Parent(s): bc5c1c0

added app.py, updated retriever

Browse files
Files changed (3) hide show
  1. app.py +272 -1
  2. retrieval_log.csv +0 -0
  3. retriever.py +3 -0
app.py CHANGED
@@ -1 +1,272 @@
1
- #nothing yet...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+
3
+ import streamlit as st
4
+ import sqlite3
5
+ from datetime import datetime
6
+ from retriever import Retriever
7
+ from openai import OpenAI
8
+ import logging
9
+ from transformers import pipeline
10
+
11
+ # -----------------------
12
+ # Configuration and Setup
13
+ # -----------------------
14
+
15
+ # Setup logging
16
+ logging.basicConfig(
17
+ level=logging.INFO,
18
+ format='%(asctime)s %(levelname)s:%(name)s:%(message)s',
19
+ handlers=[
20
+ logging.FileHandler("app.log"),
21
+ logging.StreamHandler()
22
+ ]
23
+ )
24
+ logger = logging.getLogger(__name__)
25
+
26
+ CURRICULUM_SUMMARY = """Your curriculum goals:
27
+ - Facilitate learning using Socratic questioning.
28
+ - Encourage critical thinking and exploration.
29
+ - Align responses with educational objectives described in the curriculum.
30
+ Use these principles as a guide for all answers."""
31
+
32
+ MODEL_NAME = "gpt-4o-mini"
33
+ TOP_K = 3
34
+ DB_NAME = "conversations.db"
35
+
36
+ # -----------------------
37
+ # Helper Functions
38
+ # -----------------------
39
+
40
+ def init_db():
41
+ """Initialize the SQLite database if it doesn't exist."""
42
+ try:
43
+ conn = sqlite3.connect(DB_NAME)
44
+ c = conn.cursor()
45
+ c.execute('''
46
+ CREATE TABLE IF NOT EXISTS conversations (
47
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
48
+ role TEXT,
49
+ content TEXT,
50
+ timestamp TEXT
51
+ )
52
+ ''')
53
+ conn.commit()
54
+ logger.info("Conversations table ensured/created successfully.")
55
+ except sqlite3.Error as e:
56
+ logger.error(f"Error initializing database: {e}")
57
+ raise
58
+ finally:
59
+ conn.close()
60
+
61
+ def add_message(role, content):
62
+ """Add a message (user/assistant) to the database."""
63
+ try:
64
+ conn = sqlite3.connect(DB_NAME)
65
+ c = conn.cursor()
66
+ c.execute("INSERT INTO conversations (role, content, timestamp) VALUES (?, ?, ?)",
67
+ (role, content, datetime.now().isoformat()))
68
+ conn.commit()
69
+ logger.info(f"Message added: role={role}, content length={len(content)}")
70
+ except sqlite3.Error as e:
71
+ logger.error(f"Error adding message to database: {e}")
72
+ raise
73
+ finally:
74
+ conn.close()
75
+
76
+ def load_messages():
77
+ """Load all messages from the database."""
78
+ try:
79
+ conn = sqlite3.connect(DB_NAME)
80
+ c = conn.cursor()
81
+ c.execute("SELECT role, content FROM conversations ORDER BY id ASC")
82
+ rows = c.fetchall()
83
+ messages = [{"role": r, "content": cnt} for (r, cnt) in rows]
84
+ logger.info(f"Loaded {len(messages)} messages from the database.")
85
+ return messages
86
+ except sqlite3.Error as e:
87
+ logger.error(f"Error loading messages from database: {e}")
88
+ raise
89
+ finally:
90
+ conn.close()
91
+
92
+ @st.cache_resource
93
+ def load_summarizer():
94
+ """
95
+ Load and cache the summarization pipeline.
96
+ """
97
+ try:
98
+ summarizer = pipeline("summarization", model="facebook/bart-large-cnn", device=-1)
99
+ return summarizer
100
+ except Exception as e:
101
+ logger.error(f"Failed to load summarizer pipeline: {e}")
102
+ return None
103
+
104
+ summarizer = load_summarizer()
105
+
106
+ def truncate_and_summarize(messages):
107
+ """
108
+ If conversation too long, summarize older messages.
109
+ We'll keep the last 20 messages and summarize the rest.
110
+ """
111
+ if len(messages) <= 20:
112
+ return messages # No need to summarize
113
+
114
+ # Separate older and recent messages
115
+ older = messages[:-20]
116
+ recent = messages[-20:]
117
+
118
+ # Combine older messages into a single text for summarization
119
+ conversation_text = "\n".join([f"{m['role']}: {m['content']}" for m in older])
120
+ summary_input = ("Summarize the following conversation concisely to act as assistant's memory:\n\n"
121
+ + conversation_text)
122
+
123
+ if summarizer:
124
+ try:
125
+ # Perform summarization
126
+ summary_result = summarizer(summary_input, max_length=250, min_length=30, do_sample=False)
127
+ summary_text = summary_result[0]['summary_text'].strip()
128
+ logger.info("Successfully summarized older conversation.")
129
+ summarized = [{"role": "system", "content": "Summary of previous conversation: " + summary_text}]
130
+ return summarized + recent
131
+ except Exception as e:
132
+ logger.error(f"Error during summarization: {e}")
133
+
134
+ return messages
135
+
136
+ def build_prompt(user_query, retrieved_chunks, messages):
137
+ """
138
+ Build the prompt for the LLM:
139
+ - System message with curriculum summary (ADD IN PROMETHEUS PROMPT HERE?)
140
+ - Summarized older context
141
+ - Recent conversation and user query
142
+ - Retrieved chunks as additional context
143
+ """
144
+ # Summarize older part if needed
145
+ messages = truncate_and_summarize(messages)
146
+
147
+ # Construct prompt
148
+ ## NEEDS TO BE UPDATED WITH ACTUAL PROMETHEUS PROMPT
149
+ prompt_messages = [
150
+ {"role": "system", "content": "you are a personal tutor that uses the socratic method of teaching. here are the learning goals for this class: " + CURRICULUM_SUMMARY}
151
+ ]
152
+
153
+ # Include conversation history
154
+ for m in messages:
155
+ prompt_messages.append({"role": m["role"], "content": m["content"]})
156
+
157
+ # Add retrieved chunks as system context
158
+ if retrieved_chunks:
159
+ chunks_text = "\n".join([f"Page {c['page_num']}:\n{c['content']}" for c in retrieved_chunks])
160
+ prompt_messages.append({"role": "system", "content": "Retrieved content from textbook. Base response on this as your guiding knowledge:\n" + chunks_text})
161
+
162
+ # Finally, add the user's new query
163
+ prompt_messages.append({"role": "user", "content": user_query})
164
+
165
+ return prompt_messages
166
+
167
+ def send_query_to_llm(messages):
168
+ """Send the constructed messages to the LLM and get a response."""
169
+ try:
170
+ client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"]) # Ensure this is set in Streamlit secrets
171
+ completion = client.chat.completions.create(
172
+ model=MODEL_NAME,
173
+ messages=messages
174
+ )
175
+ return completion.choices[0].message['content'].strip()
176
+ except Exception as e:
177
+ logger.error(f"Error communicating with OpenAI: {e}")
178
+ return "I'm sorry, I couldn't process your request at the moment."
179
+
180
+ # -----------------------
181
+ # Streamlit UI
182
+ # -----------------------
183
+
184
+ init_db() # Ensure DB is ready
185
+
186
+ @st.cache_resource
187
+ # NEED TO FIGURE OUT HOW TO PROPERLY IMPORT RETRIEVER
188
+ def load_retriever():
189
+ try:
190
+ retriever = Retriever()
191
+ logger.info("Retriever initialized successfully.")
192
+ return retriever
193
+ except Exception as e:
194
+ logger.error(f"Failed to initialize Retriever: {e}")
195
+ return None
196
+
197
+ retriever = load_retriever()
198
+
199
+ st.title("Prometheus v0.1 - Personal Tutor")
200
+
201
+ st.write("**Instructions:**")
202
+ st.write("- Press the 'Send' button or Enter to submit your query.")
203
+ st.write("- Use Shift+Enter (or Ctrl+Enter) for a new line in the text area.")
204
+ st.write("- Type 'quit' if you wish to stop asking questions (clears conversation history).")
205
+
206
+ # Display conversation history from DB
207
+ messages = load_messages()
208
+ for m in messages:
209
+ if m['role'] == 'user':
210
+ st.markdown(f"**You:** {m['content']}")
211
+ elif m['role'] == 'assistant':
212
+ st.markdown(f"**Tutor:** {m['content']}")
213
+ elif m['role'] == 'system':
214
+ st.markdown(f"**System:** {m['content']}")
215
+
216
+ # Input form
217
+ with st.form(key='query_form'):
218
+ user_query = st.text_area("Enter your query:", height=100, key='user_input')
219
+ submitted = st.form_submit_button("Send")
220
+
221
+ if submitted and user_query.strip():
222
+ # If user wants to quit
223
+ if user_query.strip().lower() == 'quit':
224
+ # Clear conversation history
225
+ try:
226
+ conn = sqlite3.connect(DB_NAME)
227
+ c = conn.cursor()
228
+ c.execute("DELETE FROM conversations")
229
+ conn.commit()
230
+ logger.info("Conversation history cleared.")
231
+ st.success("Conversation history cleared.")
232
+ except sqlite3.Error as e:
233
+ logger.error(f"Error clearing conversation history: {e}")
234
+ st.error("Failed to clear conversation history.")
235
+ finally:
236
+ conn.close()
237
+ else:
238
+ # Add user message to DB
239
+ add_message("user", user_query.strip())
240
+
241
+ # Retrieve chunks
242
+ if retriever:
243
+ results = retriever.retrieve(user_query.strip(), k=TOP_K)
244
+ logger.info(f"Retrieved {len(results)} chunks for query: '{user_query.strip()}'")
245
+ else:
246
+ results = []
247
+ logger.warning("Retriever is not available.")
248
+
249
+ # Load updated messages (including user query)
250
+ messages = load_messages()
251
+
252
+ # Build prompt
253
+ llm_prompt = build_prompt(user_query.strip(), results, messages)
254
+
255
+ # Call LLM
256
+ assistant_response = send_query_to_llm(llm_prompt)
257
+
258
+ # Add assistant message to DB
259
+ add_message("assistant", assistant_response)
260
+
261
+ # Display assistant response and retrieved sources
262
+ st.markdown(f"**Tutor:** {assistant_response}")
263
+
264
+ if results:
265
+ st.markdown("**Sources:**")
266
+ for i, res in enumerate(results):
267
+ st.markdown(f"- **Result {i+1}:** Page {res['page_num']}")
268
+ st.markdown(f"```\n{res['content']}\n```")
269
+ else:
270
+ st.markdown("**Sources:** No relevant sources found.")
271
+
272
+ st.rerun() # Refresh to show updated conversation
retrieval_log.csv CHANGED
The diff for this file is too large to render. See raw diff
 
retriever.py CHANGED
@@ -47,6 +47,8 @@ class Retriever:
47
 
48
  return results[:k]
49
 
 
 
50
  if __name__ == '__main__':
51
  retriever = Retriever()
52
  sample_query = "what is the triple entente?"
@@ -57,3 +59,4 @@ if __name__ == '__main__':
57
  print(f"Result {i+1}:")
58
  print(f"Page Number: {res['page_num']}")
59
  print(f"Content: {res['content']}\n")
 
 
47
 
48
  return results[:k]
49
 
50
+ """
51
+ #for testing - removed for prod
52
  if __name__ == '__main__':
53
  retriever = Retriever()
54
  sample_query = "what is the triple entente?"
 
59
  print(f"Result {i+1}:")
60
  print(f"Page Number: {res['page_num']}")
61
  print(f"Content: {res['content']}\n")
62
+ """