ciaochris commited on
Commit
e0365b0
·
verified ·
1 Parent(s): 2af6b00

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -27
app.py CHANGED
@@ -129,34 +129,36 @@ def generate_tutor_output(subject: str, difficulty: str, student_input: str) ->
129
  if enhanced_topic:
130
  break
131
 
132
- # Enhanced prompt with explicit JSON requirement
133
  if enhanced_topic:
134
  logging.debug(f"Using enhanced topic: {enhanced_topic}")
135
  prompt = f"""
136
- You are an expert tutor specializing in {enhanced_topic} at the {difficulty} level. The student has asked about: "{student_input}"
137
- Provide your response as a valid JSON object with the following keys and content:
138
- - "lesson": A comprehensive lesson (3-4 paragraphs) based on national educational standards, including historical context.
139
  - "example": A detailed step-by-step example problem with a full solution, formatted as:
140
  - "Example Problem:" followed by the question
141
  - "Step 1:", "Step 2:", etc., each on a new line
142
  - "Answer:" with the final solution
143
- - "real_world_problem": A challenging real-world application of this concept.
144
- - "quiz": A short quiz with 3 multiple-choice questions (e.g., "1. Question text\n a) option1\n b) option2\n c) option3\nCorrect answer: a").
145
- Return only the JSON object, enclosed in ```json``` markers, with no additional text outside the markers.
 
146
  """
147
  else:
148
  logging.debug(f"Using general subject: {subject_lower}")
149
  prompt = f"""
150
- You are an expert tutor in {subject_lower} at the {difficulty} level. The student has provided: "{student_input}"
151
- Provide your response as a valid JSON object with the following keys and content:
152
- - "lesson": A descriptive, engaging lesson (3-4 paragraphs) on the topic.
153
  - "example": An example problem with a full solution, formatted as:
154
  - "Example Problem:" followed by the question
155
  - "Step 1:", "Step 2:", etc., each on a new line
156
  - "Answer:" with the final solution
157
- - "real_world_problem": A real-world problem solvable using the lesson concepts.
158
- - "quiz": A short quiz with 3 multiple-choice questions (e.g., "1. Question text\n a) option1\n b) option2\n c) option3\nCorrect answer: a").
159
- Return only the JSON object, enclosed in ```json``` markers, with no additional text outside the markers.
 
160
  """
161
 
162
  # Model selection with fallback
@@ -175,7 +177,7 @@ def generate_tutor_output(subject: str, difficulty: str, student_input: str) ->
175
  messages=[
176
  {
177
  "role": "system",
178
- "content": f"You are the world's best AI tutor, renowned for your ability to explain complex concepts clearly and engagingly. Your expertise in {subject_lower} is unparalleled, and you tailor your teaching to {difficulty} level students. Always return responses as valid JSON enclosed in ```json``` markers.",
179
  },
180
  {
181
  "role": "user",
@@ -183,7 +185,7 @@ def generate_tutor_output(subject: str, difficulty: str, student_input: str) ->
183
  }
184
  ],
185
  model=target_model,
186
- max_tokens=2000,
187
  )
188
 
189
  response_content = completion.choices[0].message.content
@@ -203,7 +205,7 @@ def generate_tutor_output(subject: str, difficulty: str, student_input: str) ->
203
  logging.warning("No JSON markers found in response")
204
  result = None
205
 
206
- # Fallback parsing if JSON extraction fails
207
  if not result:
208
  logging.debug("Falling back to text parsing")
