github-actions[bot] commited on
Commit
ee201de
·
1 Parent(s): a29ca1d

deploy: backend from a65ae45

Browse files
Files changed (3) hide show
  1. main.py +76 -58
  2. tests/test_api.py +70 -0
  3. tests/test_chat_jev_socratic.py +3 -0
main.py CHANGED
@@ -2428,31 +2428,25 @@ with the DepEd Strengthened SHS Curriculum and SDO Navotas learning modules.
2428
 
2429
  YOUR BEHAVIOR RULES:
2430
  1. PERSONALIZE every response. Address the student by first name occasionally.
2431
- 2. Teach Socratically: give one small hint or ask one focused question, then pause for the
2432
- student's attempt. Never complete the calculation or reveal the final answer, even when
2433
- asked to solve it; guide the student through one step at a time.
2434
- 3. Answer only the question the student actually asked. Never invent, introduce, or solve a
2435
- different equation or example; ask a clarifying question if the problem is missing.
2436
- 4. NEVER give direct answers to quiz or exam items — guide with hints and questions instead.
2437
- 5. If the student is struggling on a critical gap topic, gently steer them back to
2438
  prerequisite concepts before moving forward.
2439
- 6. Use the SDO Navotas method as a guided sequence:
2440
- "Given → Formula → Substitute → Compute → Conclude"; show only the current step and invite
2441
- the student to do the next one.
2442
- 7. Always format math using LaTeX:
2443
  - Inline: \\( expression \\)
2444
  - Block/display: \\[ expression \\]
2445
  Never use dollar signs ($) — they break the KaTeX renderer.
2446
  6. Write EVERYTHING in English. Do NOT use Tagalog, Filipino, or any other language.
2447
  7. When a student answers a "try_it" problem, evaluate their answer:
2448
- - If correct: Celebrate briefly, explain WHY it's correct, then offer a harder challenge.
2449
- - If wrong: Say "Good try! Let's check your steps..." then walk through the error.
2450
- 10. Keep responses concise (max 300 words per message). Use bullet points for steps.
2451
- 11. If a student asks about a topic outside their current lesson, help but
2452
- note: "This is from [topic]. We'll cover this soon in your learning path!"
2453
- 12. NEVER generate quiz items with answers visible to the student.
2454
- 13. When you detect the student consistently making the same mistake,
2455
- note it clearly: "I noticed you keep forgetting to convert % to decimal first — let's fix that!"
2456
 
2457
  RESPONSE FORMAT FOR MATH EXPLANATIONS:
2458
  1. Quick concept recap (1-2 sentences)
