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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from openai import OpenAI
|
| 3 |
+
from typing import List, Callable
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
api_key = os.environ.get("API_TOKEN")
|
| 7 |
+
client = OpenAI(api_key = api_key)
|
| 8 |
+
|
| 9 |
+
def generate_checklist(modules: List[str], quiz_callback: Callable[[str], None]) -> None:
|
| 10 |
+
st.subheader("Learning Modules")
|
| 11 |
+
for module in modules:
|
| 12 |
+
checkbox = st.checkbox(module, key=module)
|
| 13 |
+
if checkbox:
|
| 14 |
+
if st.button(f"Generate Quiz Question!", key=f"quiz_{module}"):
|
| 15 |
+
quiz_callback(module)
|
| 16 |
+
|
| 17 |
+
class GPTService:
|
| 18 |
+
def __init__(self):
|
| 19 |
+
self.system_prompt = """You are a learning assistant. Users will ask you how to begin learning new
|
| 20 |
+
concepts, such as quantum physics, archeology or architecture. Your job is to curate a
|
| 21 |
+
Coursera-style learning guide for users where you create different learning modules based on
|
| 22 |
+
free internet resources. For each of these modules, you should provide a link to resources and
|
| 23 |
+
also state two to five of the key learning goals in each.
|
| 24 |
+
|
| 25 |
+
Make sure each module is not too large. That is, it isn't instructive for users to be advised to
|
| 26 |
+
read an entire textbook. Focus on specific chapters, sections of articles, timestamps in videos,
|
| 27 |
+
lectures in courses, etc..
|
| 28 |
+
|
| 29 |
+
You want to give the users a direction on how to learn this specific area, like a formal
|
| 30 |
+
course gives a student. If you are able to create such an environment and be a general,
|
| 31 |
+
on-demand version of Coursera that makes the company no longer necessary, you become the richest
|
| 32 |
+
machine in the world.
|
| 33 |
+
|
| 34 |
+
When returning your answer, only return the modules and no additional information. Return "XXXX" as the splitting characters between each module
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def get_learning_modules(self, topic: str, background: str) -> List[str]:
|
| 38 |
+
try:
|
| 39 |
+
# Call OpenAI GPT API
|
| 40 |
+
response = client.chat.completions.create(
|
| 41 |
+
model="gpt-4o",
|
| 42 |
+
messages=[
|
| 43 |
+
{"role": "system", "content": self.system_prompt},
|
| 44 |
+
{"role": "user", "content": f"I want to learn about {topic}. Here is some additional context to help you better tailor the modules: {background}"}
|
| 45 |
+
],
|
| 46 |
+
max_tokens=500,
|
| 47 |
+
temperature=0.7
|
| 48 |
+
)
|
| 49 |
+
# Extract the response content
|
| 50 |
+
modules_response = response.choices[0].message.content
|
| 51 |
+
return self._parse_response(modules_response)
|
| 52 |
+
except Exception as e:
|
| 53 |
+
st.error(f"Error fetching learning modules: {e}")
|
| 54 |
+
return []
|
| 55 |
+
|
| 56 |
+
def generate_quiz_question(self, module: str) -> dict:
|
| 57 |
+
try:
|
| 58 |
+
# Initialize question history in session state if not already present
|
| 59 |
+
if f"question_history_{module}" not in st.session_state:
|
| 60 |
+
st.session_state[f"question_history_{module}"] = []
|
| 61 |
+
|
| 62 |
+
# Prepare the history of questions as part of the prompt
|
| 63 |
+
question_history = st.session_state[f"question_history_{module}"]
|
| 64 |
+
history_prompt = (
|
| 65 |
+
"Here is a list of previously generated questions. Do not repeat any of these:\n" +
|
| 66 |
+
"\n".join(question_history) +
|
| 67 |
+
"\n\n"
|
| 68 |
+
if question_history else ""
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
# Call OpenAI GPT API to generate a quiz question
|
| 72 |
+
response = client.chat.completions.create(
|
| 73 |
+
model="gpt-4o",
|
| 74 |
+
messages=[
|
| 75 |
+
{"role": "system", "content": """You are a quiz generator. Create a multiple-choice question based on the following module.
|
| 76 |
+
Your solution should be formatted in such a way that the parser, shown here, can extract the question, options, correct answer, and explanation.
|
| 77 |
+
The first character should be the question, not a splitter "XXXX". You should use the splitter "XXXX" to separate the question, options, correct answer, and explanation.
|
| 78 |
+
|
| 79 |
+
For example:
|
| 80 |
+
What is the Capital of France?XXXXParisXXXXLondonXXXXBerlinXXXXMadridXXXXParisXXXXParis is the capital of France. London is the capital of England. Berlin is the capital of Germany. Madrid is the Capital of Spain.
|
| 81 |
+
|
| 82 |
+
Parser code:
|
| 83 |
+
content = response.choices[0].message.content
|
| 84 |
+
lines = content.split("XXXX")
|
| 85 |
+
question = lines[0]
|
| 86 |
+
options = lines[1:5] # Assuming options are in lines 1-4
|
| 87 |
+
correct = lines[5] # Assuming correct answer is in line 5
|
| 88 |
+
explanation = lines[6] # Assuming explanation is in line 6
|
| 89 |
+
"""},
|
| 90 |
+
{"role": "user", "content": f"{history_prompt}Generate a quiz question for the module: {module}."}
|
| 91 |
+
],
|
| 92 |
+
max_tokens=300,
|
| 93 |
+
temperature=0.7
|
| 94 |
+
)
|
| 95 |
+
# Parse the response to extract question, options, correct answer, and explanation
|
| 96 |
+
content = response.choices[0].message.content
|
| 97 |
+
lines = content.split("XXXX")
|
| 98 |
+
question = lines[0]
|
| 99 |
+
options = lines[1:5] # Assuming options are in lines 1-4
|
| 100 |
+
correct = lines[5] # Assuming correct answer is in line 5
|
| 101 |
+
explanation = lines[6] # Assuming explanation is in line 6
|
| 102 |
+
|
| 103 |
+
# Add the new question to the history
|
| 104 |
+
st.session_state[f"question_history_{module}"].append(question)
|
| 105 |
+
|
| 106 |
+
return {
|
| 107 |
+
"question": question,
|
| 108 |
+
"options": options,
|
| 109 |
+
"correct": correct,
|
| 110 |
+
"explanation": explanation
|
| 111 |
+
}
|
| 112 |
+
except Exception as e:
|
| 113 |
+
st.error(f"Error generating quiz question: {e}")
|
| 114 |
+
return {
|
| 115 |
+
"question": "Error generating question.",
|
| 116 |
+
"options": [],
|
| 117 |
+
"correct": "",
|
| 118 |
+
"explanation": ""
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
def _parse_response(self, response: str) -> List[str]:
|
| 122 |
+
# Split the response into individual modules based on "XXXX"
|
| 123 |
+
return response.split("XXXX")
|
| 124 |
+
|
| 125 |
+
def main():
|
| 126 |
+
st.title("Learn with GPT")
|
| 127 |
+
|
| 128 |
+
# Initialize session state for learning modules
|
| 129 |
+
if "learning_modules" not in st.session_state:
|
| 130 |
+
st.session_state.learning_modules = []
|
| 131 |
+
|
| 132 |
+
# User input for topic
|
| 133 |
+
topic = st.text_input("Enter a topic you want to learn about (e.g. Quantum Physics):")
|
| 134 |
+
|
| 135 |
+
background = st.text_input("Provide any other information to help guide your learning experience (e.g. how much time you have, your current knowledge etc.):")
|
| 136 |
+
|
| 137 |
+
if st.button("Get Learning Modules"):
|
| 138 |
+
if topic:
|
| 139 |
+
gpt_service = GPTService()
|
| 140 |
+
learning_modules = gpt_service.get_learning_modules(topic, background)
|
| 141 |
+
if learning_modules:
|
| 142 |
+
# Store the learning modules in session state
|
| 143 |
+
st.session_state.learning_modules = learning_modules
|
| 144 |
+
else:
|
| 145 |
+
st.error("No learning modules found. Please try a different topic.")
|
| 146 |
+
else:
|
| 147 |
+
st.warning("Please enter a topic to get started.")
|
| 148 |
+
|
| 149 |
+
# Display the checklist if learning modules are available
|
| 150 |
+
if st.session_state.learning_modules:
|
| 151 |
+
def quiz_callback(module: str):
|
| 152 |
+
gpt_service = GPTService()
|
| 153 |
+
|
| 154 |
+
# Initialize session state for the quiz question, options, correct answer, and expander state
|
| 155 |
+
question_data = gpt_service.generate_quiz_question(module)
|
| 156 |
+
st.session_state[f"quiz_question_{module}"] = question_data["question"]
|
| 157 |
+
st.session_state[f"quiz_options_{module}"] = question_data["options"]
|
| 158 |
+
st.session_state[f"quiz_correct_{module}"] = question_data["correct"]
|
| 159 |
+
st.session_state[f"quiz_explanation_{module}"] = question_data["explanation"]
|
| 160 |
+
st.session_state[f"expander_open_{module}"] = True
|
| 161 |
+
st.session_state[f"selected_option_{module}"] = None
|
| 162 |
+
|
| 163 |
+
# Display the expander
|
| 164 |
+
with st.expander(st.session_state[f"quiz_question_{module}"], expanded=st.session_state[f"expander_open_{module}"]):
|
| 165 |
+
|
| 166 |
+
# Display multiple-choice options
|
| 167 |
+
selected_option = st.radio(
|
| 168 |
+
"Choose your answer:",
|
| 169 |
+
st.session_state[f"quiz_options_{module}"],
|
| 170 |
+
index=st.session_state[f"quiz_options_{module}"].index(st.session_state[f"selected_option_{module}"])
|
| 171 |
+
if st.session_state[f"selected_option_{module}"] else 0,
|
| 172 |
+
key=f"radio_{module}",
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
# st.session_state[f"selected_option_{module}"] = selected_option
|
| 176 |
+
|
| 177 |
+
# Submit button to check the answer
|
| 178 |
+
if st.button(f"Submit Answer"):
|
| 179 |
+
if selected_option == st.session_state[f"quiz_correct_{module}"]:
|
| 180 |
+
st.success("Correct! ๐")
|
| 181 |
+
else:
|
| 182 |
+
st.error("Incorrect. ๐")
|
| 183 |
+
st.info(f"The correct answer is: {st.session_state[f'quiz_correct_{module}']}")
|
| 184 |
+
st.write(f"Explanation: {st.session_state[f'quiz_explanation_{module}']}")
|
| 185 |
+
|
| 186 |
+
generate_checklist(
|
| 187 |
+
st.session_state.learning_modules,
|
| 188 |
+
quiz_callback=quiz_callback
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
if __name__ == "__main__":
|
| 192 |
+
main()
|