Spaces:
Runtime error

File size: 13,596 Bytes
8ab5cfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
"""
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)