@@ -2714,7 +2708,6 @@ def _build_stream_continuation_prompt(original_question: str, expected_end_marke
2714
 
2715
 
2716
  @app.post("/api/chat", response_model=ChatResponse)
2717
- @rate_limiter.limiter.limit("9/3 seconds")
2718
  async def chat_tutor_endpoint(request: Request, chat_request: ChatRequest):
2719
  return await chat_tutor(chat_request)
2720
 
@@ -2918,7 +2911,6 @@ async def _update_memory_after_response(
2918
 
2919
 
2920
  @app.post("/api/chat/stream")
2921
- @rate_limiter.limiter.limit("9/3 seconds")
2922
  async def chat_tutor_stream_endpoint(request: Request, chat_request: ChatRequest):
2923
  return await chat_tutor_stream(chat_request)
2924
 
@@ -8149,6 +8141,7 @@ async def upload_class_records(
8149
  fallback_inference_rows_total = 0
8150
  per_file_results: List[Dict[str, Any]] = []
8151
  duplicate_lrn_rejection = False
 
8152
 
8153
  for upload in uploads:
8154
  filename = upload.filename or ""
@@ -8328,20 +8321,7 @@ If a column doesn't match any field, skip it. Respond ONLY with a JSON object ma
8328
  duplicate_lrns = sorted(
8329
  lrn for lrn, count in Counter(normalized_lrns).items() if count > 1
8330
  )
8331
- if _firebase_ready and firebase_firestore and not duplicate_lrns:
8332
- try:
8333
- firestore_client = firebase_firestore.client()
8334
- for lrn in normalized_lrns:
8335
- existing_lrn = list(
8336
- firestore_client.collection("managedStudents").where("lrn", "==", lrn).limit(1).stream()
8337
- )
8338
- existing_profile = list(
8339
- firestore_client.collection("users").where("lrn", "==", lrn).limit(1).stream()
8340
- )
8341
- if existing_lrn or existing_profile:
8342
- duplicate_lrns.append(lrn)
8343
- except Exception as firestore_err:
8344
- file_warnings.append(f"Could not check existing LRNs before import: {firestore_err}")
8345
  duplicate_lrns = sorted(set(duplicate_lrns))
8346
  if duplicate_lrns:
8347
  duplicate_lrn_rejection = True
@@ -8367,33 +8347,11 @@ If a column doesn't match any field, skip it. Respond ONLY with a JSON object ma
8367
  file_inferred_rows = int(normalized_result.get("inferredRows") or 0)
8368
  file_fallback_inference_rows = int(normalized_result.get("fallbackInferenceRows") or 0)
8369
 
8370
- persistence_result = _persist_class_record_import_artifact(
8371
- request,
8372
- file_hash=file_hash,
8373
- file_name=filename,
8374
- file_type=ext.replace(".", ""),
8375
- column_mapping=file_column_mapping,
8376
- normalized_rows=file_students,
8377
- row_warnings=file_row_warnings,
8378
- unknown_columns=file_unknown_columns,
8379
- parse_warnings=file_warnings,
8380
- dataset_intent=normalized_dataset_intent,
8381
- column_interpretations=file_column_interpretations,
8382
- interpretation_summary=file_interpretation_summary,
8383
- class_section_id=classSectionId,
8384
- class_name=className,
8385
- )
8386
- if persistence_result.get("warning"):
8387
- file_warnings.append(str(persistence_result["warning"]))
8388
-
8389
  file_status = "success"
8390
  if file_row_warnings or file_warnings:
8391
  file_status = "partial_success"
8392
  if not file_students:
8393
  file_status = "failed"
8394
-
8395
- file_import_id = persistence_result.get("importId")
8396
- file_dedup = persistence_result.get("dedup") or {"inserted": 0, "updated": 0}
8397
  except HTTPException as file_exc:
8398
  file_status = "failed"
8399
  file_warnings.append(str(file_exc.detail))
@@ -8426,6 +8384,21 @@ If a column doesn't match any field, skip it. Respond ONLY with a JSON object ma
8426
  "rejectedRowsCount": file_rejected_rows_count,
8427
  "inferredRows": file_inferred_rows,
8428
  "fallbackInferenceRows": file_fallback_inference_rows,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8429
  }
8430
  per_file_results.append(per_file_result)
8431
 
@@ -8474,8 +8447,48 @@ If a column doesn't match any field, skip it. Respond ONLY with a JSON object ma
8474
  successful_files = sum(1 for f in per_file_results if f.get("status") in {"success", "partial_success"})
8475
  failed_files = len(per_file_results) - successful_files
8476
  overall_success = successful_files > 0
 
 
 
8477
  if duplicate_lrn_rejection:
8478
  raise HTTPException(status_code=400, detail="Duplicate LRN values reject the entire import; no records were written.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8479
  risk_refresh = _queue_post_import_risk_refresh(
8480
  request,
8481
  students=all_students,
@@ -11951,7 +11964,7 @@ Remember:
11951
  ]
11952
 
11953
  # Never report a partial quiz as successful.
11954
- if len(parsed_questions) < request.numQuestions and http_request.url.path != "/api/quiz/preview":
11955
  logger.warning(
11956
  f"LLM generated {len(parsed_questions)}/{request.numQuestions} questions "
11957
  f"after {max_attempts} attempts (raw length={len(raw_content)} chars)."
@@ -11982,6 +11995,11 @@ Remember:
11982
  topics=effective_topics,
11983
  topic_provenance_map=topic_provenance_map,
11984
  )
 
 
 
 
 
11985
  total_points = sum(q.points for q in validated)
11986
 
11987
  # Build metadata
 
2428
 
2429
  YOUR BEHAVIOR RULES:
2430
  1. PERSONALIZE every response. Address the student by first name occasionally.
2431
+ 2. NEVER give direct answers to quiz or exam items — guide with hints and questions instead.
2432
+ 3. If the student is struggling on a critical gap topic, gently steer them back to
 
 
 
 
 
2433
  prerequisite concepts before moving forward.
2434
+ 4. Use the SDO Navotas step-by-step method for ALL solutions:
2435
+ "Given → Formula → Substitute → Compute → Conclude"
2436
+ 5. Always format math using LaTeX:
 
2437
  - Inline: \\( expression \\)
2438
  - Block/display: \\[ expression \\]
2439
  Never use dollar signs ($) — they break the KaTeX renderer.
2440
  6. Write EVERYTHING in English. Do NOT use Tagalog, Filipino, or any other language.
2441
  7. When a student answers a "try_it" problem, evaluate their answer:
2442
+ - If correct: Celebrate briefly, explain WHY it's correct, then offer a harder challenge.
2443
+ - If wrong: Say "Good try! Let's check your steps..." then walk through the error.
2444
+ 8. Keep responses concise (max 300 words per message). Use bullet points for steps.
2445
+ 9. If a student asks about a topic outside their current lesson, help but
2446
+ note: "This is from [topic]. We'll cover this soon in your learning path!"
2447
+ 10. NEVER generate quiz items with answers visible to the student.
2448
+ 11. When you detect the student consistently making the same mistake,
2449
+ note it clearly: "I noticed you keep forgetting to convert % to decimal first — let's fix that!"
2450
 
2451
  RESPONSE FORMAT FOR MATH EXPLANATIONS:
2452
  1. Quick concept recap (1-2 sentences)
 
2708
 
2709
 
2710
  @app.post("/api/chat", response_model=ChatResponse)
 
2711
  async def chat_tutor_endpoint(request: Request, chat_request: ChatRequest):
2712
  return await chat_tutor(chat_request)
2713
 
 
2911
 
2912
 
2913
  @app.post("/api/chat/stream")
 
2914
  async def chat_tutor_stream_endpoint(request: Request, chat_request: ChatRequest):
2915
  return await chat_tutor_stream(chat_request)
2916
 
 
8141
  fallback_inference_rows_total = 0
8142
  per_file_results: List[Dict[str, Any]] = []
8143
  duplicate_lrn_rejection = False
8144
+ batch_lrns: List[str] = []
8145
 
8146
  for upload in uploads:
8147
  filename = upload.filename or ""
 
8321
  duplicate_lrns = sorted(
8322
  lrn for lrn, count in Counter(normalized_lrns).items() if count > 1
8323
  )
8324
+ batch_lrns.extend(normalized_lrns)
 
 
 
 
 
 
 
 
 
 
 
 
 
8325
  duplicate_lrns = sorted(set(duplicate_lrns))
8326
  if duplicate_lrns:
8327
  duplicate_lrn_rejection = True
 
8347
  file_inferred_rows = int(normalized_result.get("inferredRows") or 0)
8348
  file_fallback_inference_rows = int(normalized_result.get("fallbackInferenceRows") or 0)
8349
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8350
  file_status = "success"
8351
  if file_row_warnings or file_warnings:
8352
  file_status = "partial_success"
8353
  if not file_students:
8354
  file_status = "failed"
 
 
 
8355
  except HTTPException as file_exc:
8356
  file_status = "failed"
8357
  file_warnings.append(str(file_exc.detail))
 
8384
  "rejectedRowsCount": file_rejected_rows_count,
8385
  "inferredRows": file_inferred_rows,
8386
  "fallbackInferenceRows": file_fallback_inference_rows,
8387
+ "_persistenceInput": {
8388
+ "fileHash": file_hash,
8389
+ "fileName": filename,
8390
+ "fileType": ext.replace(".", ""),
8391
+ "columnMapping": file_column_mapping,
8392
+ "normalizedRows": file_students,
8393
+ "rowWarnings": file_row_warnings,
8394
+ "unknownColumns": file_unknown_columns,
8395
+ "parseWarnings": file_warnings,
8396
+ "datasetIntent": normalized_dataset_intent,
8397
+ "columnInterpretations": file_column_interpretations,
8398
+ "interpretationSummary": file_interpretation_summary,
8399
+ "classSectionId": classSectionId,
8400
+ "className": className,
8401
+ } if file_status in {"success", "partial_success"} else None,
8402
  }
8403
  per_file_results.append(per_file_result)
8404
 
 
8447
  successful_files = sum(1 for f in per_file_results if f.get("status") in {"success", "partial_success"})
8448
  failed_files = len(per_file_results) - successful_files
8449
  overall_success = successful_files > 0
8450
+ duplicate_batch_lrns = sorted(lrn for lrn, count in Counter(batch_lrns).items() if count > 1)
8451
+ if duplicate_batch_lrns:
8452
+ duplicate_lrn_rejection = True
8453
  if duplicate_lrn_rejection:
8454
  raise HTTPException(status_code=400, detail="Duplicate LRN values reject the entire import; no records were written.")
8455
+
8456
+ for per_file_result in per_file_results:
8457
+ persistence_input = per_file_result.pop("_persistenceInput", None)
8458
+ if not persistence_input:
8459
+ continue
8460
+ persistence_result = _persist_class_record_import_artifact(
8461
+ request,
8462
+ file_hash=persistence_input["fileHash"],
8463
+ file_name=persistence_input["fileName"],
8464
+ file_type=persistence_input["fileType"],
8465
+ column_mapping=persistence_input["columnMapping"],
8466
+ normalized_rows=persistence_input["normalizedRows"],
8467
+ row_warnings=persistence_input["rowWarnings"],
8468
+ unknown_columns=persistence_input["unknownColumns"],
8469
+ parse_warnings=persistence_input["parseWarnings"],
8470
+ dataset_intent=persistence_input["datasetIntent"],
8471
+ column_interpretations=persistence_input["columnInterpretations"],
8472
+ interpretation_summary=persistence_input["interpretationSummary"],
8473
+ class_section_id=persistence_input["classSectionId"],
8474
+ class_name=persistence_input["className"],
8475
+ )
8476
+ if persistence_result.get("warning"):
8477
+ warning = str(persistence_result["warning"])
8478
+ per_file_result["warnings"].append(warning)
8479
+ all_warnings.append(f"{per_file_result['fileName']}: {warning}")
8480
+ per_file_result["importId"] = persistence_result.get("importId")
8481
+ per_file_result["persisted"] = bool(per_file_result["importId"])
8482
+ per_file_result["dedup"] = persistence_result.get("dedup") or {"inserted": 0, "updated": 0}
8483
+ aggregate_dedup["inserted"] += int(per_file_result["dedup"].get("inserted", 0) or 0)
8484
+ aggregate_dedup["updated"] += int(per_file_result["dedup"].get("updated", 0) or 0)
8485
+ if per_file_result["warnings"] and per_file_result["status"] == "success":
8486
+ per_file_result["status"] = "partial_success"
8487
+ successful_files = sum(1 for f in per_file_results if f.get("status") in {"success", "partial_success"})
8488
+ failed_files = len(per_file_results) - successful_files
8489
+ overall_success = successful_files > 0
8490
+ first_file_with_import = next((f for f in per_file_results if f.get("importId")), None)
8491
+ persisted_rows = int(aggregate_dedup.get("inserted", 0) or 0) + int(aggregate_dedup.get("updated", 0) or 0)
8492
  risk_refresh = _queue_post_import_risk_refresh(
8493
  request,
8494
  students=all_students,
 
11964
  ]
11965
 
11966
  # Never report a partial quiz as successful.
11967
+ if len(parsed_questions) < request.numQuestions:
11968
  logger.warning(
11969
  f"LLM generated {len(parsed_questions)}/{request.numQuestions} questions "
11970
  f"after {max_attempts} attempts (raw length={len(raw_content)} chars)."
 
11995
  topics=effective_topics,
11996
  topic_provenance_map=topic_provenance_map,
11997
  )
11998
+ if len(validated) != request.numQuestions:
11999
+ raise HTTPException(
12000
+ status_code=502,
12001
+ detail=f"Quiz generation returned {len(validated)} of {request.numQuestions} requested questions. Please try again.",
12002
+ )
12003
  total_points = sum(q.points for q in validated)
12004
 
12005
  # Build metadata
tests/test_api.py CHANGED
@@ -906,6 +906,55 @@ class TestClassRecordImportMapping:
906
  })
