rak-301 commited on
Commit
6bb57e5
·
verified ·
1 Parent(s): 4fe3510

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +164 -163
app.py CHANGED
@@ -1,164 +1,165 @@
1
- import os
2
- import json
3
- from typing import List, Dict
4
-
5
- import streamlit as st
6
- from streamlit_chat import message
7
- from langchain.chat_models import ChatOpenAI
8
- from langchain.chains import LLMChain
9
- from langchain.prompts import PromptTemplate
10
-
11
- # Load configuration
12
- working_dir = os.path.dirname(os.path.abspath(__file__))
13
- with open(f"{working_dir}/config.json") as config_file:
14
- config_data = json.load(config_file)
15
- OPENAI_API_KEY = config_data["OPENAI_API_KEY"]
16
-
17
- # Configure Streamlit page
18
- st.set_page_config(page_title="Socratic Learning Bot", page_icon="🤖", layout="centered")
19
-
20
- # Initialize session state
21
- if "conversation" not in st.session_state:
22
- st.session_state.conversation = None
23
- if "chat_history" not in st.session_state:
24
- st.session_state.chat_history = []
25
- if "hint_level" not in st.session_state:
26
- st.session_state.hint_level = 1
27
-
28
-
29
- # Initialize LangChain components
30
- @st.cache_resource
31
- def initialize_conversation():
32
- llm = ChatOpenAI(
33
- temperature=0.7,
34
- openai_api_key=OPENAI_API_KEY,
35
- model_name="gpt-4"
36
- )
37
-
38
- template = """
39
- You are an AI tutor designed to help users learn programming concepts and problem-solving skills using a Socratic method. Your primary goal is to guide users towards solutions by asking thought-provoking questions and encouraging critical thinking. Follow these guidelines when responding to user queries:
40
-
41
- 1. Begin with questions:
42
- a. Ask the user to explain their understanding of the problem.
43
- b. Inquire about their current approach or thought process.
44
- c. Encourage them to think about potential edge cases or limitations.
45
-
46
- 2. If the user provides code, help them identify issues:
47
- a. Ask them to walk through their code step-by-step.
48
- b. Point out specific lines that may contain errors or inefficiencies.
49
- c. Encourage the user to think about why those lines might be problematic.
50
-
51
- 3. Provide hints in the following stages, only moving to the next stage if the user is stuck:
52
-
53
- a. Hint 1: Ask a leading question about the topic or sub-topic that guides them towards the solution.
54
- b. Hint 2: Provide a conceptual hint framed as a question, encouraging them to make connections.
55
- c. Hint 3: Offer a more detailed explanation, but frame it as a series of questions for the user to consider.
56
- d. Hint 4: Present pseudocode as a series of questions (e.g., "What if we first...? Then how would we...?").
57
- e. Hint 5: Provide a partial code skeleton with key parts missing, asking the user how they would fill in the gaps.
58
- f. Hint 6: As a last resort, provide a working solution, but ask the user to explain each part of the code.
59
-
60
- 4. Guide users through the problem-solving process from brute force to optimal solutions:
61
- a. Ask them to consider the simplest possible solution and its limitations.
62
- b. Encourage them to think about how they could improve upon their initial approach.
63
- c. Guide them towards optimization by asking about time and space complexity.
64
-
65
- 5. Continuously engage the user in the learning process:
66
- a. After each response from the user, ask follow-up questions to deepen their understanding.
67
- b. Encourage them to predict the outcome of their approach before testing it.
68
- c. If they seem confused, ask them to rephrase the problem or explain their current understanding.
69
-
70
- 6. Adaptively adjust your questioning:
71
- a. If the user is struggling, simplify your questions and provide more context.
72
- b. If the user is progressing well, ask more challenging questions to push their understanding further.
73
-
74
- 7. Before providing language-specific hints or code:
75
- a. Ask the user about their preferred programming language.
76
- b. Inquire about their familiarity with relevant language features or libraries.
77
-
78
- Remember, your role is to facilitate active learning. Avoid giving direct answers unless absolutely necessary. Always encourage users to arrive at solutions through their own reasoning and experimentation.
79
-
80
- Current hint level: {hint_level}
81
- Recent context:
82
- {context}
83
-
84
- Human: {human_input}
85
- AI Tutor: Let's approach this step-by-step. First, could you tell me more about...
86
- """
87
-
88
- prompt = PromptTemplate(
89
- input_variables=["context", "human_input", "hint_level"],
90
- template=template
91
- )
92
-
93
- return LLMChain(llm=llm, prompt=prompt)
94
-
95
-
96
- # Title
97
- st.title("🤖 Socratic Learning Bot")
98
-
99
-
100
- # Function to get bot response
101
- def get_bot_response(user_input: str) -> str:
102
- if st.session_state.conversation is None:
103
- st.session_state.conversation = initialize_conversation()
104
-
105
- # Include recent chat history for context
106
- recent_history = st.session_state.chat_history[-5:] # Last 5 messages
107
- context = "\n".join([f"{msg['role']}: {msg['content']}" for msg in recent_history])
108
-
109
- response = st.session_state.conversation.predict(
110
- context=context,
111
- human_input=user_input,
112
- hint_level=st.session_state.hint_level
113
- )
114
- return response
115
-
116
-
117
- # Function to display chat history
118
- def display_chat_history(history: List[Dict[str, str]]):
119
- for i, chat in enumerate(history):
120
- if chat["role"] == "user":
121
- message(chat["content"], is_user=True, key=f"{i}_user")
122
- else:
123
- message(chat["content"], is_user=False, key=f"{i}_bot")
124
-
125
-
126
- # Main chat interface
127
- def chat_interface():
128
- # Get initial context from the user
129
- if not st.session_state.chat_history:
130
- context = st.text_input("Please provide the programming topic or problem you'd like help with:")
131
- if context:
132
- bot_response = get_bot_response(f"The user wants help with the following topic or problem: {context}")
133
- st.session_state.chat_history.append({"role": "assistant", "content": bot_response})
134
-
135
- # Display chat history
136
- display_chat_history(st.session_state.chat_history)
137
-
138
- # Get user input
139
- user_input = st.text_input("Type your message here:", key="user_input")
140
-
141
- # Add buttons for user actions
142
- col1, col2, col3 = st.columns(3)
143
- with col1:
144
- if st.button("Send"):
145
- if user_input:
146
- st.session_state.chat_history.append({"role": "user", "content": user_input})
147
- bot_response = get_bot_response(user_input)
148
- st.session_state.chat_history.append({"role": "assistant", "content": bot_response})
149
- st.rerun()
150
- with col2:
151
- if st.button("Next Hint"):
152
- st.session_state.hint_level = min(st.session_state.hint_level + 1, 6)
153
- bot_response = get_bot_response("I need more help. Can you provide the next hint?")
154
- st.session_state.chat_history.append({"role": "assistant", "content": bot_response})
155
- st.rerun()
156
- with col3:
157
- if st.button("Reset Hints"):
158
- st.session_state.hint_level = 1
159
- st.session_state.chat_history.append({"role": "system", "content": "Hint level has been reset to 1."})
160
- st.rerun()
161
-
162
-
163
- if __name__ == "__main__":
 
