abhilashnl2006 commited on
Commit
eefc6b5
1 Parent(s): a6474a0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +93 -59
app.py CHANGED
@@ -12,112 +12,146 @@ openai.api_key = api_key
12
 
13
  def generate_exercise_question(topic):
14
  try:
15
- # Construct the initial message for exercise generation
16
- messages = [{"role": "system", "content": "You are an AI tutor specialized in teaching Python programming. Your primary task is to create exercise questions based on the topics users want to learn. Provide clear, concise, and informative exercises. Ensure that all your responses strictly adhere to the subject of Python programming and do not engage in any discussions that are insensitive, sexual, casual, comedic, or unrelated to Python programming."}]
17
- messages.append({"role": "user", "content": f"Create an exercise question on {topic}."})
18
 
19
- # Generate a response using gpt-3.5-turbo
20
  response = openai.ChatCompletion.create(
21
  model="gpt-3.5-turbo",
22
  messages=messages,
23
- max_tokens=150,
24
  n=1,
25
  stop=None,
26
  temperature=0.7,
27
- stream=False
28
  )
29
 
30
- question = response['choices'][0]['message']['content'].strip()
31
  return question
32
  except Exception as e:
33
  return f"Error: {str(e)}"
34
 
35
- def check_answer(topic, user_code):
36
  try:
37
- # Construct the messages for checking the answer
38
- messages = [{"role": "system", "content": "You are an AI tutor specialized in teaching Python programming. Your primary task is to create and evaluate exercise questions based on the topics users want to learn. Ensure that all your responses strictly adhere to the subject of Python programming and do not engage in any discussions that are insensitive, sexual, casual, comedic, or unrelated to Python programming."}]
39
- messages.append({"role": "user", "content": f"Check this answer for an exercise on {topic}: {user_code}."})
40
 
41
- # Generate a response using gpt-3.5-turbo
42
  response = openai.ChatCompletion.create(
43
  model="gpt-3.5-turbo",
44
  messages=messages,
45
- max_tokens=150,
46
  n=1,
47
  stop=None,
48
  temperature=0.7,
49
- stream=False
50
  )
51
 
52
- feedback = response['choices'][0]['message']['content'].strip()
53
  return feedback
54
  except Exception as e:
55
  return f"Error: {str(e)}"
56
 
57
- def respond(message, chat_history):
58
- if chat_history is None:
59
- chat_history = []
60
-
61
- if message.lower() == "next":
62
- topic = chat_history[0][0] if chat_history else ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  question = generate_exercise_question(topic)
64
  chat_history.append((message, question))
65
- return "", chat_history, chat_history, topic, gr.update(visible=True)
66
  else:
67
- # Check if this is the first message to set the topic
68
- if len(chat_history) == 0:
69
- topic = message
70
  question = generate_exercise_question(topic)
71
  chat_history.append((message, question))
72
- return "", chat_history, chat_history, topic, gr.update(visible=True)
73
  else:
74
- chat_history.append((message, "Please answer the question or type 'next' for another question on the same topic."))
75
- return "", chat_history, chat_history, "", None
76
 
77
  def submit_code(topic, user_code, chat_history):
78
- feedback = check_answer(topic, user_code)
79
- chat_history.append((user_code, feedback))
80
- return "", chat_history, chat_history, "", None
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
  def clear():
83
- return [], [], "", ""
84
 
85
- # Create the Gradio interface
86
  with gr.Blocks() as demo:
87
- gr.Markdown("# Python Tutor")
88
- gr.Markdown("Helps you learn Python using the latest documentation.")
89
 
90
  chatbot = gr.Chatbot(label="Python Tutor")
91
- state = gr.State([])
92
- topic_state = gr.State("")
93
 
94
  with gr.Row():
95
- with gr.Column():
96
  user_input = gr.Textbox(
97
  show_label=False,
98
- placeholder="Type the Python topic you want to learn about...",
99
  lines=1
100
  )
 
 
101
  submit_button = gr.Button("Submit")
102
- next_button = gr.Button("Next")
103
- code_input = gr.Code(language="python", lines=10, visible=False)
104
  clear_button = gr.Button("Clear")
105
 
106
- submit_button.click(respond, [user_input, state], [user_input, state, chatbot, topic_state, code_input])
107
- submit_button.click(submit_code, [topic_state, code_input, state], [code_input, state, chatbot, topic_state], queue=False)
108
- next_button.click(respond, inputs=["next", state], outputs=[user_input, state, chatbot, topic_state, code_input])
109
- clear_button.click(clear, None, [chatbot, state, topic_state])
110
-
111
- examples = [
112
- ["lists"],
113
- ["decorators"],
114
- ["dictionaries"],
115
- ["file handling"],
116
- ["classes and objects"]
117
- ]
118
-
119
- # Add examples
120
- gr.Examples(examples=examples, inputs=[user_input])
121
-
122
- # Launch the app
123
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
  def generate_exercise_question(topic):
14
  try:
15
+ messages = [{"role": "system", "content": "You are an AI tutor specialized in teaching Python programming. Your task is to create exercise questions based on the given topic. Provide clear, concise, and informative exercises. Include a specific task for the user to implement, along with example input and expected output."}]
16
+ messages.append({"role": "user", "content": f"Create an exercise question on {topic} with a specific task, example input, and expected output."})
 
17
 
 
18
  response = openai.ChatCompletion.create(
19
  model="gpt-3.5-turbo",
20
  messages=messages,
21
+ max_tokens=250,
22
  n=1,
23
  stop=None,
24
  temperature=0.7,
 
25
  )