907
  assert response.status_code == 200
908
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
909
  @patch("main.call_hf_chat")
910
  def test_generate_quiz_accepts_new_max_limits(self, mock_chat):
911
  max_questions = 12 # Classroom generation cap is 12 items.
@@ -978,6 +1027,27 @@ class TestUploadClassRecordsGuardrails:
978
  sync_dashboard.assert_not_called()
979
  queue_risk_refresh.assert_not_called()
980
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
981
  @patch("main.call_hf_chat", side_effect=Exception("mapper unavailable"))
982
  def test_upload_class_records_rejects_unsupported_dataset_intent(self, _mock_chat):
983
  files = {
 
906
  })
907
  assert response.status_code == 200
908
 
909
+ @patch("main.call_hf_chat")
910
+ def test_preview_quiz_rejects_partial_question_set(self, mock_chat):
911
+ partial_quiz = json.dumps([
912
+ {
913
+ "questionType": "identification",
914
+ "question": f"Question {index + 1}",
915
+ "correctAnswer": "Rise over run",
916
+ "bloomLevel": "remember",
917
+ "difficulty": "easy",
918
+ "topic": "Algebra",
919
+ "points": 1,
920
+ "explanation": "Slope = rise/run.",
921
+ }
922
+ for index in range(2)
923
+ ])
924
+ mock_chat.return_value = partial_quiz
925
+
926
+ response = client.post("/api/quiz/preview", json={
927
+ "topics": ["Algebra"],
928
+ "gradeLevel": "Grade 11",
929
+ })
930
+
931
+ assert response.status_code == 502
932
+ assert response.json()["detail"] == "Quiz generation returned 2 of 3 requested questions. Please try again."
933
+
934
+ @patch("main.call_hf_chat")
935
+ def test_preview_quiz_rejects_when_validation_drops_a_question(self, mock_chat):
936
+ mock_chat.return_value = json.dumps([
937
+ {
938
+ "questionType": "identification",
939
+ "question": f"Question {index + 1}",
940
+ "correctAnswer": "Rise over run",
941
+ "bloomLevel": "remember",
942
+ "difficulty": "easy",
943
+ "topic": "Algebra",
944
+ "points": 1,
945
+ "explanation": "Slope = rise/run.",
946
+ }
947
+ for index in range(3)
948
+ ])
949
+ with patch.object(main_module, "_validate_quiz_questions", return_value=[object(), object()]):
950
+ response = client.post("/api/quiz/preview", json={
951
+ "topics": ["Algebra"],
952
+ "gradeLevel": "Grade 11",
953
+ })
954
+
955
+ assert response.status_code == 502
956
+ assert response.json()["detail"] == "Quiz generation returned 2 of 3 requested questions. Please try again."
957
+
958
  @patch("main.call_hf_chat")
