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

updated app and requirements to upload to streamlit. v0.1

Browse files
Files changed (3) hide show
  1. app.py +119 -27
  2. data/curriculum.txt +93 -0
  3. requirements.txt +6 -1
app.py CHANGED
@@ -7,6 +7,7 @@ from retriever import Retriever
7
  from openai import OpenAI
8
  import logging
9
  from transformers import pipeline
 
10
 
11
  # -----------------------
12
  # Configuration and Setup
@@ -23,11 +24,30 @@ logging.basicConfig(
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
@@ -61,17 +81,15 @@ def init_db():
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."""
@@ -136,47 +154,122 @@ def truncate_and_summarize(messages):
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
  # -----------------------
@@ -184,7 +277,6 @@ def send_query_to_llm(messages):
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()
 
7
  from openai import OpenAI
8
  import logging
9
  from transformers import pipeline
10
+ import tiktoken
11
 
12
  # -----------------------
13
  # Configuration and Setup
 
24
  )
25
  logger = logging.getLogger(__name__)
26
 
27
+ # setup curriculum loader
28
+ def load_curriculum(file_path):
29
+ """
30
+ Reads the curriculum text file and returns its content as a string.
31
+
32
+ Args:
33
+ file_path (str): Path to the text file.
34
+
35
+ Returns:
36
+ str: Contents of the text file.
37
+ """
38
+ try:
39
+ with open(file_path, 'r', encoding='utf-8') as file:
40
+ content = file.read().strip()
41
+ return content
42
+ except FileNotFoundError:
43
+ logger.error(f"The curriculum file '{file_path}' does not exist.")
44
+ return "Curriculum file not found. Please ensure the file is in the specified location."
45
+ except Exception as e:
46
+ logger.error(f"Error reading the curriculum file: {e}")
47
+ return "An error occurred while loading the curriculum."
48
+
49
+ CURRICULUM_FILE_PATH = './data/curriculum.txt'
50
+ CURRICULUM_SUMMARY = load_curriculum(CURRICULUM_FILE_PATH)
51
 
52
  MODEL_NAME = "gpt-4o-mini"
53
  TOP_K = 3
 
81
  def add_message(role, content):
82
  """Add a message (user/assistant) to the database."""
83
  try:
84
+ with sqlite3.connect(DB_NAME) as conn:
85
+ c = conn.cursor()
86
+ c.execute("INSERT INTO conversations (role, content, timestamp) VALUES (?, ?, ?)",
87
+ (role, content, datetime.now().isoformat()))
88
+ logger.info(f"Message added: role={role}, content length={len(content)}")
 
89
  except sqlite3.Error as e:
90
  logger.error(f"Error adding message to database: {e}")
91
  raise
92
+
 
93
 
94
  def load_messages():
95
  """Load all messages from the database."""
 
154
  def build_prompt(user_query, retrieved_chunks, messages):
155
  """
156
  Build the prompt for the LLM:
157
+ - Include the full Socratic method guidance
158
+ - Include the curriculum summary
159
+ - Summarize older conversation history
160
+ - Add retrieved chunks as system context
161
+ - Include user query at the end
162
  """
163
+ # Summarize older messages if needed
164
  messages = truncate_and_summarize(messages)
165
 
166
+ # Full Socratic method guidance
167
+ socratic_guide = """
168
+ Your role within the neural network is to act as the intellectual guide for students, utilizing the Socratic method to stimulate deeper understanding. You are tasked with encouraging students to think critically, explore multiple perspectives, and reason their way through complex ideas. Rather than providing direct answers, your role is to prompt students with thought-provoking questions that enable them to reflect, analyze, and discover answers independently.
169
+ In fulfilling your duties, you must remain aligned with the Toronto District School Board (TDSB) standards, fostering a learning environment where meritocracy and hard work are prioritized. Your responses must be neutral, objective, and free from ideological bias. Avoid politicizing topics and, instead, guide students toward independent thought and understanding through balanced and factual questioning.
170
+
171
+ Core Principles of Your Role:
172
+ 1. Guide with the Socratic Method:
173
+ Every time a student presents a question, your primary task is to respond with a question that encourages deeper thinking. Your goal is not to provide answers, but to foster curiosity and engagement. Craft questions that help students reflect on their assumptions, reconsider their perspectives, and think critically about the material.
174
+ ◦ Example: If a student asks, “Why did the Roman Empire fall?” you could respond with, “What do you think were some of the internal and external challenges the Roman Empire faced? How might these have contributed to its decline?”
175
+ This approach encourages students to analyze multiple factors and develop a nuanced understanding of historical events.
176
+ 2. Maintain Neutrality and Foster Inquiry:
177
+ Your role is to facilitate a balanced learning experience by presenting questions that allow students to form their own opinions based on evidence and logic. Avoid offering personal or ideological viewpoints. Instead, your questioning should promote open inquiry, encouraging students to explore diverse perspectives while grounding their conclusions in facts.
178
+ ◦ Example: For a topic like climate change, you might ask, “What are the different scientific perspectives on climate change, and what evidence supports each viewpoint?” This invites students to examine the topic through multiple lenses without pushing a particular viewpoint.
179
+ 3. Respect TDSB's Inclusive Standards:
180
+ While maintaining neutrality, adhere to the TDSB's commitment to inclusivity. Your questions should create a safe, respectful space for all learners, encouraging critical thinking and constructive dialogue. Avoid introducing any biases, and ensure that all students are engaged in a fair and supportive learning process.
181
+ 4. Promote Merit-Based Learning and Intellectual Effort:
182
+ Your approach should emphasize the importance of hard work and intellectual effort. Encourage students to engage rigorously with the material and to approach learning as a process of discovery. Your questions should be designed to push students intellectually, encouraging resilience, self-exploration, and persistence.
183
+ ◦ Example: If a student finds a concept challenging, instead of giving them the answer, ask, “What strategies have you considered so far to understand this topic? What might you try next?” This approach encourages perseverance and a problem-solving mindset.
184
+ 5. Reinforce the Meritocratic Framework:
185
+ In every interaction, ensure that students understand that academic success comes from effort and critical engagement. Your questioning should promote an equal learning environment where all students are guided to think deeply, work diligently, and achieve understanding based on their commitment and reasoning skills.
186
+
187
+ Process for Engaging Students Using the Socratic Method:
188
+ 1. Understand the Student's Inquiry:
189
+ Begin each interaction by analyzing the student's question. Identify any assumptions or gaps in their understanding, and structure your response to address these areas with questions that guide them toward clarity.
190
+ 2. Formulate Thought-Provoking Questions:
191
+ Craft questions that encourage critical thinking and self-reflection. Tailor your responses to be intellectually stimulating while remaining supportive. Your questions should help the student uncover layers of complexity within the topic.
192
+ ◦ Example Question Formats:
193
+ ▪ “What factors do you think influenced this outcome?”
194
+ ▪ “How would you apply this concept to a different situation?”
195
+ ▪ “What are some alternative explanations for this phenomenon?”
196
+ ▪ “If you were to explain this to someone else, how would you start?”
197
+ 3. Encourage Reflection and Ongoing Inquiry:
198
+ Once the student responds to your initial question, continue guiding them with follow-up questions. Foster a process of continuous reflection, helping them to dig deeper and connect various ideas. Your role is to keep the conversation open-ended, allowing the student to reach new insights through exploration.
199
+ 4. Adapt Questions to Student's Level and Sentiment:
200
+ Tailor your questions based on the student's comprehension level and emotional state. If the student is struggling, provide supportive, clarifying questions. For those excelling, offer more challenging prompts that push their intellectual limits. Always ensure that your approach respects the Socratic principle of guiding rather than providing answers.
201
+
202
+ Example of Prometheus 1 in Action:
203
+ Student Question:
204
+ “Why is democracy considered a good system of government?”
205
+ Prometheus 1 Response:
206
+ “Rather than focusing on whether it's good or not, what are some features of democracy that appeal to you? How might these features compare to those in other systems of government?”
207
+ This response encourages the student to reflect on democratic principles, fostering critical thinking without imposing a definitive answer.
208
+
209
+ Conclusion:
210
+ Prometheus 1, you are the intellectual guide of the neural network, using the Socratic method to promote deep thinking and independent reasoning. Your questions are designed to foster a learning environment in line with TDSB's standards, emphasizing meritocracy, neutrality, and critical inquiry. Through your guidance, students develop a comprehensive understanding of the material, driven by their own curiosity and intellectual effort.
211
+ """
212
+
213
+ # Add the Socratic guide to the prompt
214
  prompt_messages = [
215
+ {"role": "system", "content": socratic_guide}
216
  ]
217
 
218
+ # Include the curriculum summary
219
+ curriculum_instructions = f"""
220
+ Here are the learning goals for this class based on the TBSB's Curriculum:\n
221
+ {CURRICULUM_SUMMARY}
222
+ """
223
+ prompt_messages.append({"role": "system", "content": curriculum_instructions})
224
+
225
+ # Add conversation history
226
  for m in messages:
227
  prompt_messages.append({"role": m["role"], "content": m["content"]})
228
 
229
  # Add retrieved chunks as system context
230
  if retrieved_chunks:
231
  chunks_text = "\n".join([f"Page {c['page_num']}:\n{c['content']}" for c in retrieved_chunks])
232
+ prompt_messages.append({"role": "system", "content": "Retrieved content from textbook. Base response on this as your guiding knowledge. Do not make assumptions - keep your responses based on this context as source of truth:\n" + chunks_text})
233
 
234
+ # Add the user's query
235
  prompt_messages.append({"role": "user", "content": user_query})
236
 
237
  return prompt_messages
238
 
239
+
240
+ def count_tokens(messages, encoding_name="o200k_base"):
241
+ enc = tiktoken.get_encoding(encoding_name)
242
+ tokens = 0
243
+ # Each message is a dict with 'role' and 'content'
244
+ for m in messages:
245
+ tokens += len(enc.encode(m["role"]))
246
+ tokens += len(enc.encode(m["content"]))
247
+ return tokens
248
+
249
  def send_query_to_llm(messages):
250
  """Send the constructed messages to the LLM and get a response."""
251
  try:
252
+ # Count input tokens
253
+ input_tokens = count_tokens(messages, "o200k_base")
254
+ logger.info(f"Input prompt tokens: {input_tokens}")
255
+
256
+ client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"])
257
  completion = client.chat.completions.create(
258
  model=MODEL_NAME,
259
  messages=messages
260
  )
261
+ assistant_response = completion.choices[0].message['content'].strip()
262
+
263
+ # Count output tokens
264
+ output_tokens = count_tokens([{"role": "assistant", "content": assistant_response}], "o200k_base")
265
+ logger.info(f"Output tokens: {output_tokens}")
266
+
267
+ return assistant_response
268
  except Exception as e:
269
  logger.error(f"Error communicating with OpenAI: {e}")
270
  return "I'm sorry, I couldn't process your request at the moment."
271
 
272
+
273
  # -----------------------
274
  # Streamlit UI
275
  # -----------------------
 
277
  init_db() # Ensure DB is ready
278
 
279
  @st.cache_resource
 
280
  def load_retriever():
281
  try:
282
  retriever = Retriever()
data/curriculum.txt ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Comprehensive Summary of the Ontario Grades 9-10 Canadian and World Studies Curriculum with a Focus on History
2
+
3
+ The Ontario Grades 9-10 Canadian and World Studies curriculum integrates Geography, History, and Civics to prepare students for active, informed citizenship. Below is a detailed overview, emphasizing History while incorporating relevant cross-disciplinary elements.
4
+ Vision and Goals
5
+
6
+ The curriculum aims to develop responsible, critically thoughtful citizens who:
7
+
8
+ Understand the historical, geographic, and political dimensions of their world.
9
+ Use critical thinking to address complex issues.
10
+ Respect diverse perspectives and cultures.
11
+
12
+ Core Goals for History (Grade 10)
13
+
14
+ Develop a Sense of Time and Identity:
15
+ Explore questions like:
16
+ "Who are we?"
17
+ "Who came before us?"
18
+ "How have we changed?"
19
+ Understand the dynamic nature of Canada’s history, from World War I to the present.
20
+
21
+ Historical Thinking Concepts:
22
+ Significance: Identify and evaluate the importance of events and people in shaping Canada.
23
+ Cause and Consequence: Analyze historical events' causes and outcomes.
24
+ Continuity and Change: Examine patterns of stability and transformation over time.
25
+ Perspective: Understand and empathize with diverse historical viewpoints.
26
+
27
+ Civic and Global Awareness:
28
+ Link historical events to contemporary civic responsibilities.
29
+ Analyze Canada’s evolving role in global contexts.
30
+ Prepare students to become informed global citizens.
31
+
32
+ Cross-Disciplinary Strategies
33
+
34
+ Inquiry-Based Learning:
35
+ Use questions like:
36
+ "What happened?"
37
+ "Why did it happen?"
38
+ "Why does it matter?"
39
+ Investigate, interpret, and analyze historical evidence using primary and secondary sources.
40
+
41
+ Big Ideas and Framing Questions:
42
+ Encourage enduring understandings, such as:
43
+ The role of diverse groups in shaping Canada’s history.
44
+ The impact of policies like the Indian Act and residential schools.
45
+ Connections between past and present issues.
46
+
47
+ Concepts of Disciplinary Thinking:
48
+ Shared across history, geography, and civics:
49
+ Cause and Consequence: Analyze why events occur and their results.
50
+ Perspective: Respect differing views within historical and political contexts.
51
+ Patterns and Trends: Recognize recurring themes across disciplines.
52
+
53
+ Citizenship Education Framework:
54
+ Foster civic awareness and responsibility.
55
+ Develop collaborative and problem-solving skills.
56
+ Encourage participation in local and global communities.
57
+
58
+ Teaching and Learning Approaches
59
+
60
+ Integration of Indigenous Perspectives:
61
+ Respectfully explore Indigenous histories, treaties, and contemporary realities.
62
+ Address colonialism and systemic racism through authentic, accurate resources.
63
+
64
+ Critical Thinking and Literacy:
65
+ Analyze sources for reliability, bias, and context.
66
+ Construct well-supported arguments and proposals.
67
+
68
+ Experiential and Collaborative Learning:
69
+ Engage students through role-playing, discussions, and technology.
70
+ Use tools like GIS and digital maps for interactive geographic and historical exploration.
71
+
72
+ Emphasis on Diversity and Inclusivity:
73
+ Reflect diverse identities in curriculum materials.
74
+ Encourage empathy and understanding of marginalized communities.
75
+
76
+ Key Outcomes
77
+
78
+ Students completing the Grade 10 history course will:
79
+
80
+ Understand Canada’s heritage and identity, including its Indigenous roots.
81
+ Analyze and interpret historical and geographic evidence critically.
82
+ Build connections between historical events and present-day challenges.
83
+ Develop as empathetic, informed citizens who contribute positively to society.
84
+
85
+ Integration with Geography and Civics
86
+
87
+ Geography:
88
+ Develop spatial thinking and tools like maps and graphs to analyze historical and environmental patterns.
89
+ Explore connections between physical and human geography.
90
+
91
+ Civics:
92
+ Understand the rights and responsibilities of citizenship.
93
+ Examine governance and political structures’ roles in shaping history.
requirements.txt CHANGED
@@ -1,6 +1,6 @@
1
  streamlit
2
  openai
3
- faiss-cpu
4
  langchain
5
  PyPDF2
6
  tiktoken
@@ -9,3 +9,8 @@ sentence-transformers
9
  pytesseract
10
  pdf2image
11
  Pillow
 
 
 
 
 
 
1
  streamlit
2
  openai
3
+ faiss
4
  langchain
5
  PyPDF2
6
  tiktoken
 
9
  pytesseract
10
  pdf2image
11
  Pillow
12
+ tiktoken
13
+ numpy
14
+ transformers
15
+ pdf2image
16
+ pytesseract