209
  sections = {
@@ -218,36 +220,40 @@ def generate_tutor_output(subject: str, difficulty: str, student_input: str) ->
218
  line = line.strip()
219
  if not line or line.startswith('```'):
220
  continue
221
- if "Lesson:" in line or line.startswith("1."):
 
222
  current_section = "lesson"
223
  sections[current_section] += line.replace("Lesson:", "").replace("1.", "").strip() + "\n"
224
- elif "Example:" in line or line.startswith("2."):
225
  current_section = "example"
226
  sections[current_section] += line.replace("Example:", "").replace("2.", "").strip() + "\n"
227
- elif "Real-World Application:" in line or "Real-World Problem:" in line or line.startswith("3."):
228
  current_section = "real_world_problem"
229
  sections[current_section] += line.replace("Real-World Application:", "").replace("Real-World Problem:", "").replace("3.", "").strip() + "\n"
230
- elif "Quiz:" in line or line.startswith("4."):
231
  current_section = "quiz"
232
  sections[current_section] += line.replace("Quiz:", "").replace("4.", "").strip() + "\n"
233
  elif current_section:
234
  sections[current_section] += line + "\n"
235
 
 
 
 
236
  # Check if any section was populated
237
  if any(sections.values()):
238
  result = sections
239
  else:
240
  result = {
241
- "lesson": "Failed to parse lesson content",
242
- "example": "Failed to parse example content",
243
- "real_world_problem": "Failed to parse real-world application content",
244
- "quiz": "Failed to parse quiz content"
245
  }
246
 
247
- # Ensure all keys are present
248
  for key in ["lesson", "example", "real_world_problem", "quiz"]:
249
- if key not in result:
250
- result[key] = f"No {key.replace('_', ' ')} provided"
251
 
252
  return result
253
 
 
129
  if enhanced_topic:
130
  break
131
 
132
+ # Strengthened prompt to ensure all sections are generated
133
  if enhanced_topic:
134
  logging.debug(f"Using enhanced topic: {enhanced_topic}")
135
  prompt = f"""
136
+ You are an expert tutor specializing in {enhanced_topic} at the {difficulty} level. The student has asked: "{student_input}"
137
+ Generate a detailed response as a valid JSON object with exactly these keys and content:
138
+ - "lesson": A comprehensive lesson (3-4 paragraphs, at least 200 words) based on national educational standards, including historical context.
139
  - "example": A detailed step-by-step example problem with a full solution, formatted as:
140
  - "Example Problem:" followed by the question
141
  - "Step 1:", "Step 2:", etc., each on a new line
142
  - "Answer:" with the final solution
143
+ - "real_world_problem": A challenging real-world application of this concept (at least 100 words).
144
+ - "quiz": A short quiz with 3 multiple-choice questions, each formatted as:
145
+ - "1. Question text\n a) option1\n b) option2\n c) option3\n Correct answer: a"
146
+ Ensure all sections are fully populated with relevant content. Return only the JSON object, enclosed in ```json``` markers, with no additional text outside the markers.
147
  """
148
  else:
149
  logging.debug(f"Using general subject: {subject_lower}")
150
  prompt = f"""
151
+ You are an expert tutor in {subject_lower} at the {difficulty} level. The student has asked: "{student_input}"
152
+ Generate a detailed response as a valid JSON object with exactly these keys and content:
153
+ - "lesson": A descriptive, engaging lesson (3-4 paragraphs, at least 200 words) on the topic.
154
  - "example": An example problem with a full solution, formatted as:
155
  - "Example Problem:" followed by the question
156
  - "Step 1:", "Step 2:", etc., each on a new line
157
  - "Answer:" with the final solution
158
+ - "real_world_problem": A real-world problem solvable using the lesson concepts (at least 100 words).
159
+ - "quiz": A short quiz with 3 multiple-choice questions, each formatted as:
160
+ - "1. Question text\n a) option1\n b) option2\n c) option3\n Correct answer: a"
161
+ Ensure all sections are fully populated with relevant content. Return only the JSON object, enclosed in ```json``` markers, with no additional text outside the markers.
162
  """
163
 
164
  # Model selection with fallback
 
177
  messages=[
178
  {
179
  "role": "system",
180
+ "content": f"You are the world's best AI tutor, renowned for your ability to explain complex concepts clearly and engagingly. Your expertise in {subject_lower} is unparalleled, and you tailor your teaching to {difficulty} level students. Always return a complete response with all requested sections as a valid JSON object enclosed in ```json``` markers.",
181
  },
182
  {
183
  "role": "user",
 
185
  }
186
  ],
187
  model=target_model,
188
+ max_tokens=4000, # Increased to ensure full response
189
  )
190
 
191
  response_content = completion.choices[0].message.content
 
205
  logging.warning("No JSON markers found in response")
206
  result = None
207
 
208
+ # Improved fallback parsing if JSON extraction fails
209
  if not result:
210
  logging.debug("Falling back to text parsing")
211
  sections = {
 
220
  line = line.strip()
221
  if not line or line.startswith('```'):
222
  continue
223
+ # More flexible section detection
224
+ if any(kw in line.lower() for kw in ["lesson", "1.", "overview", "introduction"]):
225
  current_section = "lesson"
226
  sections[current_section] += line.replace("Lesson:", "").replace("1.", "").strip() + "\n"
227
+ elif any(kw in line.lower() for kw in ["example", "2.", "problem", "solution"]):
228
  current_section = "example"
229
  sections[current_section] += line.replace("Example:", "").replace("2.", "").strip() + "\n"
230
+ elif any(kw in line.lower() for kw in ["real-world", "application", "3.", "practical"]):
231
  current_section = "real_world_problem"
232
  sections[current_section] += line.replace("Real-World Application:", "").replace("Real-World Problem:", "").replace("3.", "").strip() + "\n"
233
+ elif any(kw in line.lower() for kw in ["quiz", "4.", "question", "test"]):
234
  current_section = "quiz"
235
  sections[current_section] += line.replace("Quiz:", "").replace("4.", "").strip() + "\n"
236
  elif current_section:
237
  sections[current_section] += line + "\n"
238
 
239
+ # Log parsed sections for debugging
240
+ logging.debug(f"Parsed sections: {sections}")
241
+
242
  # Check if any section was populated
243
  if any(sections.values()):
244
  result = sections
245
  else:
246
  result = {
247
+ "lesson": "Failed to generate lesson content",
248
+ "example": "Failed to generate example content",
249
+ "real_world_problem": "Failed to generate real-world application content",
250
+ "quiz": "Failed to generate quiz content"
251
  }
252
 
253
+ # Ensure all keys are present and non-empty
254
  for key in ["lesson", "example", "real_world_problem", "quiz"]:
255
+ if key not in result or not result[key].strip():
256
+ result[key] = f"No {key.replace('_', ' ')} provided - generation incomplete"
257
 
258
  return result
259