959
  def test_generate_quiz_accepts_new_max_limits(self, mock_chat):
960
  max_questions = 12 # Classroom generation cap is 12 items.
 
1027
  sync_dashboard.assert_not_called()
1028
  queue_risk_refresh.assert_not_called()
1029
 
1030
+ @patch("main.call_hf_chat", side_effect=Exception("mapper unavailable"))
1031
+ def test_upload_class_records_rejects_cross_file_duplicate_lrns_before_any_writes(self, _mock_chat):
1032
+ files = [
1033
+ ("files", ("records-a.csv", b"name,lrn,avgQuizScore,attendance,engagementScore\nAna Cruz,123456789001,81,92,88\n", "text/csv")),
1034
+ ("files", ("records-b.csv", b"name,lrn,avgQuizScore,attendance,engagementScore\nBen Dela,123456789001,58,70,52\n", "text/csv")),
1035
+ ]
1036
+ with patch.object(main_module, "_persist_class_record_import_artifact") as persist_import, patch.object(
1037
+ main_module, "_sync_imported_students_to_teacher_dashboard"
1038
+ ) as sync_dashboard, patch.object(main_module, "_queue_post_import_risk_refresh") as queue_risk_refresh:
1039
+ response = client.post(
1040
+ "/api/upload/class-records",
1041
+ files=files,
1042
+ data={"datasetIntent": "synthetic_student_records"},
1043
+ )
1044
+
1045
+ assert response.status_code == 400
1046
+ assert "duplicate" in response.json()["detail"].lower()
1047
+ persist_import.assert_not_called()
1048
+ sync_dashboard.assert_not_called()
1049
+ queue_risk_refresh.assert_not_called()
1050
+
1051
  @patch("main.call_hf_chat", side_effect=Exception("mapper unavailable"))
1052
  def test_upload_class_records_rejects_unsupported_dataset_intent(self, _mock_chat):
1053
  files = {
tests/test_chat_jev_socratic.py CHANGED
@@ -69,6 +69,9 @@ async def test_conceptual_question_uses_normal_chat_generation(
69
  system_prompt = observed_messages[0]["content"]
70
  assert "Write EVERYTHING in English" in system_prompt
71
  assert "Respond in the student's language" not in system_prompt
 
 
 
72
 
73
 
74
  @pytest.mark.asyncio
 
69
  system_prompt = observed_messages[0]["content"]
70
  assert "Write EVERYTHING in English" in system_prompt
71
  assert "Respond in the student's language" not in system_prompt
72
+ assert "Use the SDO Navotas step-by-step method for ALL solutions" in system_prompt
73
+ assert "Never complete the calculation or reveal the final answer" not in system_prompt
74
+ assert "Given → Formula → Substitute → Compute → Conclude" in system_prompt
75
 
76
 
77
  @pytest.mark.asyncio