26
 
27
+ question = response.choices[0].message['content'].strip()
28
  return question
29
  except Exception as e:
30
  return f"Error: {str(e)}"
31
 
32
+ def check_answer(topic, exercise, user_code):
33
  try:
34
+ messages = [{"role": "system", "content": "You are an AI tutor specialized in teaching Python programming. Your task is to evaluate the user's code for the given exercise. Provide feedback on correctness and suggest improvements if needed."}]
35
+ messages.append({"role": "user", "content": f"Evaluate this answer for the exercise on {topic}: \nExercise: {exercise}\nUser's code: {user_code}"})
 
36
 
 
37
  response = openai.ChatCompletion.create(
38
  model="gpt-3.5-turbo",
39
  messages=messages,
40
+ max_tokens=250,
41
  n=1,
42
  stop=None,
43
  temperature=0.7,
 
44
  )
45
 
46
+ feedback = response.choices[0].message['content'].strip()
47
  return feedback
48
  except Exception as e:
49
  return f"Error: {str(e)}"
50
 
51
+ def get_solution(topic, exercise):
52
+ try:
53
+ messages = [{"role": "system", "content": "You are an AI tutor specialized in teaching Python programming. Your task is to provide a correct solution for the given exercise."}]
54
+ messages.append({"role": "user", "content": f"Provide the correct solution code for this exercise on {topic}: {exercise}"})
55
+
56
+ response = openai.ChatCompletion.create(
57
+ model="gpt-3.5-turbo",
58
+ messages=messages,
59
+ max_tokens=250,
60
+ n=1,
61
+ stop=None,
62
+ temperature=0.7,
63
+ )
64
+
65
+ solution = response.choices[0].message['content'].strip()
66
+ return solution
67
+ except Exception as e:
68
+ return f"Error: {str(e)}"
69
+
70
+ def respond(message, chat_history, topic, show_code_editor):
71
+ if not chat_history:
72
+ topic = message
73
  question = generate_exercise_question(topic)
74
  chat_history.append((message, question))
75
+ return "", chat_history, topic, True
76
  else:
77
+ if message.lower() == "next":
 
 
78
  question = generate_exercise_question(topic)
79
  chat_history.append((message, question))
80
+ return "", chat_history, topic, True
81
  else:
82
+ chat_history.append((message, "Please submit your code using the code editor below."))
83
+ return "", chat_history, topic, show_code_editor
84
 
85
  def submit_code(topic, user_code, chat_history):
86
+ exercise = chat_history[-2][1] # Get the last exercise question
87
+ feedback = check_answer(topic, exercise, user_code)
88
+
89
+ if "correct" in feedback.lower():
90
+ response = f"{feedback}\n\nGreat job! Type 'next' to see the next question."
91
+ else:
92
+ solution = get_solution(topic, exercise)
93
+ response = f"{feedback}\n\nHere's the correct solution:\n\n{solution}\n\nType 'next' to see the next question."
94
+
95
+ chat_history.append((user_code, response))
96
+ return "", chat_history, False # Hide code editor after submission
97
+
98
+ def undo(chat_history, show_code_editor):
99
+ if chat_history:
100
+ chat_history.pop()
101
+ return chat_history, True if len(chat_history) > 0 else False
102
 
103
  def clear():
104
+ return [], "", False
105
 
 
106
  with gr.Blocks() as demo:
107
+ gr.Markdown("# Python Practice Bot")
108
+ gr.Markdown("Learn Python through exercises. Start by entering a topic you want to practice.")
109
 
110
  chatbot = gr.Chatbot(label="Python Tutor")
111
+ topic = gr.State("")
112
+ show_code_editor = gr.State(False)
113
 
114
  with gr.Row():
115
+ with gr.Column(scale=3):
116
  user_input = gr.Textbox(
117
  show_label=False,
118
+ placeholder="Enter a Python topic or type 'next' for a new question...",
119
  lines=1
120
  )
121
+ code_input = gr.Code(language="python", label="Your Solution", visible=False)
122
+ with gr.Column(scale=1):
123
  submit_button = gr.Button("Submit")
124
+ code_submit_button = gr.Button("Submit Code", visible=False)
125
+ undo_button = gr.Button("Undo")
126
  clear_button = gr.Button("Clear")
127
 
128
+ submit_button.click(
129
+ respond,
130
+ [user_input, chatbot, topic, show_code_editor],
131
+ [user_input, chatbot, topic, show_code_editor],
132
+ queue=False
133
+ ).then(
134
+ lambda x: gr.update(visible=x),
135
+ [show_code_editor],
136
+ [code_input, code_submit_button]
137
+ )
138
+
139
+ code_submit_button.click(
140
+ submit_code,
141
+ [topic, code_input, chatbot],
142
+ [code_input, chatbot, show_code_editor]
143
+ ).then(
144
+ lambda x: gr.update(visible=x),
145
+ [show_code_editor],
146
+ [code_input, code_submit_button]
147
+ )
148
+
149
+ undo_button.click(undo, [chatbot, show_code_editor], [chatbot, show_code_editor])
150
+ clear_button.click(clear, None, [chatbot, topic, show_code_editor])
151
+
152
+ gr.Examples(
153
+ examples=[["lists"], ["decorators"], ["dictionaries"], ["file handling"], ["classes and objects"]],
154
+ inputs=[user_input]
155
+ )
156
+
157
+ demo.launch()