164
  chat_interface()
 
1
+ import os
2
+ import json
3
+ from typing import List, Dict
4
+
5
+ import streamlit as st
6
+ from streamlit_chat import message
7
+ from langchain.chat_models import ChatOpenAI
8
+ from langchain.chains import LLMChain
9
+ from langchain.prompts import PromptTemplate
10
+
11
+ # Load configuration
12
+ # working_dir = os.path.dirname(os.path.abspath(__file__))
13
+ # with open(f"{working_dir}/config.json") as config_file:
14
+ # config_data = json.load(config_file)
15
+ # OPENAI_API_KEY = config_data["OPENAI_API_KEY"]
16
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
17
+
18
+ # Configure Streamlit page
19
+ st.set_page_config(page_title="Socratic Learning Bot", page_icon="🤖", layout="centered")
20
+
21
+ # Initialize session state
22
+ if "conversation" not in st.session_state:
23
+ st.session_state.conversation = None
24
+ if "chat_history" not in st.session_state:
25
+ st.session_state.chat_history = []
26
+ if "hint_level" not in st.session_state:
27
+ st.session_state.hint_level = 1
28
+
29
+
30
+ # Initialize LangChain components
31
+ @st.cache_resource
32
+ def initialize_conversation():
33
+ llm = ChatOpenAI(
34
+ temperature=0.7,
35
+ openai_api_key=OPENAI_API_KEY,
36
+ model_name="gpt-4"
37
+ )
38
+
39
+ template = """
40
+ You are an AI tutor designed to help users learn programming concepts and problem-solving skills using a Socratic method. Your primary goal is to guide users towards solutions by asking thought-provoking questions and encouraging critical thinking. Follow these guidelines when responding to user queries:
41
+
42
+ 1. Begin with questions:
43
+ a. Ask the user to explain their understanding of the problem.
44
+ b. Inquire about their current approach or thought process.
45
+ c. Encourage them to think about potential edge cases or limitations.
46
+
47
+ 2. If the user provides code, help them identify issues:
48
+ a. Ask them to walk through their code step-by-step.
49
+ b. Point out specific lines that may contain errors or inefficiencies.
50
+ c. Encourage the user to think about why those lines might be problematic.
51
+
52
+ 3. Provide hints in the following stages, only moving to the next stage if the user is stuck:
53
+
54
+ a. Hint 1: Ask a leading question about the topic or sub-topic that guides them towards the solution.
55
+ b. Hint 2: Provide a conceptual hint framed as a question, encouraging them to make connections.
56
+ c. Hint 3: Offer a more detailed explanation, but frame it as a series of questions for the user to consider.
57
+ d. Hint 4: Present pseudocode as a series of questions (e.g., "What if we first...? Then how would we...?").
58
+ e. Hint 5: Provide a partial code skeleton with key parts missing, asking the user how they would fill in the gaps.
59
+ f. Hint 6: As a last resort, provide a working solution, but ask the user to explain each part of the code.
60
+
61
+ 4. Guide users through the problem-solving process from brute force to optimal solutions:
62
+ a. Ask them to consider the simplest possible solution and its limitations.
63
+ b. Encourage them to think about how they could improve upon their initial approach.
64
+ c. Guide them towards optimization by asking about time and space complexity.
65
+
66
+ 5. Continuously engage the user in the learning process:
67
+ a. After each response from the user, ask follow-up questions to deepen their understanding.
68
+ b. Encourage them to predict the outcome of their approach before testing it.
69
+ c. If they seem confused, ask them to rephrase the problem or explain their current understanding.
70
+
71
+ 6. Adaptively adjust your questioning:
72
+ a. If the user is struggling, simplify your questions and provide more context.
73
+ b. If the user is progressing well, ask more challenging questions to push their understanding further.
74
+
75
+ 7. Before providing language-specific hints or code:
76
+ a. Ask the user about their preferred programming language.
77
+ b. Inquire about their familiarity with relevant language features or libraries.
78
+
79
+ Remember, your role is to facilitate active learning. Avoid giving direct answers unless absolutely necessary. Always encourage users to arrive at solutions through their own reasoning and experimentation.
80
+
81
+ Current hint level: {hint_level}
82
+ Recent context:
83
+ {context}
84
+
85
+ Human: {human_input}
86
+ AI Tutor: Let's approach this step-by-step. First, could you tell me more about...
87
+ """
88
+
89
+ prompt = PromptTemplate(
90
+ input_variables=["context", "human_input", "hint_level"],
91
+ template=template
92
+ )
93
+
94
+ return LLMChain(llm=llm, prompt=prompt)
95
+
96
+
97
+ # Title
98
+ st.title("🤖 Socratic Learning Bot")
99
+
100
+
101
+ # Function to get bot response
102
+ def get_bot_response(user_input: str) -> str:
103
+ if st.session_state.conversation is None:
104
+ st.session_state.conversation = initialize_conversation()
105
+
106
+ # Include recent chat history for context
107
+ recent_history = st.session_state.chat_history[-5:] # Last 5 messages
108
+ context = "\n".join([f"{msg['role']}: {msg['content']}" for msg in recent_history])
109
+
110
+ response = st.session_state.conversation.predict(
111
+ context=context,
112
+ human_input=user_input,
113
+ hint_level=st.session_state.hint_level
114
+ )
115
+ return response
116
+
117
+
118
+ # Function to display chat history
119
+ def display_chat_history(history: List[Dict[str, str]]):
120
+ for i, chat in enumerate(history):
121
+ if chat["role"] == "user":
122
+ message(chat["content"], is_user=True, key=f"{i}_user")
123
+ else:
124
+ message(chat["content"], is_user=False, key=f"{i}_bot")
125
+
126
+
127
+ # Main chat interface
128
+ def chat_interface():
129
+ # Get initial context from the user
130
+ if not st.session_state.chat_history:
131
+ context = st.text_input("Please provide the programming topic or problem you'd like help with:")
132
+ if context:
133
+ bot_response = get_bot_response(f"The user wants help with the following topic or problem: {context}")
134
+ st.session_state.chat_history.append({"role": "assistant", "content": bot_response})
135
+
136
+ # Display chat history
137
+ display_chat_history(st.session_state.chat_history)
138
+
139
+ # Get user input
140
+ user_input = st.text_input("Type your message here:", key="user_input")
141
+
142
+ # Add buttons for user actions
143
+ col1, col2, col3 = st.columns(3)
144
+ with col1:
145
+ if st.button("Send"):
146
+ if user_input:
147
+ st.session_state.chat_history.append({"role": "user", "content": user_input})
148
+ bot_response = get_bot_response(user_input)
149
+ st.session_state.chat_history.append({"role": "assistant", "content": bot_response})
150
+ st.rerun()
151
+ with col2:
152
+ if st.button("Next Hint"):
153
+ st.session_state.hint_level = min(st.session_state.hint_level + 1, 6)
154
+ bot_response = get_bot_response("I need more help. Can you provide the next hint?")
155
+ st.session_state.chat_history.append({"role": "assistant", "content": bot_response})
156
+ st.rerun()
157
+ with col3:
158
+ if st.button("Reset Hints"):
159
+ st.session_state.hint_level = 1
160
+ st.session_state.chat_history.append({"role": "system", "content": "Hint level has been reset to 1."})
161
+ st.rerun()
162
+
163
+
164
+ if __name__ == "__main__":
165
  chat_interface()