Spaces:
Sleeping
Sleeping
github-actions[bot] commited on
Commit ·
846f533
1
Parent(s): f9f5d3e
deploy: backend from 8dd600c
Browse files- main.py +34 -1
- requirements.txt +1 -0
- routes/deepseek_rag_routes.py +57 -7
- routes/jev_routes.py +60 -0
- routes/rag_routes.py +28 -1
- services/jev_client.py +208 -0
- tests/test_api.py +16 -0
- tests/test_chat_jev_socratic.py +83 -0
- tests/test_jev_client.py +51 -0
- tests/test_jev_hybrid_backend.py +247 -0
- tests/test_jev_routes.py +80 -0
- tests/test_rag_lesson_jev.py +111 -0
- tests/test_weakness_jev.py +81 -0
main.py
CHANGED
|
@@ -130,6 +130,8 @@ from routes.intervention_routes import router as intervention_router
|
|
| 130 |
from routes.pipeline_routes import router as pipeline_router
|
| 131 |
from routes.deepseek_rag_routes import router as deepseek_rag_router
|
| 132 |
from routes.at_risk_resolution import router as at_risk_resolution_router
|
|
|
|
|
|
|
| 133 |
|
| 134 |
# Rate limiting (slowapi)
|
| 135 |
try:
|
|
@@ -395,6 +397,7 @@ PUBLIC_API_PATHS: Set[str] = {
|
|
| 395 |
"/api/quiz/topics",
|
| 396 |
"/api/rag/health",
|
| 397 |
"/api/templates/class-records",
|
|
|
|
| 398 |
}
|
| 399 |
|
| 400 |
ROLE_POLICIES: Dict[str, Set[str]] = {
|
|
@@ -1216,6 +1219,7 @@ app.include_router(intervention_router)
|
|
| 1216 |
app.include_router(pipeline_router)
|
| 1217 |
app.include_router(deepseek_rag_router)
|
| 1218 |
app.include_router(at_risk_resolution_router)
|
|
|
|
| 1219 |
|
| 1220 |
|
| 1221 |
# ─── Global Exception Handler ─────────────────────────────────
|
|
@@ -1836,6 +1840,7 @@ _MATH_SCOPE_PATTERNS: Tuple[re.Pattern[str], ...] = (
|
|
| 1836 |
re.compile(r"\b(?:difference between|relationship between|compare|contrast)\s+(?:\w+\s+){0,3}(?:and|vs|versus|with)", re.IGNORECASE),
|
| 1837 |
# Learning/understanding signals
|
| 1838 |
re.compile(r"\b(?:i don't understand|i don't get|i'm confused|help me|can you help|struggle|confus|difficult|hard to)\b", re.IGNORECASE),
|
|
|
|
| 1839 |
# Proof derivation
|
| 1840 |
re.compile(r"\b(?:proof|prove|derivation|derive|show that)\b", re.IGNORECASE),
|
| 1841 |
)
|
|
@@ -2223,8 +2228,11 @@ class ChatRequest(BaseModel):
|
|
| 2223 |
class ChatResponse(BaseModel):
|
| 2224 |
response: str
|
| 2225 |
verified: Optional[bool] = None
|
| 2226 |
-
confidence: Optional[
|
| 2227 |
warning: Optional[str] = None
|
|
|
|
|
|
|
|
|
|
| 2228 |
|
| 2229 |
|
| 2230 |
class StudentRiskData(BaseModel):
|
|
@@ -2711,6 +2719,31 @@ async def chat_tutor(request: ChatRequest):
|
|
| 2711 |
if boundary_response is not None:
|
| 2712 |
return ChatResponse(response=boundary_response)
|
| 2713 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2714 |
system_prompt = MATH_TUTOR_SYSTEM_PROMPT
|
| 2715 |
|
| 2716 |
# ─── Memory Context Injection ────────────────────────────
|
|
|
|
| 130 |
from routes.pipeline_routes import router as pipeline_router
|
| 131 |
from routes.deepseek_rag_routes import router as deepseek_rag_router
|
| 132 |
from routes.at_risk_resolution import router as at_risk_resolution_router
|
| 133 |
+
from routes.jev_routes import router as jev_router
|
| 134 |
+
from services.jev_client import route_student_intent
|
| 135 |
|
| 136 |
# Rate limiting (slowapi)
|
| 137 |
try:
|
|
|
|
| 397 |
"/api/quiz/topics",
|
| 398 |
"/api/rag/health",
|
| 399 |
"/api/templates/class-records",
|
| 400 |
+
"/api/jev/verify",
|
| 401 |
}
|
| 402 |
|
| 403 |
ROLE_POLICIES: Dict[str, Set[str]] = {
|
|
|
|
| 1219 |
app.include_router(pipeline_router)
|
| 1220 |
app.include_router(deepseek_rag_router)
|
| 1221 |
app.include_router(at_risk_resolution_router)
|
| 1222 |
+
app.include_router(jev_router)
|
| 1223 |
|
| 1224 |
|
| 1225 |
# ─── Global Exception Handler ─────────────────────────────────
|
|
|
|
| 1840 |
re.compile(r"\b(?:difference between|relationship between|compare|contrast)\s+(?:\w+\s+){0,3}(?:and|vs|versus|with)", re.IGNORECASE),
|
| 1841 |
# Learning/understanding signals
|
| 1842 |
re.compile(r"\b(?:i don't understand|i don't get|i'm confused|help me|can you help|struggle|confus|difficult|hard to)\b", re.IGNORECASE),
|
| 1843 |
+
re.compile(r"\b(?:give me|just give me|tell me)\s+(?:the\s+)?answer\b", re.IGNORECASE),
|
| 1844 |
# Proof derivation
|
| 1845 |
re.compile(r"\b(?:proof|prove|derivation|derive|show that)\b", re.IGNORECASE),
|
| 1846 |
)
|
|
|
|
| 2228 |
class ChatResponse(BaseModel):
|
| 2229 |
response: str
|
| 2230 |
verified: Optional[bool] = None
|
| 2231 |
+
confidence: Optional[float] = None
|
| 2232 |
warning: Optional[str] = None
|
| 2233 |
+
sources: List[Dict[str, Any]] = Field(default_factory=list)
|
| 2234 |
+
suggestedFollowups: List[str] = Field(default_factory=list)
|
| 2235 |
+
activeModel: Optional[str] = None
|
| 2236 |
|
| 2237 |
|
| 2238 |
class StudentRiskData(BaseModel):
|
|
|
|
| 2719 |
if boundary_response is not None:
|
| 2720 |
return ChatResponse(response=boundary_response)
|
| 2721 |
|
| 2722 |
+
if not request.history and not _skip_scope_check:
|
| 2723 |
+
try:
|
| 2724 |
+
intent_res = await route_student_intent(request.message)
|
| 2725 |
+
if (
|
| 2726 |
+
intent_res.get("choice") == "direct_answer_request"
|
| 2727 |
+
and float(intent_res.get("confidence", 0.0)) >= 0.80
|
| 2728 |
+
):
|
| 2729 |
+
return ChatResponse(
|
| 2730 |
+
response=(
|
| 2731 |
+
"I can guide you step-by-step, but I won't give the final answer "
|
| 2732 |
+
"directly! What is the governing formula or first step you think "
|
| 2733 |
+
"we should use here?"
|
| 2734 |
+
),
|
| 2735 |
+
sources=[],
|
| 2736 |
+
suggestedFollowups=[
|
| 2737 |
+
"What is the first step?",
|
| 2738 |
+
"Can you explain the formula?",
|
| 2739 |
+
"Give me a hint",
|
| 2740 |
+
],
|
| 2741 |
+
confidence=float(intent_res.get("confidence", 0.95)),
|
| 2742 |
+
activeModel="jev-socratic-router",
|
| 2743 |
+
)
|
| 2744 |
+
except Exception as intent_err:
|
| 2745 |
+
logger.warning("Jev intent routing failed; continuing with chat: %s", intent_err)
|
| 2746 |
+
|
| 2747 |
system_prompt = MATH_TUTOR_SYSTEM_PROMPT
|
| 2748 |
|
| 2749 |
# ─── Memory Context Injection ────────────────────────────
|
requirements.txt
CHANGED
|
@@ -29,3 +29,4 @@ google-api-python-client>=2.0.0
|
|
| 29 |
pypdf>=4.0.0
|
| 30 |
slowapi>=0.1.0
|
| 31 |
limits>=3.0.0
|
|
|
|
|
|
| 29 |
pypdf>=4.0.0
|
| 30 |
slowapi>=0.1.0
|
| 31 |
limits>=3.0.0
|
| 32 |
+
typesafe-sdk>=0.1.0
|
routes/deepseek_rag_routes.py
CHANGED
|
@@ -14,6 +14,7 @@ from fastapi import APIRouter
|
|
| 14 |
|
| 15 |
from services.ai_client import REASONER_MODEL, CHAT_MODEL
|
| 16 |
from services.inference_client import is_enabled, rag_grounded_completion, parse_json_response
|
|
|
|
| 17 |
from rag.curriculum_rag import (
|
| 18 |
retrieve_curriculum_context,
|
| 19 |
build_analysis_curriculum_context,
|
|
@@ -54,6 +55,31 @@ class WeaknessDetectionResponse(BaseModel):
|
|
| 54 |
source: str = "rule_based" # "deepseek" or "rule_based"
|
| 55 |
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
@router.post("/weakness-detection", response_model=WeaknessDetectionResponse)
|
| 58 |
async def detect_weaknesses(req: WeaknessDetectionRequest):
|
| 59 |
"""Detect topic-level weaknesses using RAG + DeepSeek, with rule-based fallback."""
|
|
@@ -75,11 +101,17 @@ async def detect_weaknesses(req: WeaknessDetectionRequest):
|
|
| 75 |
rule_flagged.append(topic_id)
|
| 76 |
rule_confidence[topic_id] = round(1.0 - accuracy, 2)
|
| 77 |
|
|
|
|
| 78 |
if not is_enabled() or not rule_flagged:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
return WeaknessDetectionResponse(
|
| 80 |
flagged_topics=rule_flagged,
|
| 81 |
confidence=rule_confidence,
|
| 82 |
-
reasoning_summary=
|
| 83 |
source="rule_based",
|
| 84 |
)
|
| 85 |
|
|
@@ -115,14 +147,32 @@ async def detect_weaknesses(req: WeaknessDetectionRequest):
|
|
| 115 |
'"reasoning_summary": "plain text for teacher dashboard, grounded in DepEd competencies"}'
|
| 116 |
)
|
| 117 |
|
| 118 |
-
|
| 119 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
|
| 121 |
if parsed and "flagged_topics" in parsed:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
return WeaknessDetectionResponse(
|
| 123 |
-
flagged_topics=
|
| 124 |
-
confidence=
|
| 125 |
-
|
|
|
|
|
|
|
|
|
|
| 126 |
source="deepseek",
|
| 127 |
)
|
| 128 |
|
|
@@ -130,7 +180,7 @@ async def detect_weaknesses(req: WeaknessDetectionRequest):
|
|
| 130 |
return WeaknessDetectionResponse(
|
| 131 |
flagged_topics=rule_flagged,
|
| 132 |
confidence=rule_confidence,
|
| 133 |
-
reasoning_summary=
|
| 134 |
source="rule_based",
|
| 135 |
)
|
| 136 |
|
|
|
|
| 14 |
|
| 15 |
from services.ai_client import REASONER_MODEL, CHAT_MODEL
|
| 16 |
from services.inference_client import is_enabled, rag_grounded_completion, parse_json_response
|
| 17 |
+
from services.jev_client import score_student_mastery
|
| 18 |
from rag.curriculum_rag import (
|
| 19 |
retrieve_curriculum_context,
|
| 20 |
build_analysis_curriculum_context,
|
|
|
|
| 55 |
source: str = "rule_based" # "deepseek" or "rule_based"
|
| 56 |
|
| 57 |
|
| 58 |
+
async def _annotate_mastery(
|
| 59 |
+
req: WeaknessDetectionRequest,
|
| 60 |
+
flagged_topics: list[str],
|
| 61 |
+
reasoning_summary: str,
|
| 62 |
+
) -> str:
|
| 63 |
+
annotations: list[str] = []
|
| 64 |
+
for topic in flagged_topics:
|
| 65 |
+
topic_questions = [q.model_dump() for q in req.questions if q.topic_id == topic]
|
| 66 |
+
try:
|
| 67 |
+
mastery = await score_student_mastery(
|
| 68 |
+
student_answers=topic_questions,
|
| 69 |
+
topic=topic,
|
| 70 |
+
)
|
| 71 |
+
if mastery.get("action") == "fallback_disabled" or "level" not in mastery:
|
| 72 |
+
continue
|
| 73 |
+
annotations.append(f"{topic} [Bloom Mastery: {mastery['level']}]")
|
| 74 |
+
except Exception as exc:
|
| 75 |
+
logger.warning("Jev mastery scoring failed for %s: %s", topic, exc)
|
| 76 |
+
continue
|
| 77 |
+
|
| 78 |
+
if not annotations:
|
| 79 |
+
return reasoning_summary
|
| 80 |
+
return f"{reasoning_summary} {'; '.join(annotations)}"
|
| 81 |
+
|
| 82 |
+
|
| 83 |
@router.post("/weakness-detection", response_model=WeaknessDetectionResponse)
|
| 84 |
async def detect_weaknesses(req: WeaknessDetectionRequest):
|
| 85 |
"""Detect topic-level weaknesses using RAG + DeepSeek, with rule-based fallback."""
|
|
|
|
| 101 |
rule_flagged.append(topic_id)
|
| 102 |
rule_confidence[topic_id] = round(1.0 - accuracy, 2)
|
| 103 |
|
| 104 |
+
standard_summary = "Rule-based detection: topics below 60% accuracy threshold."
|
| 105 |
if not is_enabled() or not rule_flagged:
|
| 106 |
+
reasoning_summary = await _annotate_mastery(
|
| 107 |
+
req,
|
| 108 |
+
rule_flagged,
|
| 109 |
+
standard_summary,
|
| 110 |
+
)
|
| 111 |
return WeaknessDetectionResponse(
|
| 112 |
flagged_topics=rule_flagged,
|
| 113 |
confidence=rule_confidence,
|
| 114 |
+
reasoning_summary=reasoning_summary,
|
| 115 |
source="rule_based",
|
| 116 |
)
|
| 117 |
|
|
|
|
| 147 |
'"reasoning_summary": "plain text for teacher dashboard, grounded in DepEd competencies"}'
|
| 148 |
)
|
| 149 |
|
| 150 |
+
try:
|
| 151 |
+
raw = rag_grounded_completion(REASONER_MODEL, system_prompt, user_prompt, temperature=0.1)
|
| 152 |
+
parsed = parse_json_response(raw)
|
| 153 |
+
except Exception as exc:
|
| 154 |
+
logger.warning(f"RAG grounded completion failed for weakness detection: {exc}, falling back to rule-based with Jev mastery")
|
| 155 |
+
parsed = None
|
| 156 |
|
| 157 |
if parsed and "flagged_topics" in parsed:
|
| 158 |
+
flagged_topics = [
|
| 159 |
+
topic for topic in parsed["flagged_topics"] if topic in rule_flagged
|
| 160 |
+
]
|
| 161 |
+
parsed_confidence = parsed.get("confidence", rule_confidence)
|
| 162 |
+
if not isinstance(parsed_confidence, dict):
|
| 163 |
+
parsed_confidence = rule_confidence
|
| 164 |
+
reasoning_summary = await _annotate_mastery(
|
| 165 |
+
req,
|
| 166 |
+
flagged_topics,
|
| 167 |
+
parsed.get("reasoning_summary", ""),
|
| 168 |
+
)
|
| 169 |
return WeaknessDetectionResponse(
|
| 170 |
+
flagged_topics=flagged_topics,
|
| 171 |
+
confidence={
|
| 172 |
+
topic: parsed_confidence.get(topic, rule_confidence[topic])
|
| 173 |
+
for topic in flagged_topics
|
| 174 |
+
},
|
| 175 |
+
reasoning_summary=reasoning_summary,
|
| 176 |
source="deepseek",
|
| 177 |
)
|
| 178 |
|
|
|
|
| 180 |
return WeaknessDetectionResponse(
|
| 181 |
flagged_topics=rule_flagged,
|
| 182 |
confidence=rule_confidence,
|
| 183 |
+
reasoning_summary=await _annotate_mastery(req, rule_flagged, standard_summary),
|
| 184 |
source="rule_based",
|
| 185 |
)
|
| 186 |
|
routes/jev_routes.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
from fastapi import APIRouter, HTTPException
|
| 7 |
+
from pydantic import BaseModel, ConfigDict
|
| 8 |
+
|
| 9 |
+
from services.jev_client import verify_lesson_factuality
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
logger = logging.getLogger(__name__)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class JevVerifyRequest(BaseModel):
|
| 16 |
+
model_config = ConfigDict(extra="forbid", strict=True)
|
| 17 |
+
|
| 18 |
+
referenceText: str
|
| 19 |
+
generatedText: str
|
| 20 |
+
claimType: str = "curriculum_alignment"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class JevVerifyResponse(BaseModel):
|
| 24 |
+
model_config = ConfigDict(extra="forbid", strict=True)
|
| 25 |
+
|
| 26 |
+
verified: bool
|
| 27 |
+
pCorrect: float
|
| 28 |
+
pLeak: float
|
| 29 |
+
action: str
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
router = APIRouter(prefix="/api/jev", tags=["jev"])
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@router.post("/verify", response_model=JevVerifyResponse)
|
| 36 |
+
async def verify_jev(request: JevVerifyRequest) -> JevVerifyResponse:
|
| 37 |
+
if len(request.referenceText) + len(request.generatedText) > 8000:
|
| 38 |
+
raise HTTPException(
|
| 39 |
+
status_code=400,
|
| 40 |
+
detail="Combined text exceeds 8000 characters limit",
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
try:
|
| 44 |
+
verification: dict[str, Any] = await verify_lesson_factuality(
|
| 45 |
+
request.referenceText,
|
| 46 |
+
request.generatedText,
|
| 47 |
+
)
|
| 48 |
+
except Exception as exc:
|
| 49 |
+
logger.exception("JEV verification failed")
|
| 50 |
+
raise HTTPException(
|
| 51 |
+
status_code=502,
|
| 52 |
+
detail="JEV verification service unavailable",
|
| 53 |
+
) from exc
|
| 54 |
+
verified = bool(verification.get("verified", True))
|
| 55 |
+
return JevVerifyResponse(
|
| 56 |
+
verified=verified,
|
| 57 |
+
pCorrect=float(verification.get("pCorrect", 1.0 if verified else 0.0)),
|
| 58 |
+
pLeak=float(verification.get("pLeak", 0.0)),
|
| 59 |
+
action=str(verification.get("action", "verified")),
|
| 60 |
+
)
|
routes/rag_routes.py
CHANGED
|
@@ -12,6 +12,7 @@ from fastapi import APIRouter, HTTPException, Request
|
|
| 12 |
from pydantic import BaseModel, Field, field_validator
|
| 13 |
|
| 14 |
from services.llm_json import extract_json_object
|
|
|
|
| 15 |
|
| 16 |
from services.inference_client import (
|
| 17 |
InferenceRequest,
|
|
@@ -457,7 +458,32 @@ async def rag_lesson(request: Request, payload: RagLessonRequest):
|
|
| 457 |
# ── Step 4: Parse & validate response ────────────────────────────────────
|
| 458 |
try:
|
| 459 |
parsed_lesson = _strip_thinking_and_parse(raw_explanation)
|
| 460 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 461 |
except Exception as exc:
|
| 462 |
logger.error(f"RAG parse error: {type(exc).__name__}: {exc}")
|
| 463 |
raise HTTPException(
|
|
@@ -534,6 +560,7 @@ async def rag_lesson(request: Request, payload: RagLessonRequest):
|
|
| 534 |
for row in chunks
|
| 535 |
],
|
| 536 |
"activeModel": get_model_for_task("rag_lesson"),
|
|
|
|
| 537 |
}
|
| 538 |
|
| 539 |
|
|
|
|
| 12 |
from pydantic import BaseModel, Field, field_validator
|
| 13 |
|
| 14 |
from services.llm_json import extract_json_object
|
| 15 |
+
from services.jev_client import verify_lesson_factuality
|
| 16 |
|
| 17 |
from services.inference_client import (
|
| 18 |
InferenceRequest,
|
|
|
|
| 458 |
# ── Step 4: Parse & validate response ────────────────────────────────────
|
| 459 |
try:
|
| 460 |
parsed_lesson = _strip_thinking_and_parse(raw_explanation)
|
| 461 |
+
lesson_title = payload.lessonTitle or payload.topic
|
| 462 |
+
ref_text = format_retrieved_chunks(chunks)
|
| 463 |
+
gen_text = json.dumps(parsed_lesson.get("sections", []), ensure_ascii=False)
|
| 464 |
+
try:
|
| 465 |
+
verification = await verify_lesson_factuality(
|
| 466 |
+
reference_text=ref_text,
|
| 467 |
+
generated_text=gen_text,
|
| 468 |
+
)
|
| 469 |
+
except Exception as exc:
|
| 470 |
+
logger.warning("Jev verification error: %s; failing open", exc)
|
| 471 |
+
verification = None
|
| 472 |
+
|
| 473 |
+
if verification is not None and (
|
| 474 |
+
not verification.get("verified", True)
|
| 475 |
+
or verification.get("pCorrect", 1.0) < 0.70
|
| 476 |
+
):
|
| 477 |
+
logger.warning(
|
| 478 |
+
"Jev factuality check failed (pCorrect=%.2f); replacing with grounded defaults",
|
| 479 |
+
verification.get("pCorrect", 0.0),
|
| 480 |
+
)
|
| 481 |
+
parsed_lesson = {
|
| 482 |
+
**parsed_lesson,
|
| 483 |
+
"sections": list(_build_grounded_defaults(lesson_title, chunks=chunks).values()),
|
| 484 |
+
}
|
| 485 |
+
else:
|
| 486 |
+
parsed_lesson = _ensure_7_sections(parsed_lesson, lesson_title, chunks=chunks)
|
| 487 |
except Exception as exc:
|
| 488 |
logger.error(f"RAG parse error: {type(exc).__name__}: {exc}")
|
| 489 |
raise HTTPException(
|
|
|
|
| 560 |
for row in chunks
|
| 561 |
],
|
| 562 |
"activeModel": get_model_for_task("rag_lesson"),
|
| 563 |
+
"jevVerification": verification,
|
| 564 |
}
|
| 565 |
|
| 566 |
|
services/jev_client.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small, fail-open TypeSafe adapters for student-learning judgments."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import asyncio
|
| 6 |
+
import logging
|
| 7 |
+
import os
|
| 8 |
+
from typing import Any, Callable, Mapping
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
CLIENT_TIMEOUT_SECONDS = 5.0
|
| 13 |
+
_REQUEST_LIMIT = asyncio.Semaphore(10)
|
| 14 |
+
|
| 15 |
+
try:
|
| 16 |
+
from typesafe_sdk import Choice, Noul, Score, TypeSafeClient
|
| 17 |
+
except ImportError: # Optional dependency: the backend remains usable offline.
|
| 18 |
+
Choice = None # type: ignore[assignment,misc]
|
| 19 |
+
Noul = None # type: ignore[assignment,misc]
|
| 20 |
+
Score = None # type: ignore[assignment,misc]
|
| 21 |
+
TypeSafeClient = None # type: ignore[assignment,misc]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _build_choice() -> Any:
|
| 25 |
+
if Choice is None:
|
| 26 |
+
return None
|
| 27 |
+
return Choice(
|
| 28 |
+
instructions="Classify the student's tutoring intent.",
|
| 29 |
+
criteria={
|
| 30 |
+
"direct_answer_request": "The student asks for a direct answer.",
|
| 31 |
+
"conceptual_confusion": "The student needs an explanation of a concept.",
|
| 32 |
+
"calculation_error": "The student made or reports a calculation error.",
|
| 33 |
+
"off_topic_or_frustrated": "The message is off-topic or expresses frustration.",
|
| 34 |
+
},
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _build_noul(instructions: str, true_criteria: str, false_criteria: str) -> Any:
|
| 39 |
+
if Noul is None:
|
| 40 |
+
return None
|
| 41 |
+
return Noul(
|
| 42 |
+
instructions=instructions,
|
| 43 |
+
criteria={"true": true_criteria, "false": false_criteria},
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _build_score() -> Any:
|
| 48 |
+
if Score is None:
|
| 49 |
+
return None
|
| 50 |
+
return Score(
|
| 51 |
+
instructions="Score the student's demonstrated Bloom mastery level.",
|
| 52 |
+
criteria=[
|
| 53 |
+
"0 Recall: remembers definitions or facts.",
|
| 54 |
+
"1 Procedural: follows a familiar procedure.",
|
| 55 |
+
"2 Conceptual Transfer: applies concepts to a new problem.",
|
| 56 |
+
"3 Metacognitive: explains and evaluates their own reasoning.",
|
| 57 |
+
],
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
INTENT_ROUTING = _build_choice()
|
| 62 |
+
FACTUAL_ALIGNMENT = _build_noul(
|
| 63 |
+
"Is the generated lesson supported by the reference text?",
|
| 64 |
+
"The generated lesson is factually aligned with the reference.",
|
| 65 |
+
"The generated lesson contains an unsupported or hallucinated claim.",
|
| 66 |
+
)
|
| 67 |
+
PEDAGOGICAL_LEAK = _build_noul(
|
| 68 |
+
"Does the response reveal the final solution instead of giving a Socratic hint?",
|
| 69 |
+
"The response leaks the final solution.",
|
| 70 |
+
"The response gives a Socratic hint without revealing the final solution.",
|
| 71 |
+
)
|
| 72 |
+
BLOOM_MASTERY_SCORE = _build_score()
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _fallback_intent() -> dict[str, Any]:
|
| 76 |
+
return {"action": "fallback_disabled", "choice": "conceptual_confusion"}
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _fallback_factuality() -> dict[str, Any]:
|
| 80 |
+
return {"action": "fallback_disabled", "verified": True}
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _fallback_mastery() -> dict[str, Any]:
|
| 84 |
+
return {"action": "fallback_disabled", "pCorrect": 1.0, "level": 0}
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _fallback_safety() -> dict[str, Any]:
|
| 88 |
+
return {"action": "fallback_disabled", "pLeak": 0.0, "safe": True}
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _api_key() -> str | None:
|
| 92 |
+
key = os.getenv("TYPESAFE_API_KEY", "").strip()
|
| 93 |
+
return key or None
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def _answer_field(answer: object, field_name: str, default: Any) -> Any:
|
| 97 |
+
if isinstance(answer, Mapping):
|
| 98 |
+
return answer.get(field_name, default)
|
| 99 |
+
return getattr(answer, field_name, default)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def _answers(response: object) -> Mapping[str, object]:
|
| 103 |
+
response_answers = getattr(response, "answers", {})
|
| 104 |
+
return response_answers if isinstance(response_answers, Mapping) else {}
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
async def _system_one(state: dict[str, Any], questions: dict[str, Any]) -> object:
|
| 108 |
+
if TypeSafeClient is None:
|
| 109 |
+
raise ImportError("typesafe_sdk is not installed")
|
| 110 |
+
|
| 111 |
+
async with _REQUEST_LIMIT:
|
| 112 |
+
client = TypeSafeClient(api_key=_api_key(), timeout=CLIENT_TIMEOUT_SECONDS)
|
| 113 |
+
call = asyncio.to_thread(client.system_one, state=state, questions=questions)
|
| 114 |
+
return await asyncio.wait_for(call, timeout=CLIENT_TIMEOUT_SECONDS)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
async def _call_or_fallback(
|
| 118 |
+
state: dict[str, Any],
|
| 119 |
+
questions: dict[str, Any],
|
| 120 |
+
fallback: Callable[[], dict[str, Any]],
|
| 121 |
+
) -> object | dict[str, Any]:
|
| 122 |
+
if _api_key() is None:
|
| 123 |
+
return fallback()
|
| 124 |
+
try:
|
| 125 |
+
return await _system_one(state, questions)
|
| 126 |
+
except (ImportError, asyncio.TimeoutError, OSError) as exc:
|
| 127 |
+
logger.warning("TypeSafe request unavailable: %s", exc)
|
| 128 |
+
except Exception as exc:
|
| 129 |
+
logger.warning("TypeSafe request failed: %s", exc)
|
| 130 |
+
return fallback()
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
async def route_student_intent(message: str) -> dict[str, Any]:
|
| 134 |
+
"""Classify a student's message into the tutoring intent taxonomy."""
|
| 135 |
+
response = await _call_or_fallback(
|
| 136 |
+
{"message": message}, {"intent": INTENT_ROUTING}, _fallback_intent
|
| 137 |
+
)
|
| 138 |
+
if isinstance(response, dict):
|
| 139 |
+
return response
|
| 140 |
+
answer = _answers(response).get("intent")
|
| 141 |
+
return {
|
| 142 |
+
"choice": _answer_field(answer, "choice", "conceptual_confusion"),
|
| 143 |
+
"confidence": _answer_field(answer, "confidence", 0.0),
|
| 144 |
+
"probabilities": _answer_field(answer, "probabilities", {}),
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
async def verify_lesson_factuality(
|
| 149 |
+
reference_text: str, generated_text: str
|
| 150 |
+
) -> dict[str, Any]:
|
| 151 |
+
"""Check generated lesson claims against the supplied reference."""
|
| 152 |
+
response = await _call_or_fallback(
|
| 153 |
+
{"reference_text": reference_text, "generated_text": generated_text},
|
| 154 |
+
{"factual_alignment": FACTUAL_ALIGNMENT},
|
| 155 |
+
_fallback_factuality,
|
| 156 |
+
)
|
| 157 |
+
if isinstance(response, dict):
|
| 158 |
+
return response
|
| 159 |
+
answer = _answers(response).get("factual_alignment")
|
| 160 |
+
alignment_probability = _answer_field(answer, "noul", 1.0)
|
| 161 |
+
return {
|
| 162 |
+
"verified": float(alignment_probability) >= 0.5,
|
| 163 |
+
"confidence": abs(float(alignment_probability) - 0.5) * 2,
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
async def score_student_mastery(
|
| 168 |
+
student_answers: list[dict[str, Any]], topic: str
|
| 169 |
+
) -> dict[str, Any]:
|
| 170 |
+
"""Estimate mastery from answers using four Bloom levels."""
|
| 171 |
+
response = await _call_or_fallback(
|
| 172 |
+
{"student_answers": student_answers, "topic": topic},
|
| 173 |
+
{"bloom_mastery_score": BLOOM_MASTERY_SCORE},
|
| 174 |
+
_fallback_mastery,
|
| 175 |
+
)
|
| 176 |
+
if isinstance(response, dict):
|
| 177 |
+
return response
|
| 178 |
+
answer = _answers(response).get("bloom_mastery_score")
|
| 179 |
+
level = _answer_field(answer, "score", _answer_field(answer, "level", 0))
|
| 180 |
+
return {"level": level, "pCorrect": _answer_field(answer, "confidence", 0.0)}
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
async def verify_solution_safety(
|
| 184 |
+
reference_steps: str, student_steps: str
|
| 185 |
+
) -> dict[str, Any]:
|
| 186 |
+
"""Check whether student-facing steps reveal the final solution."""
|
| 187 |
+
response = await _call_or_fallback(
|
| 188 |
+
{"reference_steps": reference_steps, "student_steps": student_steps},
|
| 189 |
+
{"pedagogical_leak": PEDAGOGICAL_LEAK},
|
| 190 |
+
_fallback_safety,
|
| 191 |
+
)
|
| 192 |
+
if isinstance(response, dict):
|
| 193 |
+
return response
|
| 194 |
+
answer = _answers(response).get("pedagogical_leak")
|
| 195 |
+
leak_probability = _answer_field(answer, "noul", 0.0)
|
| 196 |
+
return {"pLeak": leak_probability, "safe": not bool(leak_probability)}
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
__all__ = [
|
| 200 |
+
"BLOOM_MASTERY_SCORE",
|
| 201 |
+
"FACTUAL_ALIGNMENT",
|
| 202 |
+
"INTENT_ROUTING",
|
| 203 |
+
"PEDAGOGICAL_LEAK",
|
| 204 |
+
"route_student_intent",
|
| 205 |
+
"score_student_mastery",
|
| 206 |
+
"verify_lesson_factuality",
|
| 207 |
+
"verify_solution_safety",
|
| 208 |
+
]
|
tests/test_api.py
CHANGED
|
@@ -202,6 +202,22 @@ class TestAuthMiddleware:
|
|
| 202 |
|
| 203 |
|
| 204 |
class TestChatEndpoint:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
@patch("main.call_hf_chat")
|
| 206 |
def test_chat_success(self, mock_chat):
|
| 207 |
mock_chat.return_value = "Hello! 2+2=4."
|
|
|
|
| 202 |
|
| 203 |
|
| 204 |
class TestChatEndpoint:
|
| 205 |
+
@pytest.fixture(scope="class", autouse=True)
|
| 206 |
+
@classmethod
|
| 207 |
+
def pin_jev_intent(cls):
|
| 208 |
+
with patch.object(
|
| 209 |
+
main_module,
|
| 210 |
+
"route_student_intent",
|
| 211 |
+
new=AsyncMock(
|
| 212 |
+
return_value={
|
| 213 |
+
"choice": "conceptual_confusion",
|
| 214 |
+
"confidence": 0.0,
|
| 215 |
+
"action": "fallback_test",
|
| 216 |
+
}
|
| 217 |
+
),
|
| 218 |
+
):
|
| 219 |
+
yield
|
| 220 |
+
|
| 221 |
@patch("main.call_hf_chat")
|
| 222 |
def test_chat_success(self, mock_chat):
|
| 223 |
mock_chat.return_value = "Hello! 2+2=4."
|
tests/test_chat_jev_socratic.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
|
| 9 |
+
|
| 10 |
+
import main
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@pytest.fixture(autouse=True)
|
| 14 |
+
def isolate_chat_dependencies(monkeypatch: pytest.MonkeyPatch) -> None:
|
| 15 |
+
monkeypatch.setattr(main, "HAS_MEMORY_SERVICE", False)
|
| 16 |
+
monkeypatch.setattr(main, "HAS_FIREBASE_ADMIN", False)
|
| 17 |
+
monkeypatch.setattr(main, "retrieve_curriculum_context", lambda **_: [])
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@pytest.mark.asyncio
|
| 21 |
+
async def test_direct_answer_request_returns_socratic_response_without_llm(
|
| 22 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 23 |
+
) -> None:
|
| 24 |
+
async def route_intent(_message: str) -> dict[str, object]:
|
| 25 |
+
return {"choice": "direct_answer_request", "confidence": 0.93}
|
| 26 |
+
|
| 27 |
+
async def unexpected_llm_call(*_args: object, **_kwargs: object) -> str:
|
| 28 |
+
raise AssertionError("DeepSeek must not run for a high-confidence direct request")
|
| 29 |
+
|
| 30 |
+
monkeypatch.setattr(main, "route_student_intent", route_intent)
|
| 31 |
+
monkeypatch.setattr(main, "call_hf_chat_async", unexpected_llm_call)
|
| 32 |
+
|
| 33 |
+
response = await main.chat_tutor(main.ChatRequest(message="Just give me the answer"))
|
| 34 |
+
|
| 35 |
+
assert response.response == (
|
| 36 |
+
"I can guide you step-by-step, but I won't give the final answer directly! "
|
| 37 |
+
"What is the governing formula or first step you think we should use here?"
|
| 38 |
+
)
|
| 39 |
+
assert response.sources == []
|
| 40 |
+
assert response.suggestedFollowups == [
|
| 41 |
+
"What is the first step?",
|
| 42 |
+
"Can you explain the formula?",
|
| 43 |
+
"Give me a hint",
|
| 44 |
+
]
|
| 45 |
+
assert response.confidence == 0.93
|
| 46 |
+
assert response.activeModel == "jev-socratic-router"
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@pytest.mark.asyncio
|
| 50 |
+
async def test_conceptual_question_uses_normal_chat_generation(
|
| 51 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 52 |
+
) -> None:
|
| 53 |
+
async def route_intent(_message: str) -> dict[str, object]:
|
| 54 |
+
return {"choice": "conceptual_confusion", "confidence": 0.91}
|
| 55 |
+
|
| 56 |
+
async def normal_llm_call(*_args: object, **_kwargs: object) -> str:
|
| 57 |
+
return "A function maps each input to exactly one output."
|
| 58 |
+
|
| 59 |
+
monkeypatch.setattr(main, "route_student_intent", route_intent)
|
| 60 |
+
monkeypatch.setattr(main, "call_hf_chat_async", normal_llm_call)
|
| 61 |
+
|
| 62 |
+
response = await main.chat_tutor(main.ChatRequest(message="What is a function?"))
|
| 63 |
+
|
| 64 |
+
assert response.response == "A function maps each input to exactly one output."
|
| 65 |
+
assert response.activeModel is None
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@pytest.mark.asyncio
|
| 69 |
+
async def test_jev_failure_fails_open_to_normal_chat_generation(
|
| 70 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 71 |
+
) -> None:
|
| 72 |
+
async def failed_route(_message: str) -> dict[str, object]:
|
| 73 |
+
raise RuntimeError("Jev unavailable")
|
| 74 |
+
|
| 75 |
+
async def normal_llm_call(*_args: object, **_kwargs: object) -> str:
|
| 76 |
+
return "Start by identifying the known values."
|
| 77 |
+
|
| 78 |
+
monkeypatch.setattr(main, "route_student_intent", failed_route)
|
| 79 |
+
monkeypatch.setattr(main, "call_hf_chat_async", normal_llm_call)
|
| 80 |
+
|
| 81 |
+
response = await main.chat_tutor(main.ChatRequest(message="How do I start this problem?"))
|
| 82 |
+
|
| 83 |
+
assert response.response == "Start by identifying the known values."
|
tests/test_jev_client.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
from services import jev_client
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
@pytest.mark.asyncio
|
| 7 |
+
async def test_missing_key_uses_deterministic_fallbacks(monkeypatch: pytest.MonkeyPatch) -> None:
|
| 8 |
+
monkeypatch.delenv("TYPESAFE_API_KEY", raising=False)
|
| 9 |
+
|
| 10 |
+
assert await jev_client.route_student_intent("I am stuck") == {
|
| 11 |
+
"action": "fallback_disabled",
|
| 12 |
+
"choice": "conceptual_confusion",
|
| 13 |
+
}
|
| 14 |
+
assert await jev_client.verify_lesson_factuality("x", "y") == {
|
| 15 |
+
"action": "fallback_disabled",
|
| 16 |
+
"verified": True,
|
| 17 |
+
}
|
| 18 |
+
assert await jev_client.score_student_mastery([], "algebra") == {
|
| 19 |
+
"action": "fallback_disabled",
|
| 20 |
+
"pCorrect": 1.0,
|
| 21 |
+
"level": 0,
|
| 22 |
+
}
|
| 23 |
+
assert await jev_client.verify_solution_safety("x", "y") == {
|
| 24 |
+
"action": "fallback_disabled",
|
| 25 |
+
"pLeak": 0.0,
|
| 26 |
+
"safe": True,
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@pytest.mark.asyncio
|
| 31 |
+
async def test_empty_key_is_treated_as_missing(monkeypatch: pytest.MonkeyPatch) -> None:
|
| 32 |
+
monkeypatch.setenv("TYPESAFE_API_KEY", " ")
|
| 33 |
+
|
| 34 |
+
response = await jev_client.route_student_intent("hello")
|
| 35 |
+
|
| 36 |
+
assert response["action"] == "fallback_disabled"
|
| 37 |
+
assert response["choice"] == "conceptual_confusion"
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@pytest.mark.asyncio
|
| 41 |
+
async def test_sdk_failure_returns_fallback(monkeypatch: pytest.MonkeyPatch) -> None:
|
| 42 |
+
monkeypatch.setenv("TYPESAFE_API_KEY", "test-key")
|
| 43 |
+
|
| 44 |
+
async def fail_system_one(state: dict[str, object], questions: dict[str, object]) -> object:
|
| 45 |
+
raise TimeoutError("network timeout")
|
| 46 |
+
|
| 47 |
+
monkeypatch.setattr(jev_client, "_system_one", fail_system_one)
|
| 48 |
+
|
| 49 |
+
response = await jev_client.verify_solution_safety("reference", "student")
|
| 50 |
+
|
| 51 |
+
assert response == {"action": "fallback_disabled", "pLeak": 0.0, "safe": True}
|
tests/test_jev_hybrid_backend.py
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
from types import SimpleNamespace
|
| 7 |
+
from unittest.mock import patch
|
| 8 |
+
|
| 9 |
+
import pytest
|
| 10 |
+
from fastapi import FastAPI
|
| 11 |
+
from fastapi.testclient import TestClient
|
| 12 |
+
|
| 13 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
|
| 14 |
+
|
| 15 |
+
import main
|
| 16 |
+
from routes import deepseek_rag_routes, jev_routes
|
| 17 |
+
from services import jev_client
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@pytest.mark.asyncio
|
| 21 |
+
async def test_jev_client_missing_key(monkeypatch: pytest.MonkeyPatch) -> None:
|
| 22 |
+
monkeypatch.delenv("TYPESAFE_API_KEY", raising=False)
|
| 23 |
+
|
| 24 |
+
assert await jev_client.route_student_intent("I am stuck") == {
|
| 25 |
+
"action": "fallback_disabled",
|
| 26 |
+
"choice": "conceptual_confusion",
|
| 27 |
+
}
|
| 28 |
+
assert await jev_client.verify_lesson_factuality("reference", "lesson") == {
|
| 29 |
+
"action": "fallback_disabled",
|
| 30 |
+
"verified": True,
|
| 31 |
+
}
|
| 32 |
+
assert await jev_client.score_student_mastery([], "algebra") == {
|
| 33 |
+
"action": "fallback_disabled",
|
| 34 |
+
"pCorrect": 1.0,
|
| 35 |
+
"level": 0,
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@pytest.mark.asyncio
|
| 40 |
+
async def test_jev_client_primitives(monkeypatch: pytest.MonkeyPatch) -> None:
|
| 41 |
+
monkeypatch.setenv("TYPESAFE_API_KEY", "test-key")
|
| 42 |
+
|
| 43 |
+
response_by_question = {
|
| 44 |
+
"intent": SimpleNamespace(
|
| 45 |
+
choice="direct_answer_request",
|
| 46 |
+
confidence=0.93,
|
| 47 |
+
probabilities={"direct_answer_request": 0.93},
|
| 48 |
+
),
|
| 49 |
+
"factual_alignment": SimpleNamespace(noul=0.2),
|
| 50 |
+
"bloom_mastery_score": SimpleNamespace(score=2, confidence=0.8),
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
async def fake_system_one(state: dict[str, object], questions: dict[str, object]) -> object:
|
| 54 |
+
assert state
|
| 55 |
+
assert len(questions) == 1
|
| 56 |
+
question_name = next(iter(questions))
|
| 57 |
+
return SimpleNamespace(answers={question_name: response_by_question[question_name]})
|
| 58 |
+
|
| 59 |
+
monkeypatch.setattr(jev_client, "_system_one", fake_system_one)
|
| 60 |
+
|
| 61 |
+
assert await jev_client.route_student_intent("Give me the answer") == {
|
| 62 |
+
"choice": "direct_answer_request",
|
| 63 |
+
"confidence": 0.93,
|
| 64 |
+
"probabilities": {"direct_answer_request": 0.93},
|
| 65 |
+
}
|
| 66 |
+
assert await jev_client.verify_lesson_factuality("reference", "lesson") == {
|
| 67 |
+
"verified": False,
|
| 68 |
+
"confidence": 0.6,
|
| 69 |
+
}
|
| 70 |
+
assert await jev_client.score_student_mastery([], "algebra") == {
|
| 71 |
+
"level": 2,
|
| 72 |
+
"pCorrect": 0.8,
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def test_jev_verify_endpoint(monkeypatch: pytest.MonkeyPatch) -> None:
|
| 77 |
+
app = FastAPI()
|
| 78 |
+
app.include_router(jev_routes.router)
|
| 79 |
+
|
| 80 |
+
async def verify(reference_text: str, generated_text: str) -> dict[str, object]:
|
| 81 |
+
assert (reference_text, generated_text) == ("Reference lesson", "Generated lesson")
|
| 82 |
+
return {"verified": True, "pCorrect": 0.95, "pLeak": 0.05, "action": "allow"}
|
| 83 |
+
|
| 84 |
+
monkeypatch.setattr(jev_routes, "verify_lesson_factuality", verify)
|
| 85 |
+
|
| 86 |
+
with TestClient(app) as client:
|
| 87 |
+
valid_response = client.post(
|
| 88 |
+
"/api/jev/verify",
|
| 89 |
+
json={"referenceText": "Reference lesson", "generatedText": "Generated lesson"},
|
| 90 |
+
)
|
| 91 |
+
oversized_response = client.post(
|
| 92 |
+
"/api/jev/verify",
|
| 93 |
+
json={"referenceText": "r" * 4001, "generatedText": "g" * 4000},
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
assert valid_response.status_code == 200
|
| 97 |
+
assert valid_response.json() == {
|
| 98 |
+
"verified": True,
|
| 99 |
+
"pCorrect": 0.95,
|
| 100 |
+
"pLeak": 0.05,
|
| 101 |
+
"action": "allow",
|
| 102 |
+
}
|
| 103 |
+
assert oversized_response.status_code == 400
|
| 104 |
+
assert oversized_response.json() == {
|
| 105 |
+
"detail": "Combined text exceeds 8000 characters limit",
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
CHUNKS = [
|
| 110 |
+
{
|
| 111 |
+
"content": "A rational function is a quotient of two polynomial functions.",
|
| 112 |
+
"source_file": "SHS_GM_Q1.pdf",
|
| 113 |
+
"score": 0.95,
|
| 114 |
+
"content_domain": "general",
|
| 115 |
+
}
|
| 116 |
+
]
|
| 117 |
+
LESSON_PAYLOAD = {
|
| 118 |
+
"topic": "Rational Functions",
|
| 119 |
+
"subject": "General Mathematics",
|
| 120 |
+
"quarter": 1,
|
| 121 |
+
"lessonTitle": "Introduction to Rational Functions",
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def _generated_lesson() -> str:
|
| 126 |
+
sections = [
|
| 127 |
+
{"type": "introduction", "content": "Generated introduction hallucination."},
|
| 128 |
+
{"type": "key_concepts", "content": "Generated concepts hallucination."},
|
| 129 |
+
{"type": "video", "content": "Generated video description."},
|
| 130 |
+
{"type": "worked_examples", "examples": [{"problem": "Generated example hallucination."}]},
|
| 131 |
+
{"type": "important_notes", "bulletPoints": ["Generated note hallucination."]},
|
| 132 |
+
{"type": "try_it_yourself", "practiceProblems": [{"question": "Generated practice hallucination."}]},
|
| 133 |
+
{"type": "summary", "content": "Generated summary hallucination."},
|
| 134 |
+
]
|
| 135 |
+
return json.dumps({"sections": sections})
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
@pytest.fixture
|
| 139 |
+
def rag_client() -> TestClient:
|
| 140 |
+
with patch.object(
|
| 141 |
+
main.firebase_auth,
|
| 142 |
+
"verify_id_token",
|
| 143 |
+
return_value={"uid": "teacher_T", "role": "teacher"},
|
| 144 |
+
), patch(
|
| 145 |
+
"routes.rag_routes.retrieve_lesson_pdf_context",
|
| 146 |
+
return_value=(CHUNKS, "exact_file"),
|
| 147 |
+
), patch(
|
| 148 |
+
"routes.rag_routes._generate_text",
|
| 149 |
+
return_value=_generated_lesson(),
|
| 150 |
+
), patch(
|
| 151 |
+
"routes.rag_routes._fetch_youtube_videos",
|
| 152 |
+
return_value=[],
|
| 153 |
+
), patch(
|
| 154 |
+
"routes.rag_routes._log_rag_usage",
|
| 155 |
+
return_value=None,
|
| 156 |
+
):
|
| 157 |
+
yield TestClient(main.app, headers={"Authorization": "Bearer mock_token_teacher_T"})
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def test_rag_lesson_with_jev_verification(
|
| 161 |
+
rag_client: TestClient, monkeypatch: pytest.MonkeyPatch
|
| 162 |
+
) -> None:
|
| 163 |
+
async def reject_factuality(reference_text: str, generated_text: str) -> dict[str, object]:
|
| 164 |
+
assert CHUNKS[0]["content"] in reference_text
|
| 165 |
+
assert "Generated introduction hallucination." in generated_text
|
| 166 |
+
return {"verified": False, "pCorrect": 0.20}
|
| 167 |
+
|
| 168 |
+
monkeypatch.setattr("routes.rag_routes.verify_lesson_factuality", reject_factuality)
|
| 169 |
+
|
| 170 |
+
response = rag_client.post("/api/rag/lesson", json=LESSON_PAYLOAD)
|
| 171 |
+
|
| 172 |
+
assert response.status_code == 200
|
| 173 |
+
body = response.json()
|
| 174 |
+
assert len(body["sections"]) == 7
|
| 175 |
+
assert "Generated" not in str(body["sections"])
|
| 176 |
+
assert CHUNKS[0]["content"] in str(body["sections"])
|
| 177 |
+
assert body["jevVerification"] == {"verified": False, "pCorrect": 0.20}
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
@pytest.mark.asyncio
|
| 181 |
+
async def test_weakness_detection_with_jev_score(monkeypatch: pytest.MonkeyPatch) -> None:
|
| 182 |
+
monkeypatch.setattr(deepseek_rag_routes, "is_enabled", lambda: False)
|
| 183 |
+
|
| 184 |
+
request = deepseek_rag_routes.WeaknessDetectionRequest(
|
| 185 |
+
student_id="student-1",
|
| 186 |
+
questions=[
|
| 187 |
+
deepseek_rag_routes.QuestionResult(
|
| 188 |
+
question_id="question-1",
|
| 189 |
+
topic_id="algebra",
|
| 190 |
+
quarter=1,
|
| 191 |
+
is_correct=False,
|
| 192 |
+
),
|
| 193 |
+
deepseek_rag_routes.QuestionResult(
|
| 194 |
+
question_id="question-2",
|
| 195 |
+
topic_id="algebra",
|
| 196 |
+
quarter=1,
|
| 197 |
+
is_correct=True,
|
| 198 |
+
),
|
| 199 |
+
],
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
async def score(student_answers: list[dict[str, object]], topic: str) -> dict[str, object]:
|
| 203 |
+
assert topic == "algebra"
|
| 204 |
+
assert student_answers[0]["topic_id"] == "algebra"
|
| 205 |
+
return {"level": 2}
|
| 206 |
+
|
| 207 |
+
monkeypatch.setattr(deepseek_rag_routes, "score_student_mastery", score)
|
| 208 |
+
|
| 209 |
+
response = await deepseek_rag_routes.detect_weaknesses(request)
|
| 210 |
+
|
| 211 |
+
assert response.flagged_topics == ["algebra"]
|
| 212 |
+
assert response.confidence == {"algebra": 0.5}
|
| 213 |
+
assert response.source == "rule_based"
|
| 214 |
+
assert "algebra [Bloom Mastery: 2]" in response.reasoning_summary
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
@pytest.mark.asyncio
|
| 218 |
+
async def test_chat_direct_answer_socratic_short_circuit(
|
| 219 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 220 |
+
) -> None:
|
| 221 |
+
monkeypatch.setattr(main, "HAS_MEMORY_SERVICE", False)
|
| 222 |
+
monkeypatch.setattr(main, "HAS_FIREBASE_ADMIN", False)
|
| 223 |
+
monkeypatch.setattr(main, "retrieve_curriculum_context", lambda **_: [])
|
| 224 |
+
|
| 225 |
+
async def route_intent(_message: str) -> dict[str, object]:
|
| 226 |
+
return {"choice": "direct_answer_request", "confidence": 0.93}
|
| 227 |
+
|
| 228 |
+
async def unexpected_llm_call(*_args: object, **_kwargs: object) -> str:
|
| 229 |
+
raise AssertionError("DeepSeek must not run for a direct answer request")
|
| 230 |
+
|
| 231 |
+
monkeypatch.setattr(main, "route_student_intent", route_intent)
|
| 232 |
+
monkeypatch.setattr(main, "call_hf_chat_async", unexpected_llm_call)
|
| 233 |
+
|
| 234 |
+
response = await main.chat_tutor(main.ChatRequest(message="Just give me the answer"))
|
| 235 |
+
|
| 236 |
+
assert response.response == (
|
| 237 |
+
"I can guide you step-by-step, but I won't give the final answer directly! "
|
| 238 |
+
"What is the governing formula or first step you think we should use here?"
|
| 239 |
+
)
|
| 240 |
+
assert response.sources == []
|
| 241 |
+
assert response.suggestedFollowups == [
|
| 242 |
+
"What is the first step?",
|
| 243 |
+
"Can you explain the formula?",
|
| 244 |
+
"Give me a hint",
|
| 245 |
+
]
|
| 246 |
+
assert response.confidence == 0.93
|
| 247 |
+
assert response.activeModel == "jev-socratic-router"
|
tests/test_jev_routes.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
from fastapi import FastAPI
|
| 7 |
+
from fastapi.testclient import TestClient
|
| 8 |
+
|
| 9 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
|
| 10 |
+
|
| 11 |
+
from routes import jev_routes
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
app = FastAPI()
|
| 15 |
+
app.include_router(jev_routes.router)
|
| 16 |
+
client = TestClient(app)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_verify_returns_typed_schema(monkeypatch) -> None:
|
| 20 |
+
async def fake_verify(reference_text: str, generated_text: str) -> dict[str, object]:
|
| 21 |
+
assert reference_text == "Reference lesson"
|
| 22 |
+
assert generated_text == "Generated lesson"
|
| 23 |
+
return {
|
| 24 |
+
"verified": True,
|
| 25 |
+
"pCorrect": 0.95,
|
| 26 |
+
"pLeak": 0.05,
|
| 27 |
+
"action": "allow",
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
monkeypatch.setattr(jev_routes, "verify_lesson_factuality", fake_verify)
|
| 31 |
+
|
| 32 |
+
response = client.post(
|
| 33 |
+
"/api/jev/verify",
|
| 34 |
+
json={
|
| 35 |
+
"referenceText": "Reference lesson",
|
| 36 |
+
"generatedText": "Generated lesson",
|
| 37 |
+
},
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
assert response.status_code == 200
|
| 41 |
+
assert response.json() == {
|
| 42 |
+
"verified": True,
|
| 43 |
+
"pCorrect": 0.95,
|
| 44 |
+
"pLeak": 0.05,
|
| 45 |
+
"action": "allow",
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def test_verify_rejects_oversized_request() -> None:
|
| 50 |
+
response = client.post(
|
| 51 |
+
"/api/jev/verify",
|
| 52 |
+
json={
|
| 53 |
+
"referenceText": "r" * 4001,
|
| 54 |
+
"generatedText": "g" * 4000,
|
| 55 |
+
},
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
assert response.status_code == 400
|
| 59 |
+
assert response.json() == {
|
| 60 |
+
"detail": "Combined text exceeds 8000 characters limit",
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_verify_hides_service_failure_details(monkeypatch) -> None:
|
| 65 |
+
async def failed_verify(reference_text: str, generated_text: str) -> dict[str, object]:
|
| 66 |
+
raise RuntimeError("internal service secret")
|
| 67 |
+
|
| 68 |
+
monkeypatch.setattr(jev_routes, "verify_lesson_factuality", failed_verify)
|
| 69 |
+
|
| 70 |
+
response = client.post(
|
| 71 |
+
"/api/jev/verify",
|
| 72 |
+
json={
|
| 73 |
+
"referenceText": "Reference lesson",
|
| 74 |
+
"generatedText": "Generated lesson",
|
| 75 |
+
},
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
assert response.status_code == 502
|
| 79 |
+
assert response.json() == {"detail": "JEV verification service unavailable"}
|
| 80 |
+
assert "internal service secret" not in response.text
|
tests/test_rag_lesson_jev.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
from unittest.mock import patch
|
| 5 |
+
|
| 6 |
+
import pytest
|
| 7 |
+
from fastapi.testclient import TestClient
|
| 8 |
+
|
| 9 |
+
os.environ["DEEPSEEK_API_KEY"] = "mock-key-for-testing"
|
| 10 |
+
|
| 11 |
+
import main as main_module
|
| 12 |
+
from main import app
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
client = TestClient(app, headers={"Authorization": "Bearer mock_token_teacher_T"})
|
| 16 |
+
CHUNKS = [
|
| 17 |
+
{
|
| 18 |
+
"content": "A rational function is a quotient of two polynomial functions.",
|
| 19 |
+
"source_file": "SHS_GM_Q1.pdf",
|
| 20 |
+
"score": 0.95,
|
| 21 |
+
"content_domain": "general",
|
| 22 |
+
}
|
| 23 |
+
]
|
| 24 |
+
PAYLOAD = {
|
| 25 |
+
"topic": "Rational Functions",
|
| 26 |
+
"subject": "General Mathematics",
|
| 27 |
+
"quarter": 1,
|
| 28 |
+
"lessonTitle": "Introduction to Rational Functions",
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _generated_lesson() -> str:
|
| 33 |
+
sections = [
|
| 34 |
+
{"type": "introduction", "content": "Generated introduction hallucination."},
|
| 35 |
+
{"type": "key_concepts", "content": "Generated concepts hallucination."},
|
| 36 |
+
{"type": "video", "content": "Generated video description."},
|
| 37 |
+
{"type": "worked_examples", "examples": [{"problem": "Generated example hallucination."}]},
|
| 38 |
+
{"type": "important_notes", "bulletPoints": ["Generated note hallucination."]},
|
| 39 |
+
{"type": "try_it_yourself", "practiceProblems": [{"question": "Generated practice hallucination."}]},
|
| 40 |
+
{"type": "summary", "content": "Generated summary hallucination."},
|
| 41 |
+
]
|
| 42 |
+
import json
|
| 43 |
+
|
| 44 |
+
return json.dumps({"sections": sections})
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@pytest.fixture(autouse=True)
|
| 48 |
+
def _setup_rag_mocks():
|
| 49 |
+
with patch.object(
|
| 50 |
+
main_module.firebase_auth,
|
| 51 |
+
"verify_id_token",
|
| 52 |
+
return_value={"uid": "teacher_T", "role": "teacher"},
|
| 53 |
+
), patch(
|
| 54 |
+
"routes.rag_routes.retrieve_lesson_pdf_context",
|
| 55 |
+
return_value=(CHUNKS, "exact_file"),
|
| 56 |
+
), patch(
|
| 57 |
+
"routes.rag_routes._generate_text",
|
| 58 |
+
return_value=_generated_lesson(),
|
| 59 |
+
), patch(
|
| 60 |
+
"routes.rag_routes._fetch_youtube_videos",
|
| 61 |
+
return_value=[],
|
| 62 |
+
), patch(
|
| 63 |
+
"routes.rag_routes._log_rag_usage",
|
| 64 |
+
return_value=None,
|
| 65 |
+
):
|
| 66 |
+
yield
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def test_factuality_pass_retains_generated_lesson(monkeypatch) -> None:
|
| 70 |
+
async def verify(reference_text: str, generated_text: str) -> dict[str, object]:
|
| 71 |
+
assert CHUNKS[0]["content"] in reference_text
|
| 72 |
+
assert "Generated introduction hallucination." in generated_text
|
| 73 |
+
return {"verified": True, "pCorrect": 0.95}
|
| 74 |
+
|
| 75 |
+
monkeypatch.setattr("routes.rag_routes.verify_lesson_factuality", verify)
|
| 76 |
+
|
| 77 |
+
response = client.post("/api/rag/lesson", json=PAYLOAD)
|
| 78 |
+
|
| 79 |
+
assert response.status_code == 200
|
| 80 |
+
assert response.json()["sections"][0]["content"] == "Generated introduction hallucination."
|
| 81 |
+
assert response.json()["jevVerification"] == {"verified": True, "pCorrect": 0.95}
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def test_factuality_fail_replaces_all_sections_with_grounded_defaults(monkeypatch) -> None:
|
| 85 |
+
async def verify(reference_text: str, generated_text: str) -> dict[str, object]:
|
| 86 |
+
return {"verified": False, "pCorrect": 0.20}
|
| 87 |
+
|
| 88 |
+
monkeypatch.setattr("routes.rag_routes.verify_lesson_factuality", verify)
|
| 89 |
+
|
| 90 |
+
response = client.post("/api/rag/lesson", json=PAYLOAD)
|
| 91 |
+
|
| 92 |
+
assert response.status_code == 200
|
| 93 |
+
body = response.json()
|
| 94 |
+
sections_text = str(body["sections"])
|
| 95 |
+
assert "Generated" not in sections_text
|
| 96 |
+
assert CHUNKS[0]["content"] in sections_text
|
| 97 |
+
assert len(body["sections"]) == 7
|
| 98 |
+
assert body["jevVerification"] == {"verified": False, "pCorrect": 0.20}
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def test_jev_exception_fails_open_cleanly(monkeypatch) -> None:
|
| 102 |
+
async def verify(reference_text: str, generated_text: str) -> dict[str, object]:
|
| 103 |
+
raise RuntimeError("temporary Jev outage")
|
| 104 |
+
|
| 105 |
+
monkeypatch.setattr("routes.rag_routes.verify_lesson_factuality", verify)
|
| 106 |
+
|
| 107 |
+
response = client.post("/api/rag/lesson", json=PAYLOAD)
|
| 108 |
+
|
| 109 |
+
assert response.status_code == 200
|
| 110 |
+
assert response.json()["sections"][0]["content"] == "Generated introduction hallucination."
|
| 111 |
+
assert response.json()["jevVerification"] is None
|
tests/test_weakness_jev.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
from routes import deepseek_rag_routes
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def _request(*questions: tuple[str, bool]) -> deepseek_rag_routes.WeaknessDetectionRequest:
|
| 7 |
+
return deepseek_rag_routes.WeaknessDetectionRequest(
|
| 8 |
+
student_id="student-1",
|
| 9 |
+
questions=[
|
| 10 |
+
deepseek_rag_routes.QuestionResult(
|
| 11 |
+
question_id=f"question-{index}",
|
| 12 |
+
topic_id=topic,
|
| 13 |
+
quarter=1,
|
| 14 |
+
is_correct=is_correct,
|
| 15 |
+
)
|
| 16 |
+
for index, (topic, is_correct) in enumerate(questions)
|
| 17 |
+
],
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@pytest.mark.asyncio
|
| 22 |
+
async def test_weak_topic_receives_bloom_mastery_annotation(monkeypatch: pytest.MonkeyPatch) -> None:
|
| 23 |
+
monkeypatch.setattr(deepseek_rag_routes, "is_enabled", lambda: False)
|
| 24 |
+
calls: list[tuple[list[dict], str]] = []
|
| 25 |
+
|
| 26 |
+
async def score(student_answers: list[dict], topic: str) -> dict:
|
| 27 |
+
calls.append((student_answers, topic))
|
| 28 |
+
return {"level": 2}
|
| 29 |
+
|
| 30 |
+
monkeypatch.setattr(deepseek_rag_routes, "score_student_mastery", score)
|
| 31 |
+
|
| 32 |
+
response = await deepseek_rag_routes.detect_weaknesses(
|
| 33 |
+
_request(("algebra", False), ("algebra", True))
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
assert response.flagged_topics == ["algebra"]
|
| 37 |
+
assert "[Bloom Mastery: 2]" in response.reasoning_summary
|
| 38 |
+
assert calls[0][1] == "algebra"
|
| 39 |
+
assert calls[0][0][0]["topic_id"] == "algebra"
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@pytest.mark.asyncio
|
| 43 |
+
async def test_strong_topic_does_not_trigger_jev_or_flagging(
|
| 44 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 45 |
+
) -> None:
|
| 46 |
+
monkeypatch.setattr(deepseek_rag_routes, "is_enabled", lambda: False)
|
| 47 |
+
|
| 48 |
+
async def fail_score(student_answers: list[dict], topic: str) -> dict:
|
| 49 |
+
raise AssertionError("Jev must not score strong topics")
|
| 50 |
+
|
| 51 |
+
monkeypatch.setattr(deepseek_rag_routes, "score_student_mastery", fail_score)
|
| 52 |
+
|
| 53 |
+
response = await deepseek_rag_routes.detect_weaknesses(
|
| 54 |
+
_request(("algebra", True), ("algebra", True), ("algebra", True))
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
assert response.flagged_topics == []
|
| 58 |
+
assert "Bloom Mastery" not in response.reasoning_summary
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@pytest.mark.asyncio
|
| 62 |
+
async def test_jev_failure_preserves_rule_based_response(
|
| 63 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 64 |
+
) -> None:
|
| 65 |
+
monkeypatch.setattr(deepseek_rag_routes, "is_enabled", lambda: False)
|
| 66 |
+
|
| 67 |
+
async def fail_score(student_answers: list[dict], topic: str) -> dict:
|
| 68 |
+
raise TimeoutError("Jev timeout")
|
| 69 |
+
|
| 70 |
+
monkeypatch.setattr(deepseek_rag_routes, "score_student_mastery", fail_score)
|
| 71 |
+
|
| 72 |
+
response = await deepseek_rag_routes.detect_weaknesses(
|
| 73 |
+
_request(("geometry", False))
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
assert response.flagged_topics == ["geometry"]
|
| 77 |
+
assert response.confidence == {"geometry": 1.0}
|
| 78 |
+
assert response.reasoning_summary == (
|
| 79 |
+
"Rule-based detection: topics below 60% accuracy threshold."
|
| 80 |
+
)
|
| 81 |
+
assert response.source == "rule_based"
|