Spaces:
Runtime error
Runtime error
Download src/tutor_session.py from TrueTensor/Vidya-V3-Tutor: direct link, hf CLI and curl.
- Browser
- Download file 13.6 kB
-
https://huggingface.co/spaces/TrueTensor/Vidya-V3-Tutor/resolve/main/src/tutor_session.py
- Command line
-
hf download hf://spaces/TrueTensor/Vidya-V3-Tutor/src/tutor_session.py
-
curl -L -o tutor_session.py https://huggingface.co/spaces/TrueTensor/Vidya-V3-Tutor/resolve/main/src/tutor_session.py
13.6 kB
| """ | |
| tutor_session.py β Manages one full tutor session end-to-end. | |
| What's new vs v1: | |
| - SignalScorecard: persistent 0-100 scores per signal, updated every turn | |
| - mastery_level updates dynamically from signal scores each turn | |
| - ca_phase re-evaluated from mastery after each mastery update | |
| - ICP profile (low_wage / high_wage) injected into every Gemini call | |
| - Full scorecard history saved in logs/conversations.json | |
| """ | |
| import json | |
| import re | |
| from src.config import SYSTEM_PROMPT_PATH, CONVERSATION_LOG_PATH | |
| import src.config as config_module | |
| from src.schemas import SessionConfig, TutorOutput, fallback_output | |
| from src.gemini_client import call_gemini | |
| from src.phase_manager import ( | |
| validate_phase, | |
| fallback_phase_update, | |
| update_mastery, | |
| phase_from_mastery, | |
| ) | |
| from src.signal_extractor import SignalScorecard | |
| from src.icp_profiles import get_icp | |
| from src.utils import print_warning | |
| # ββ Score label helper (used in learner_state sent to Gemini) ββββββββββββββββ | |
| def _score_label(score: float) -> str: | |
| """Converts a 0β100 signal score to a plain-English label for Gemini.""" | |
| if score >= 80: return f"very high ({score:.0f})" | |
| if score >= 65: return f"high ({score:.0f})" | |
| if score >= 35: return f"neutral ({score:.0f})" | |
| if score >= 20: return f"low ({score:.0f})" | |
| return f"very low ({score:.0f})" | |
| # ββ Load system prompt once βββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def _load_system_prompt() -> str: | |
| with open(SYSTEM_PROMPT_PATH, "r", encoding="utf-8") as f: | |
| return f.read() | |
| _SYSTEM_PROMPT = _load_system_prompt() | |
| # ββ JSON extraction helper ββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def _extract_json(raw: str) -> dict: | |
| cleaned = re.sub(r"```(?:json)?\s*", "", raw).strip().rstrip("`").strip() | |
| return json.loads(cleaned) | |
| # ββ Main session class ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class TutorSession: | |
| def __init__(self, config: SessionConfig): | |
| self.config = config | |
| self.mastery_level = config.mastery_level # live, updates each turn | |
| self.current_phase = config.ca_phase # assigned from mastery at start | |
| self.conversation_history: list[dict] = [] | |
| self.turn_count = 0 | |
| self.scorecard = SignalScorecard( # persistent signal scores | |
| api_key=config_module.GEMINI_API_KEY, | |
| model=config_module.GEMINI_MODEL, | |
| ) | |
| self.icp_profile = get_icp(config.icp_type) # tone + example rules | |
| # ββ Session config dict sent to Gemini every turn ββββββββββββββββββββββββ | |
| def _session_config_dict(self, signal_scores: dict) -> dict: | |
| """ | |
| Packages full session state + signal scores + ICP tone rules. | |
| Everything Gemini needs to give a perfectly adapted response. | |
| """ | |
| ast = self.icp_profile.get("anti_stereotype_threat") | |
| return { | |
| "skill_topic": self.config.skill_topic, | |
| "mastery_level": round(self.mastery_level, 3), | |
| "ca_phase": self.current_phase, | |
| "language_preference": self.config.language_preference, | |
| # ββ Full ICP context (who this learner is + how to teach them) ββββ | |
| "icp": { | |
| "type": self.config.icp_type, | |
| "tone": self.icp_profile["tone"], | |
| "tone_rules": self.icp_profile["tone_rules"], | |
| "scaffold_level": self.icp_profile["scaffold_level"], | |
| "worked_examples": self.icp_profile["worked_examples"], | |
| "language_default": self.icp_profile["language_default"], | |
| "explanation_depth": self.icp_profile["explanation_depth"], | |
| "challenge_level": self.icp_profile["challenge_level"], | |
| "goal_framing": self.icp_profile["goal_framing"], | |
| "pacing": self.icp_profile["pacing"], | |
| "encouragement": self.icp_profile["encouragement"], | |
| "anti_stereotype_threat": ast if ast else "not applicable", | |
| "learner_goals": self.icp_profile["goals"], | |
| }, | |
| # ββ Signal scores (0β100 each, rolling across turns) ββββββββββββββ | |
| "signal_scores": { | |
| k: round(v, 1) for k, v in signal_scores.items() | |
| }, | |
| # ββ Plain-English labels for Gemini βββββββββββββββββββββββββββββββ | |
| "learner_state": { | |
| k: _score_label(v) | |
| for k, v in signal_scores.items() | |
| }, | |
| } | |
| # ββ JSON parse + validate with one retry βββββββββββββββββββββββββββββββββ | |
| def _parse_and_validate(self, raw_text: str) -> dict: | |
| # Attempt 1 | |
| try: | |
| data = _extract_json(raw_text) | |
| return TutorOutput(**data).model_dump() | |
| except Exception: | |
| pass | |
| # Attempt 2: repair | |
| print_warning("Gemini returned unexpected format. Retrying onceβ¦") | |
| repair_prompt = ( | |
| f"Fix the following into valid JSON matching this schema exactly:\n" | |
| f'{{"tutor_response":"...","updated_ca_phase":"...","on_topic_flag":true/false,' | |
| f'"suggested_next_action":"..."}}\n\nReturn ONLY raw JSON:\n\n{raw_text}' | |
| ) | |
| try: | |
| raw2 = call_gemini( | |
| system_prompt=_SYSTEM_PROMPT, | |
| session_config={}, | |
| conversation_history=[], | |
| user_message=repair_prompt, | |
| ) | |
| return TutorOutput(**_extract_json(raw2)).model_dump() | |
| except Exception: | |
| pass | |
| print_warning("Repair failed. Using safe fallback response.") | |
| return fallback_output(self.current_phase) | |
| # ββ Main turn processor βββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def process_turn(self, user_message: str, debug: bool = False) -> dict: | |
| """ | |
| Processes one user turn. | |
| Order: | |
| 1. Update signal scorecard | |
| 2. Update mastery_level from scores | |
| 3. Re-evaluate phase from mastery | |
| 4. Call Gemini with full context | |
| 5. Validate output + apply phase | |
| 6. Update history | |
| 7. Return output + debug info | |
| """ | |
| self.turn_count += 1 | |
| # ββ 1. Update signal scorecard ββββββββββββββββββββββββββββββββββββββββ | |
| signal_scores = self.scorecard.update( | |
| user_message, self.config.skill_topic, | |
| self.conversation_history, # gives LLM judge conversation context | |
| ) | |
| # ββ 2. Update mastery from signal scores ββββββββββββββββββββββββββββββ | |
| old_mastery = self.mastery_level | |
| self.mastery_level = update_mastery(self.mastery_level, signal_scores) | |
| # ββ 3. Re-evaluate phase from updated mastery βββββββββββββββββββββββββ | |
| mastery_suggested_phase = phase_from_mastery(self.mastery_level, self.config.icp_type) | |
| # ββ 4. Call Gemini ββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| raw_response = call_gemini( | |
| system_prompt=_SYSTEM_PROMPT, | |
| session_config=self._session_config_dict(signal_scores), | |
| conversation_history=self.conversation_history, | |
| user_message=user_message, | |
| ) | |
| # ββ 5. Parse + validate Gemini output ββββββββββββββββββββββββββββββββ | |
| output = self._parse_and_validate(raw_response) | |
| # Validate Gemini's phase choice | |
| proposed_phase = output.get("updated_ca_phase", self.current_phase) | |
| safe_phase = validate_phase(proposed_phase, self.current_phase) | |
| if safe_phase != proposed_phase: | |
| # Gemini gave bad phase β signal-score fallback | |
| safe_phase = fallback_phase_update(self.current_phase, signal_scores) | |
| print_warning(f"Phase corrected by score fallback β {safe_phase}") | |
| # Mastery-based override β smart boundary enforcement. | |
| # | |
| # Rules: | |
| # 1. Gemini CANNOT advance phase beyond what mastery supports. | |
| # If Gemini says COACH but mastery says MODEL β block it, stay MODEL. | |
| # This is the primary guard against premature phase jumps. | |
| # 2. If mastery crossed a boundary UPWARD this turn β advance phase. | |
| # 3. If mastery dropped significantly (>= 0.06) β regress phase. | |
| # 4. Otherwise β trust Gemini's turn-by-turn judgment. | |
| phase_order = ["MODEL", "COACH", "SCAFFOLD", "FADE"] | |
| mastery_idx = phase_order.index(mastery_suggested_phase) | |
| current_idx = phase_order.index(safe_phase) | |
| mastery_delta = self.mastery_level - old_mastery # signed delta | |
| if mastery_idx < current_idx: | |
| # Gemini wants to ADVANCE beyond what mastery supports β BLOCK | |
| # e.g. mastery=0.12 β MODEL bucket, but Gemini returned COACH | |
| print_warning( | |
| f"Gemini suggested {safe_phase} but mastery={self.mastery_level:.3f} " | |
| f"only supports {mastery_suggested_phase} β holding at {mastery_suggested_phase}" | |
| ) | |
| safe_phase = mastery_suggested_phase | |
| elif mastery_idx > current_idx and mastery_delta > 0: | |
| # Mastery boundary crossed upward this turn β advance | |
| print_warning( | |
| f"Mastery={self.mastery_level:.3f} " | |
| f"({old_mastery:.3f}β{self.mastery_level:.3f}) " | |
| f"β advancing: {safe_phase} β {mastery_suggested_phase}" | |
| ) | |
| safe_phase = mastery_suggested_phase | |
| elif mastery_idx < current_idx and mastery_delta <= -0.06: | |
| # Mastery dropped significantly β regress | |
| print_warning( | |
| f"Mastery={self.mastery_level:.3f} " | |
| f"({old_mastery:.3f}β{self.mastery_level:.3f}) " | |
| f"β regressing: {safe_phase} β {mastery_suggested_phase}" | |
| ) | |
| safe_phase = mastery_suggested_phase | |
| # else: Gemini's phase decision stands (within mastery-permitted range) | |
| self.current_phase = safe_phase | |
| output["updated_ca_phase"] = safe_phase | |
| # ββ 6. Update conversation history βββββββββββββββββββββββββββββββββββ | |
| self.conversation_history.append({"role": "user", "content": user_message}) | |
| self.conversation_history.append({"role": "assistant", "content": output["tutor_response"]}) | |
| # ββ 7. Attach debug info ββββββββββββββββββββββββββββββββββββββββββββββ | |
| output["_debug"] = { | |
| "signal_scores": signal_scores, | |
| "mastery_before": round(old_mastery, 3), | |
| "mastery_after": round(self.mastery_level, 3), | |
| "mastery_phase": mastery_suggested_phase, | |
| "final_phase": safe_phase, | |
| "turn": self.turn_count, | |
| } | |
| return output | |
| # ββ Save session log ββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def save_log(self): | |
| """Appends full session to logs/conversations.json.""" | |
| CONVERSATION_LOG_PATH.parent.mkdir(parents=True, exist_ok=True) | |
| existing: list = [] | |
| if CONVERSATION_LOG_PATH.exists(): | |
| try: | |
| with open(CONVERSATION_LOG_PATH, "r", encoding="utf-8") as f: | |
| existing = json.load(f) | |
| if not isinstance(existing, list): | |
| existing = [] | |
| except json.JSONDecodeError: | |
| existing = [] | |
| session_record = { | |
| "config": self.config.model_dump(), | |
| "final_phase": self.current_phase, | |
| "final_mastery": round(self.mastery_level, 3), | |
| "turns": self.turn_count, | |
| "conversation": self.conversation_history, | |
| "signal_scorecard": self.scorecard.to_dict(), | |
| "signal_history": self.scorecard.history, | |
| } | |
| existing.append(session_record) | |
| with open(CONVERSATION_LOG_PATH, "w", encoding="utf-8") as f: | |
| json.dump(existing, f, ensure_ascii=False, indent=2) | |