j-js commited on
Commit
3139428
·
verified ·
1 Parent(s): 92fc965

Update formatting.py

Browse files
Files changed (1) hide show
  1. formatting.py +1037 -439
formatting.py CHANGED
@@ -1,525 +1,1123 @@
1
- # formatting.py
2
  from __future__ import annotations
3
 
4
  import re
5
- from typing import List
6
-
7
- from models import ExplainerResult
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
 
 
9
 
10
- def style_prefix(tone: float) -> str:
11
- if tone < 0.2:
12
- return ""
13
- if tone < 0.45:
14
- return "Let’s solve it efficiently."
15
- if tone < 0.75:
16
- return "Let’s work through it."
17
- return "You’ve got this — let’s solve it cleanly."
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
- def _clean_lines(core: str) -> list[str]:
21
- lines = []
22
- for line in (core or "").splitlines():
23
- cleaned = line.strip()
24
- if cleaned:
25
- lines.append(cleaned)
26
- return lines
27
 
 
28
 
29
- def _normalize_key(text: str) -> str:
30
- text = (text or "").strip().lower()
31
- text = text.replace("’", "'")
32
- text = re.sub(r"\s+", " ", text)
33
- return text
34
 
 
 
 
 
 
 
 
 
 
35
 
36
- def _is_wrapper_line(line: str) -> bool:
37
- key = _normalize_key(line).rstrip(":")
38
- wrapper_lines = {
39
- "let's work through it.",
40
- "lets work through it.",
41
- "let's solve it efficiently.",
42
- "lets solve it efficiently.",
43
- "you've got this — let's solve it cleanly.",
44
- "youve got this — lets solve it cleanly.",
45
- "you’ve got this — let’s solve it cleanly.",
46
- "walkthrough",
47
- "hint",
48
- "steps",
49
- "method",
50
- "explanation",
51
- "key idea",
52
- "question breakdown",
53
- "here’s what the question is really asking",
54
- "here's what the question is really asking",
55
- "let’s break down what the question is asking",
56
- "lets break down what the question is asking",
57
- "you’ve got this — here’s what the question is really asking",
58
- "you've got this — here's what the question is really asking",
59
- "what to identify first",
60
- "set-up path",
61
- "setup path",
62
- "first move",
63
- "next hint",
64
- "watch out for",
65
- "variables to define",
66
- "equations to form",
67
- "key teaching points",
68
- }
69
- return key in wrapper_lines
70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
 
72
- def _strip_leading_wrapper_lines(lines: list[str]) -> list[str]:
73
- cleaned = list(lines)
74
- while cleaned and _is_wrapper_line(cleaned[0]):
75
- cleaned.pop(0)
76
  return cleaned
77
 
78
 
79
- def _dedupe_lines(lines: list[str]) -> list[str]:
80
- seen = set()
81
- output = []
82
- for line in lines:
83
- key = _normalize_key(line)
84
- if key and key not in seen:
85
- seen.add(key)
86
- output.append(line.strip())
87
- return output
88
-
89
-
90
- def _limit_lines_for_verbosity(lines: list[str], verbosity: float, help_mode: str) -> list[str]:
91
- if not lines:
92
- return lines
93
-
94
- if help_mode == "hint":
95
- return lines[:1]
96
-
97
- if verbosity < 0.2:
98
- return lines[:1]
99
-
100
- if verbosity < 0.45:
101
- return lines[:2]
102
-
103
- if verbosity < 0.75:
104
- return lines[:3]
105
-
106
- return lines
107
-
108
-
109
- def _extract_topic_from_lines(lines: list[str]) -> str:
110
- joined = " ".join(lines).lower()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
 
112
- if any(word in joined for word in ["equation", "variable", "isolate", "algebra"]):
113
- return "algebra"
114
- if any(word in joined for word in ["percent", "percentage"]):
115
- return "percent"
116
- if any(word in joined for word in ["ratio", "proportion"]):
117
- return "ratio"
118
- if any(word in joined for word in ["probability", "outcome"]):
119
- return "probability"
120
- if any(word in joined for word in ["mean", "median", "average"]):
121
- return "statistics"
122
- if any(word in joined for word in ["triangle", "circle", "angle", "area", "perimeter"]):
123
- return "geometry"
124
- if any(word in joined for word in ["integer", "factor", "multiple", "prime", "remainder"]):
125
- return "number_theory"
126
 
127
- return "general"
128
 
 
 
129
 
130
- def _why_line(topic: str, lines: list[str]) -> str:
131
- joined = " ".join(lines).lower()
132
 
133
- if topic == "algebra":
134
- if "equation" in joined or "isolate" in joined or "variable" in joined:
135
- return "Why: this works because inverse operations undo what is attached to the variable while keeping the equation balanced."
136
- return "Why: the goal is to isolate the variable without changing the balance of the relationship."
137
-
138
- if topic == "percent":
139
- return "Why: percent relationships depend on identifying the correct base value before calculating the change or part."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
 
141
- if topic == "ratio":
142
- return "Why: ratios compare parts consistently, so the relationship must stay proportional."
143
 
144
- if topic == "probability":
145
- return "Why: probability compares favorable outcomes to the total number of possible outcomes."
146
 
147
- if topic == "statistics":
148
- return "Why: statistical measures describe the distribution, so the method depends on what feature the question asks for."
149
 
150
- if topic == "geometry":
151
- return "Why: geometry problems depend on the properties of the figure and the relationships between its parts."
 
152
 
153
- if topic == "number_theory":
154
- return "Why: number properties such as divisibility, factors, and remainders follow fixed rules that guide the method."
 
 
 
155
 
156
- return "Why: focus on the structure of the problem before doing any calculations."
157
 
 
 
 
 
 
 
 
 
 
 
 
158
 
159
- def _tone_adjust_line(line: str, tone: float) -> str:
160
- line = (line or "").strip()
161
- if not line:
162
- return line
163
 
164
- if tone < 0.25:
165
- line = re.sub(r"^let’s\s+", "", line, flags=re.IGNORECASE)
166
- line = re.sub(r"^let's\s+", "", line, flags=re.IGNORECASE)
167
- line = re.sub(r"^here is the idea in context:\s*", "", line, flags=re.IGNORECASE)
168
- return line.strip()
169
 
170
- return line
 
171
 
 
 
172
 
173
- def format_reply(core: str, tone: float, verbosity: float, transparency: float, help_mode: str) -> str:
174
- prefix = style_prefix(tone)
175
- core = (core or "").strip()
176
 
177
- if not core:
178
- return prefix or "Start with the structure of the problem."
179
 
180
- lines = _clean_lines(core)
181
- lines = _strip_leading_wrapper_lines(lines)
182
- lines = [_tone_adjust_line(line, tone) for line in lines]
183
- lines = [line for line in lines if line]
184
- lines = _dedupe_lines(lines)
185
- lines = _limit_lines_for_verbosity(lines, verbosity, help_mode)
186
 
187
- if not lines:
188
- return prefix or "Start with the structure of the problem."
 
 
 
 
 
 
 
189
 
190
- topic = _extract_topic_from_lines(lines)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
 
192
- output: list[str] = []
 
 
 
193
 
194
- if prefix:
195
- output.append(prefix)
196
- output.append("")
197
 
198
- if help_mode == "hint":
199
- output.append("Hint:")
200
- output.extend(lines[:1])
201
 
202
- if transparency >= 0.8:
203
- output.append("")
204
- output.append(_why_line(topic, lines[:1]))
205
 
206
- return "\n".join(output).strip()
 
 
 
 
 
 
 
 
 
207
 
208
- if help_mode == "walkthrough":
209
- output.append("Walkthrough:")
210
- output.extend(lines)
211
 
212
- if transparency >= 0.8:
213
- output.append("")
214
- output.append(_why_line(topic, lines))
215
 
216
- return "\n".join(output).strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217
 
218
- if help_mode in {"step_by_step", "method", "explain", "concept"}:
219
- label = {
220
- "step_by_step": "Steps:",
221
- "method": "Method:",
222
- "explain": "Explanation:",
223
- "concept": "Key idea:",
224
- }.get(help_mode, "Explanation:")
225
- output.append(label)
226
- output.extend(lines)
227
 
228
- if transparency >= 0.75:
229
- output.append("")
230
- output.append(_why_line(topic, lines))
 
 
231
 
232
- return "\n".join(output).strip()
 
 
 
233
 
234
- output.extend(lines)
235
 
236
- if transparency >= 0.85 and help_mode != "answer":
237
- output.append("")
238
- output.append(_why_line(topic, lines))
 
239
 
240
- return "\n".join(output).strip()
 
241
 
 
 
242
 
243
- # -------------------------------------------------
244
- # Explainer formatting
245
- # -------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
246
 
247
- def _explainer_header(tone: float) -> str:
248
- if tone < 0.2:
249
- return "Question breakdown:"
250
- if tone < 0.45:
251
- return "Here’s what the question is really asking:"
252
- if tone < 0.75:
253
- return "Let’s break down what the question is asking:"
254
- return "You’ve got this — here’s what the question is really asking:"
255
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
256
 
257
- def _clean_section_items(items: List[str]) -> List[str]:
258
- cleaned = []
259
- seen = set()
 
260
 
261
- for item in items or []:
262
- text = (item or "").strip()
263
  if not text:
264
  continue
265
- if _is_wrapper_line(text):
266
- continue
267
- key = _normalize_key(text)
268
- if key in seen:
269
- continue
270
- seen.add(key)
271
- cleaned.append(text)
272
 
273
- return cleaned
 
274
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
275
 
276
- def _append_section(lines: List[str], title: str, items: List[str], limit: int) -> None:
277
- cleaned = _clean_section_items(items)
278
- if not cleaned:
279
- return
280
 
281
- lines.append("")
282
- lines.append(title)
283
- for item in cleaned[:limit]:
284
- lines.append(f"- {item}")
285
 
 
 
286
 
287
- def _coerce_string(value) -> str:
288
- return (value or "").strip() if isinstance(value, str) else ""
289
 
290
 
291
- def _coerce_list(value) -> List[str]:
292
- if not value:
293
  return []
294
- if isinstance(value, list):
295
- return [str(v).strip() for v in value if str(v).strip()]
296
- if isinstance(value, tuple):
297
- return [str(v).strip() for v in value if str(v).strip()]
298
- if isinstance(value, str):
299
- text = value.strip()
300
  return [text] if text else []
301
  return []
302
 
303
 
304
- def _get_scaffold(result: ExplainerResult):
305
- return getattr(result, "scaffold", None)
 
 
 
306
 
307
 
308
- def _explainer_topic(result: ExplainerResult) -> str:
309
- topic = _coerce_string(getattr(result, "topic", ""))
310
- if topic:
311
- return topic
312
-
313
- joined = " ".join(
314
- _coerce_list(getattr(result, "teaching_points", []))
315
- + _coerce_list(getattr(result, "givens", []))
316
- + _coerce_list(getattr(result, "relationships", []))
317
- )
318
- return _extract_topic_from_lines([joined]) if joined else "general"
319
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320
 
321
- def _build_scaffold_sections(
322
- result: ExplainerResult,
323
- verbosity: float,
324
- transparency: float,
325
- ) -> List[str]:
326
- output: List[str] = []
327
- scaffold = _get_scaffold(result)
328
 
329
- if scaffold is None:
330
- return output
331
-
332
- ask = _coerce_string(getattr(scaffold, "ask", ""))
333
- setup_actions = _coerce_list(getattr(scaffold, "setup_actions", []))
334
- intermediate_steps = _coerce_list(getattr(scaffold, "intermediate_steps", []))
335
- first_move = _coerce_string(getattr(scaffold, "first_move", ""))
336
- next_hint = _coerce_string(getattr(scaffold, "next_hint", ""))
337
- variables_to_define = _coerce_list(getattr(scaffold, "variables_to_define", []))
338
- equations_to_form = _coerce_list(getattr(scaffold, "equations_to_form", []))
339
- common_traps = _coerce_list(getattr(scaffold, "common_traps", []))
340
-
341
- if ask:
342
- output.append("")
343
- output.append("What to identify first:")
344
- output.append(f"- {ask}")
345
-
346
- if setup_actions:
347
- output.append("")
348
- output.append("Set-up path:")
349
- limit = 2 if verbosity < 0.4 else 3 if verbosity < 0.75 else 5
350
- for item in setup_actions[:limit]:
351
- output.append(f"- {item}")
352
-
353
- if verbosity >= 0.55 and intermediate_steps:
354
- output.append("")
355
- output.append("How to build it:")
356
- limit = 2 if verbosity < 0.75 else 4
357
- for item in intermediate_steps[:limit]:
358
- output.append(f"- {item}")
359
-
360
- if first_move:
361
- output.append("")
362
- output.append("First move:")
363
- output.append(f"- {first_move}")
364
-
365
- if next_hint and (transparency >= 0.35 or verbosity >= 0.45):
366
- output.append("")
367
- output.append("Next hint:")
368
- output.append(f"- {next_hint}")
369
-
370
- if verbosity >= 0.65 and variables_to_define:
371
- output.append("")
372
- output.append("Variables to define:")
373
- for item in variables_to_define[:3]:
374
- output.append(f"- {item}")
375
-
376
- if transparency >= 0.55 and equations_to_form:
377
- output.append("")
378
- output.append("Equations to form:")
379
- for item in equations_to_form[:3]:
380
- output.append(f"- {item}")
381
-
382
- if transparency >= 0.6 or verbosity >= 0.75:
383
- if common_traps:
384
- output.append("")
385
- output.append("Watch out for:")
386
- for item in common_traps[:4]:
387
- output.append(f"- {item}")
388
-
389
- return output
390
-
391
-
392
- def format_explainer_response(
393
- result: ExplainerResult,
394
- tone: float,
395
- verbosity: float,
396
- transparency: float,
397
- ) -> str:
398
- if not result or not getattr(result, "understood", False):
399
- return "I can help explain what the question is asking, but I need the full wording of the question."
400
-
401
- output: List[str] = []
402
-
403
- header = _explainer_header(tone)
404
- if header:
405
- output.append(header)
406
- output.append("")
407
-
408
- # -------------------------------------------------
409
- # New publish-ready scaffold-aware path
410
- # -------------------------------------------------
411
- summary = _coerce_string(getattr(result, "summary", ""))
412
- teaching_points = _coerce_list(getattr(result, "teaching_points", []))
413
-
414
- if summary and not _is_wrapper_line(summary):
415
- output.append(summary)
416
-
417
- scaffold_sections = _build_scaffold_sections(result, verbosity, transparency)
418
- if scaffold_sections:
419
- output.extend(scaffold_sections)
420
-
421
- if teaching_points and verbosity >= 0.5:
422
- output.append("")
423
- output.append("Key teaching points:")
424
- limit = 2 if verbosity < 0.75 else 4
425
- for item in teaching_points[:limit]:
426
- output.append(f"- {item}")
427
-
428
- # -------------------------------------------------
429
- # Backward-compatible support for older explainer fields
430
- # -------------------------------------------------
431
- plain = _coerce_string(getattr(result, "plain_english", ""))
432
- if plain and not summary and not _is_wrapper_line(plain):
433
- output.append(plain)
434
-
435
- asks_for = _coerce_string(getattr(result, "asks_for", ""))
436
- if asks_for and transparency >= 0.3:
437
- output.append("")
438
- output.append(f"The question is asking for: {asks_for}")
439
-
440
- if verbosity >= 0.4:
441
- _append_section(
442
- output,
443
- "What the question gives you:",
444
- getattr(result, "givens", []) or [],
445
- 5 if verbosity >= 0.7 else 3,
446
  )
447
-
448
- if verbosity >= 0.65:
449
- _append_section(
450
- output,
451
- "Constraints or conditions:",
452
- getattr(result, "constraints", []) or [],
453
- 5,
 
 
 
 
 
 
 
 
 
 
 
 
 
454
  )
455
 
456
- if transparency >= 0.45:
457
- _append_section(
458
- output,
459
- "Key relationship:",
460
- getattr(result, "relationships", []) or [],
461
- 4,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
462
  )
463
 
464
- if transparency >= 0.5:
465
- _append_section(
466
- output,
467
- "Concepts you will probably need:",
468
- getattr(result, "needed_concepts", []) or [],
469
- 4,
 
 
470
  )
471
 
472
- if transparency >= 0.55 or verbosity >= 0.7:
473
- _append_section(
474
- output,
475
- "Watch out for:",
476
- getattr(result, "trap_notes", []) or [],
477
- 4,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
478
  )
479
 
480
- strategy_hint = _coerce_string(getattr(result, "strategy_hint", ""))
481
- if strategy_hint and verbosity >= 0.35 and not _is_wrapper_line(strategy_hint):
482
- output.append("")
483
- output.append(f"Best starting move: {strategy_hint}")
484
-
485
- if transparency >= 0.8:
486
- topic = _explainer_topic(result)
487
- why_seed_lines: List[str] = []
488
-
489
- if summary:
490
- why_seed_lines.append(summary)
491
-
492
- scaffold = _get_scaffold(result)
493
- if scaffold is not None:
494
- ask = _coerce_string(getattr(scaffold, "ask", ""))
495
- first_move = _coerce_string(getattr(scaffold, "first_move", ""))
496
- if ask:
497
- why_seed_lines.append(ask)
498
- if first_move:
499
- why_seed_lines.append(first_move)
500
-
501
- if not why_seed_lines:
502
- why_seed_lines.extend(teaching_points[:2])
503
-
504
- if why_seed_lines:
505
- output.append("")
506
- output.append(_why_line(topic, why_seed_lines))
507
-
508
- final_lines = []
509
- previous_key = None
510
- for line in output:
511
- if line is None:
512
- continue
513
- text = str(line).rstrip()
514
- key = _normalize_key(text)
515
- if key == previous_key and key:
516
- continue
517
- final_lines.append(text)
518
- previous_key = key
519
-
520
- text = "\n".join(final_lines).strip()
521
-
522
- if not text:
523
- return "I can help explain what the question is asking, but I need the full wording of the question."
524
-
525
- return text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # conversation_logic.py
2
  from __future__ import annotations
3
 
4
  import re
5
+ from typing import Any, Dict, List, Optional, Set
6
+
7
+ from context_parser import detect_intent, intent_to_help_mode
8
+ from formatting import format_reply, format_explainer_response
9
+ from generator_engine import GeneratorEngine
10
+ from models import RetrievedChunk, SolverResult
11
+ from quant_solver import is_quant_question
12
+ from solver_router import route_solver
13
+ from explainers.explainer_router import route_explainer
14
+ from question_classifier import classify_question, normalize_category
15
+ from retrieval_engine import RetrievalEngine
16
+ from utils import normalize_spaces
17
+
18
+
19
+ RETRIEVAL_ALLOWED_INTENTS = {
20
+ "walkthrough",
21
+ "step_by_step",
22
+ "explain",
23
+ "method",
24
+ "hint",
25
+ "definition",
26
+ "concept",
27
+ "instruction",
28
+ }
29
+
30
+ DIRECT_SOLVE_PATTERNS = [
31
+ r"\bsolve\b",
32
+ r"\bwhat is\b",
33
+ r"\bfind\b",
34
+ r"\bgive (?:me )?the answer\b",
35
+ r"\bjust the answer\b",
36
+ r"\banswer only\b",
37
+ r"\bcalculate\b",
38
+ ]
39
+
40
+ STRUCTURE_KEYWORDS = {
41
+ "algebra": ["equation", "solve", "isolate", "variable", "linear", "expression", "unknown", "algebra"],
42
+ "percent": ["percent", "%", "percentage", "increase", "decrease"],
43
+ "ratio": ["ratio", "proportion", "part", "share"],
44
+ "statistics": ["mean", "median", "mode", "range", "average"],
45
+ "probability": ["probability", "chance", "odds"],
46
+ "geometry": ["triangle", "circle", "angle", "area", "perimeter", "radius", "diameter"],
47
+ "number_theory": ["integer", "odd", "even", "prime", "divisible", "factor", "multiple", "remainder"],
48
+ "sequence": ["sequence", "geometric", "arithmetic", "term", "series"],
49
+ "quant": ["equation", "solve", "value", "integer", "ratio", "percent"],
50
+ "data": ["data", "mean", "median", "trend", "chart", "table", "correlation"],
51
+ "verbal": ["grammar", "meaning", "author", "argument", "sentence", "word"],
52
+ }
53
+
54
+ INTENT_KEYWORDS = {
55
+ "walkthrough": ["walkthrough", "work through", "step by step", "full working"],
56
+ "step_by_step": ["step", "first step", "next step", "step by step"],
57
+ "explain": ["explain", "why", "understand"],
58
+ "method": ["method", "approach", "how do i solve", "how to solve", "equation", "formula"],
59
+ "hint": ["hint", "nudge", "clue", "what do i do"],
60
+ "definition": ["define", "definition", "what does", "what is meant by", "meaning"],
61
+ "concept": ["concept", "idea", "principle", "rule"],
62
+ "instruction": ["how do i", "how to", "what should i do first", "what step", "first step"],
63
+ }
64
+
65
+ MISMATCH_TERMS = {
66
+ "algebra": ["absolute value", "modulus", "square root", "quadratic", "inequality", "roots", "parabola"],
67
+ "percent": ["triangle", "circle", "prime", "absolute value"],
68
+ "ratio": ["absolute value", "quadratic", "circle"],
69
+ "statistics": ["absolute value", "prime", "triangle"],
70
+ "probability": ["absolute value", "circle area", "quadratic"],
71
+ "geometry": ["absolute value", "prime", "median salary"],
72
+ "number_theory": ["circle", "triangle", "median salary"],
73
+ }
74
+
75
+
76
+ def _normalize_classified_topic(topic: Optional[str], category: Optional[str], question_text: str) -> str:
77
+ t = (topic or "").strip().lower()
78
+ q = (question_text or "").lower()
79
+ c = normalize_category(category)
80
+
81
+ has_ratio_form = bool(re.search(r"\b\d+\s*:\s*\d+\b", q))
82
+ has_algebra_form = (
83
+ "=" in q
84
+ or bool(re.search(r"\b[xyz]\b", q))
85
+ or bool(re.search(r"\d+[a-z]\b", q))
86
+ or bool(re.search(r"\b[a-z]\s*[\+\-\*/=]", q))
87
+ )
88
 
89
+ if t == "ratio" and not has_ratio_form and has_algebra_form:
90
+ t = "algebra"
91
 
92
+ if t not in {"general_quant", "general", "unknown", ""}:
93
+ return t
 
 
 
 
 
 
94
 
95
+ if "%" in q or "percent" in q:
96
+ return "percent"
97
+ if "ratio" in q or has_ratio_form:
98
+ return "ratio"
99
+ if "probability" in q or "chosen at random" in q or "odds" in q or "chance" in q:
100
+ return "probability"
101
+ if "divisible" in q or "remainder" in q or "prime" in q or "factor" in q:
102
+ return "number_theory"
103
+ if any(k in q for k in ["circle", "triangle", "perimeter", "area", "circumference"]):
104
+ return "geometry"
105
+ if any(k in q for k in ["mean", "median", "average", "sales", "revenue"]):
106
+ return "statistics" if c == "Quantitative" else "data"
107
+ if has_algebra_form or "what is x" in q or "what is y" in q or "integer" in q:
108
+ return "algebra"
109
 
110
+ if c == "DataInsight":
111
+ return "data"
112
+ if c == "Verbal":
113
+ return "verbal"
114
+ if c == "Quantitative":
115
+ return "quant"
 
116
 
117
+ return "general"
118
 
 
 
 
 
 
119
 
120
+ def _teaching_lines(chunks: List[RetrievedChunk]) -> List[str]:
121
+ lines: List[str] = []
122
+ for chunk in chunks:
123
+ text = (chunk.text or "").strip().replace("\n", " ")
124
+ if len(text) > 220:
125
+ text = text[:217].rstrip() + "…"
126
+ topic = chunk.topic or "general"
127
+ lines.append(f"- {topic}: {text}")
128
+ return lines
129
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
 
131
+ def _safe_steps(steps: List[str]) -> List[str]:
132
+ cleaned: List[str] = []
133
+ banned_patterns = [
134
+ r"\bthe answer is\b",
135
+ r"\banswer:\b",
136
+ r"\bthat gives\b",
137
+ r"\btherefore\b",
138
+ r"\bso x\s*=",
139
+ r"\bso y\s*=",
140
+ r"\bx\s*=",
141
+ r"\by\s*=",
142
+ r"\bresult is\b",
143
+ ]
144
+
145
+ for step in steps:
146
+ s = (step or "").strip()
147
+ lowered = s.lower()
148
+ if any(re.search(p, lowered) for p in banned_patterns):
149
+ continue
150
+ cleaned.append(s)
151
 
 
 
 
 
152
  return cleaned
153
 
154
 
155
+ def _compose_reply(
156
+ result: SolverResult,
157
+ intent: str,
158
+ verbosity: float,
159
+ category: Optional[str] = None,
160
+ ) -> str:
161
+ steps = _safe_steps(result.steps or [])
162
+ topic = (result.topic or "").lower().strip()
163
+
164
+ def topic_hint_fallback() -> str:
165
+ if topic == "algebra":
166
+ return "Solve for the variable."
167
+ if topic == "percent":
168
+ return "Find the percent relationship first."
169
+ if topic == "ratio":
170
+ return "Set up the ratio relationship."
171
+ if topic == "probability":
172
+ return "Identify the total possible outcomes first."
173
+ if topic == "statistics":
174
+ return "Work out which measure the question is asking for."
175
+ if topic == "geometry":
176
+ return "Focus on the figure relationships first."
177
+ if topic == "number_theory":
178
+ return "Use the number properties in the question."
179
+ return "Focus on the main relationship first."
180
+
181
+ def topic_method_fallback() -> str:
182
+ if topic == "algebra":
183
+ return "\n".join([
184
+ "- Treat it as an equation.",
185
+ "- Undo operations on both sides to isolate the variable.",
186
+ ])
187
+ if topic == "percent":
188
+ return "\n".join([
189
+ "- Identify whether you need the part, the whole, or the percent.",
190
+ "- Then set up the percent relationship carefully.",
191
+ ])
192
+ if topic == "ratio":
193
+ return "\n".join([
194
+ "- Identify which quantities are being compared.",
195
+ "- Keep the ratio in the correct order throughout.",
196
+ ])
197
+ if topic == "probability":
198
+ return "\n".join([
199
+ "- Identify what counts as a successful outcome.",
200
+ "- Then compare favorable outcomes to total possible outcomes.",
201
+ ])
202
+ if topic == "statistics":
203
+ return "\n".join([
204
+ "- Identify which statistic the question is asking for.",
205
+ "- Then use the relevant values only.",
206
+ ])
207
+ if topic == "geometry":
208
+ return "\n".join([
209
+ "- Identify the relevant shape properties.",
210
+ "- Then use the relationships given in the diagram or wording.",
211
+ ])
212
+ if topic == "number_theory":
213
+ return "\n".join([
214
+ "- Identify the relevant number property.",
215
+ "- Then apply the divisibility or factor rule carefully.",
216
+ ])
217
+ return "I can explain the method, but I do not have enough structured steps yet."
218
+
219
+ if intent == "hint":
220
+ if steps:
221
+ first = steps[0].lower()
222
+
223
+ if "equation" in first or "=" in first:
224
+ return "Treat it as an equation."
225
+ if "isolate" in first or "variable" in first or "solve" in first:
226
+ return "Solve for the variable."
227
+ if "percent" in first:
228
+ return "Find the percent relationship first."
229
+ if "ratio" in first:
230
+ return "Set up the ratio relationship."
231
+ if "probability" in first:
232
+ return "Identify the total possible outcomes first."
233
+
234
+ return topic_hint_fallback()
235
+
236
+ if intent == "instruction":
237
+ if steps:
238
+ return f"First step: {steps[0]}"
239
+ return "First, identify the key relationship or comparison in the question."
240
+
241
+ if intent == "definition":
242
+ if steps:
243
+ return f"Here is the idea in context:\n- {steps[0]}"
244
+ return "This is asking for the meaning of the term or idea in the question."
245
+
246
+ if intent in {"walkthrough", "step_by_step", "explain", "method", "concept"}:
247
+ if not steps:
248
+ return topic_method_fallback()
249
+
250
+ generic_lines = {
251
+ "solve for the variable.",
252
+ "treat it as an equation.",
253
+ "identify the quantity the question wants.",
254
+ "focus on the relationship in the question.",
255
+ }
256
+
257
+ meaningful_steps = []
258
+ for s in steps:
259
+ clean = (s or "").strip()
260
+ if not clean:
261
+ continue
262
+ if clean.lower() in generic_lines and len(steps) > 1:
263
+ continue
264
+ meaningful_steps.append(clean)
265
+
266
+ if not meaningful_steps:
267
+ meaningful_steps = steps
268
+
269
+ if verbosity < 0.25:
270
+ shown_steps = meaningful_steps[:1]
271
+ elif verbosity < 0.6:
272
+ shown_steps = meaningful_steps[:2]
273
+ elif verbosity < 0.85:
274
+ shown_steps = meaningful_steps[:3]
275
+ else:
276
+ shown_steps = meaningful_steps
277
+
278
+ return "\n".join(f"- {s}" for s in shown_steps)
279
+
280
+ if steps:
281
+ if verbosity < 0.35:
282
+ shown_steps = steps[:1]
283
+ else:
284
+ shown_steps = steps[:2]
285
+
286
+ if len(shown_steps) == 1:
287
+ return shown_steps[0]
288
+
289
+ return "\n".join(f"- {s}" for s in shown_steps)
290
+
291
+ if normalize_category(category) == "Verbal":
292
+ return "I can help analyse the wording or logic, but I need the full question text to guide you properly."
293
+
294
+ if normalize_category(category) == "DataInsight":
295
+ return "I can help reason through the data, but I need the full question or chart details to guide you properly."
296
+
297
+ return "I can help with this, but I need the full question text to guide you properly."
298
+
299
+
300
+ def is_explainer_request(text: str) -> bool:
301
+ t = (text or "").strip().lower()
302
+
303
+ explainer_signals = [
304
+ "how do i solve",
305
+ "how to solve",
306
+ "explain this",
307
+ "walk me through",
308
+ "walkthrough",
309
+ "show me how",
310
+ "what is the method",
311
+ "how would you do this",
312
+ "help me understand",
313
+ "what's the approach",
314
+ "what is the approach",
315
+ "how should i think about this",
316
+ "what is this asking",
317
+ "how do i approach this",
318
+ "can you explain",
319
+ "explain how",
320
+ "explain why",
321
+ "break this down",
322
+ "question breakdown",
323
+ "what should i identify first",
324
+ "what do i do first",
325
+ "what is the first move",
326
+ ]
327
 
328
+ return any(p in t for p in explainer_signals)
 
 
 
 
 
 
 
 
 
 
 
 
 
329
 
 
330
 
331
+ def _normalize_text(text: str) -> str:
332
+ return re.sub(r"\s+", " ", (text or "").strip().lower())
333
 
 
 
334
 
335
+ def _extract_keywords(text: str) -> Set[str]:
336
+ raw = re.findall(r"[a-zA-Z][a-zA-Z0-9_+-]*", (text or "").lower())
337
+ stop = {
338
+ "the", "a", "an", "is", "are", "to", "of", "for", "and", "or", "in", "on", "at", "by", "this", "that",
339
+ "it", "be", "do", "i", "me", "my", "you", "how", "what", "why", "give", "show", "please", "can",
340
+ }
341
+ return {w for w in raw if len(w) > 2 and w not in stop}
342
+
343
+
344
+ def _infer_structure_terms(question_text: str, topic: Optional[str], question_type: Optional[str]) -> List[str]:
345
+ terms: List[str] = []
346
+
347
+ if topic and topic in STRUCTURE_KEYWORDS:
348
+ terms.extend(STRUCTURE_KEYWORDS[topic])
349
+
350
+ if question_type:
351
+ terms.extend(question_type.replace("_", " ").split())
352
+
353
+ q = (question_text or "").lower()
354
+ if "=" in q:
355
+ terms.extend(["equation", "solve"])
356
+ if "x" in q or "y" in q:
357
+ terms.extend(["variable", "isolate"])
358
+ if "/" in q or "divide" in q:
359
+ terms.extend(["divide", "undo operations"])
360
+ if "*" in q or "times" in q or "multiply" in q:
361
+ terms.extend(["multiply", "undo operations"])
362
+ if "%" in q or "percent" in q:
363
+ terms.extend(["percent", "percentage"])
364
+ if "ratio" in q or re.search(r"\b\d+\s*:\s*\d+\b", q):
365
+ terms.extend(["ratio", "proportion"])
366
+ if "mean" in q or "average" in q:
367
+ terms.extend(["mean", "average"])
368
+ if "median" in q:
369
+ terms.extend(["median"])
370
+ if "probability" in q or "odds" in q or "chance" in q:
371
+ terms.extend(["probability", "outcome", "event"])
372
+ if "remainder" in q or "divisible" in q:
373
+ terms.extend(["remainder", "divisible"])
374
+
375
+ return list(dict.fromkeys(terms))
376
+
377
+
378
+ def _infer_mismatch_terms(topic: Optional[str], question_text: str) -> List[str]:
379
+ if not topic or topic not in MISMATCH_TERMS:
380
+ return []
381
+ q = (question_text or "").lower()
382
+ return [term for term in MISMATCH_TERMS[topic] if term not in q]
383
 
 
 
384
 
385
+ def _intent_keywords(intent: str) -> List[str]:
386
+ return INTENT_KEYWORDS.get(intent, [])
387
 
 
 
388
 
389
+ def _is_direct_solve_request(text: str, intent: str) -> bool:
390
+ if intent == "answer":
391
+ return True
392
 
393
+ t = _normalize_text(text)
394
+ if any(re.search(p, t) for p in DIRECT_SOLVE_PATTERNS):
395
+ if not any(word in t for word in ["how", "explain", "why", "method", "hint", "define", "definition", "step"]):
396
+ return True
397
+ return False
398
 
 
399
 
400
+ def should_retrieve(
401
+ intent: str,
402
+ solved: bool,
403
+ raw_user_text: str,
404
+ category: Optional[str] = None,
405
+ domain: Optional[str] = None,
406
+ topic: Optional[str] = None,
407
+ ) -> bool:
408
+ normalized_category = normalize_category(category)
409
+ normalized_domain = (domain or "").strip().lower()
410
+ normalized_topic = (topic or "").strip().lower()
411
 
412
+ if intent == "hint":
413
+ return False
 
 
414
 
415
+ if normalized_domain == "quant":
416
+ if intent in {"walkthrough", "step_by_step", "method", "explain", "concept"}:
417
+ return normalized_topic not in {"", "general", "unknown", "general_quant"}
418
+ return False
 
419
 
420
+ if intent in {"walkthrough", "step_by_step", "method", "explain", "concept", "definition", "instruction"}:
421
+ return True
422
 
423
+ if _is_direct_solve_request(raw_user_text, intent):
424
+ return (not solved) and normalized_category in {"Verbal", "DataInsight"}
425
 
426
+ if not solved and normalized_category in {"Verbal", "DataInsight"}:
427
+ return True
 
428
 
429
+ return False
 
430
 
 
 
 
 
 
 
431
 
432
+ def _score_chunk(
433
+ chunk: RetrievedChunk,
434
+ intent: str,
435
+ topic: Optional[str],
436
+ question_text: str,
437
+ question_type: Optional[str] = None,
438
+ ) -> float:
439
+ text = f"{chunk.topic} {chunk.text}".lower()
440
+ score = 0.0
441
 
442
+ if topic:
443
+ chunk_topic = (chunk.topic or "").lower()
444
+ if chunk_topic == topic.lower():
445
+ score += 4.0
446
+ elif topic.lower() in text:
447
+ score += 2.0
448
+
449
+ for term in _infer_structure_terms(question_text, topic, question_type):
450
+ if term.lower() in text:
451
+ score += 1.5
452
+
453
+ for term in _intent_keywords(intent):
454
+ if term.lower() in text:
455
+ score += 1.2
456
+
457
+ overlap = sum(1 for kw in _extract_keywords(question_text) if kw in text)
458
+ score += min(overlap * 0.4, 3.0)
459
+
460
+ for bad in _infer_mismatch_terms(topic, question_text):
461
+ if bad.lower() in text:
462
+ score -= 2.5
463
+
464
+ return score
465
+
466
+
467
+ def _filter_retrieved_chunks(
468
+ chunks: List[RetrievedChunk],
469
+ intent: str,
470
+ topic: Optional[str],
471
+ question_text: str,
472
+ question_type: Optional[str] = None,
473
+ min_score: float = 3.2,
474
+ max_chunks: int = 3,
475
+ ) -> List[RetrievedChunk]:
476
+ scored: List[tuple[float, RetrievedChunk]] = []
477
+ normalized_topic = (topic or "").lower()
478
+
479
+ for chunk in chunks:
480
+ chunk_topic = (chunk.topic or "").lower()
481
+
482
+ if normalized_topic and normalized_topic not in {"general", "unknown", "general_quant"}:
483
+ if chunk_topic == "general":
484
+ continue
485
+
486
+ s = _score_chunk(chunk, intent, topic, question_text, question_type)
487
+ if s >= min_score:
488
+ scored.append((s, chunk))
489
+
490
+ scored.sort(key=lambda x: x[0], reverse=True)
491
+ filtered = [chunk for _, chunk in scored[:max_chunks]]
492
+ if filtered:
493
+ return filtered
494
+
495
+ fallback: List[tuple[float, RetrievedChunk]] = []
496
+ for chunk in chunks:
497
+ s = _score_chunk(chunk, intent, topic, question_text, question_type)
498
+ if s >= 2.0:
499
+ fallback.append((s, chunk))
500
+
501
+ fallback.sort(key=lambda x: x[0], reverse=True)
502
+ return [chunk for _, chunk in fallback[:max_chunks]]
503
+
504
+
505
+ def _build_retrieval_query(
506
+ raw_user_text: str,
507
+ question_text: str,
508
+ intent: str,
509
+ topic: Optional[str],
510
+ solved: bool,
511
+ question_type: Optional[str] = None,
512
+ category: Optional[str] = None,
513
+ ) -> str:
514
+ parts: List[str] = []
515
+
516
+ raw = (raw_user_text or "").strip()
517
+ question = (question_text or "").strip()
518
+
519
+ if question:
520
+ parts.append(question)
521
+ elif raw:
522
+ lowered = raw.lower()
523
+
524
+ wrappers = [
525
+ "how do i solve",
526
+ "how to solve",
527
+ "solve",
528
+ "can you solve",
529
+ "walk me through",
530
+ "explain",
531
+ "help me solve",
532
+ "show me how to solve",
533
+ ]
534
+
535
+ cleaned = raw
536
+ for w in wrappers:
537
+ if lowered.startswith(w):
538
+ cleaned = raw[len(w):].strip(" :.-?")
539
+ break
540
 
541
+ if cleaned:
542
+ parts.append(cleaned)
543
+ else:
544
+ parts.append(raw)
545
 
546
+ normalized_category = normalize_category(category)
547
+ if normalized_category and normalized_category != "General":
548
+ parts.append(normalized_category)
549
 
550
+ if topic:
551
+ parts.append(topic)
 
552
 
553
+ if question_type:
554
+ parts.append(question_type.replace("_", " "))
 
555
 
556
+ if intent in {"definition", "concept"}:
557
+ parts.append("definition concept explanation")
558
+ elif intent in {"walkthrough", "step_by_step", "method", "instruction"}:
559
+ parts.append("equation solving method isolate variable worked example")
560
+ elif intent == "hint":
561
+ parts.append("equation solving hint first step isolate variable")
562
+ elif intent == "explain":
563
+ parts.append("equation solving explanation reasoning")
564
+ elif not solved:
565
+ parts.append("teaching explanation method")
566
 
567
+ return " ".join(parts).strip()
 
 
568
 
 
 
 
569
 
570
+ def _fallback_more_info_reply(
571
+ category: Optional[str],
572
+ topic: Optional[str],
573
+ intent: str,
574
+ ) -> str:
575
+ normalized_category = normalize_category(category)
576
+
577
+ if normalized_category == "Quantitative" or topic in {
578
+ "algebra", "percent", "ratio", "probability", "number_theory", "geometry", "statistics", "quant"
579
+ }:
580
+ if intent in {"walkthrough", "step_by_step", "method", "explain", "hint", "instruction"}:
581
+ return (
582
+ "I need the full question wording to guide this properly step by step. "
583
+ "Please paste the complete problem, and include the answer choices if there are any."
584
+ )
585
+ return (
586
+ "I need the full question wording to help properly. "
587
+ "Please paste the complete problem, and include the answer choices if there are any."
588
+ )
589
 
590
+ if normalized_category == "DataInsight":
591
+ return (
592
+ "I need the full chart, table, or question wording to help properly. "
593
+ "Please send the complete prompt and any answer choices."
594
+ )
 
 
 
 
595
 
596
+ if normalized_category == "Verbal":
597
+ return (
598
+ "I need the full passage, sentence, or question wording to help properly. "
599
+ "Please paste the complete text and any answer choices."
600
+ )
601
 
602
+ return (
603
+ "I need a bit more information to help properly. "
604
+ "Please send the full question or exact wording."
605
+ )
606
 
 
607
 
608
+ def _is_bad_generated_reply(text: str, user_text: str = "") -> bool:
609
+ t = (text or "").strip()
610
+ tl = t.lower()
611
+ ul = (user_text or "").strip().lower()
612
 
613
+ if not t:
614
+ return True
615
 
616
+ if len(t) < 12:
617
+ return True
618
 
619
+ bad_exact = {
620
+ "0",
621
+ "formula",
622
+ "formula formula",
623
+ "the answer",
624
+ "answer only",
625
+ "unknown",
626
+ "none",
627
+ "n/a",
628
+ }
629
+ if tl in bad_exact:
630
+ return True
631
+
632
+ bad_substrings = [
633
+ "if the problem is not fully solvable",
634
+ "if the problem is not fully solvable from the parse",
635
+ "give the test a chance to solve it",
636
+ "use the formula formula",
637
+ "cannot parse alone yet",
638
+ "i cannot parse",
639
+ "current parse alone",
640
+ "from the parse alone",
641
+ ]
642
+ if any(b in tl for b in bad_substrings):
643
+ return True
644
+
645
+ banned_answer_patterns = [
646
+ r"\bthe answer is\b",
647
+ r"\banswer:\b",
648
+ r"\bx\s*=",
649
+ r"\by\s*=",
650
+ r"\btherefore\b",
651
+ r"\bthat gives\b",
652
+ r"\bresult is\b",
653
+ ]
654
+ if any(re.search(p, tl) for p in banned_answer_patterns):
655
+ return True
656
+
657
+ words = re.findall(r"\b\w+\b", tl)
658
+ if len(words) >= 4:
659
+ unique_ratio = len(set(words)) / max(1, len(words))
660
+ if unique_ratio < 0.45:
661
+ return True
662
+
663
+ user_keywords = _extract_keywords(ul)
664
+ gen_keywords = _extract_keywords(tl)
665
+ if user_keywords and gen_keywords:
666
+ overlap = user_keywords.intersection(gen_keywords)
667
+ if len(overlap) == 0 and len(t) < 180:
668
+ return True
669
+
670
+ nonsense_patterns = [
671
+ r"\bformula\s+formula\b",
672
+ r"\btest\s+a\s+chance\s+to\s+solve\b",
673
+ r"^[\W_]*\d+[\W_]*$",
674
+ ]
675
+ if any(re.search(p, tl) for p in nonsense_patterns):
676
+ return True
677
+
678
+ return False
679
+
680
+
681
+ def _clean_teaching_text(text: str) -> str:
682
+ text = normalize_spaces((text or "").replace("\n", " ").strip())
683
+ text = re.sub(r"^[\-\•\*\d\.\)\s]+", "", text)
684
+ if len(text) > 160:
685
+ text = text[:157].rstrip() + "..."
686
+ return text
687
 
 
 
 
 
 
 
 
 
688
 
689
+ def _looks_question_specific(text: str, question_text: str) -> bool:
690
+ t = (text or "").strip().lower()
691
+ q = (question_text or "").strip().lower()
692
+
693
+ if not t:
694
+ return True
695
+
696
+ banned_phrases = [
697
+ "the correct answer",
698
+ "answer choice",
699
+ "statement 1",
700
+ "statement 2",
701
+ "option a",
702
+ "option b",
703
+ "option c",
704
+ "option d",
705
+ "option e",
706
+ "try choice",
707
+ "plug in numbers",
708
+ "backsolving",
709
+ "working backwards",
710
+ "chapter",
711
+ "note:",
712
+ ]
713
+ if any(p in t for p in banned_phrases):
714
+ return True
715
+
716
+ if "gmat" in t[:25]:
717
+ return True
718
+
719
+ if "..." in t:
720
+ return True
721
+
722
+ if len(re.findall(r"\d+", t)) >= 3:
723
+ q_numbers = set(re.findall(r"\d+", q))
724
+ t_numbers = set(re.findall(r"\d+", t))
725
+ if t_numbers and t_numbers != q_numbers and len(t_numbers - q_numbers) >= 1:
726
+ return True
727
+
728
+ q_vars = set(re.findall(r"\b[a-z]\b", q))
729
+ t_vars = set(re.findall(r"\b[a-z]\b", t))
730
+ allowed_vars = q_vars | {"x", "y"}
731
+
732
+ if t_vars and q_vars:
733
+ extra_vars = t_vars - allowed_vars
734
+ if len(extra_vars) >= 1:
735
+ return True
736
+ if re.search(r"\bset\s+[a-z]\s+equal\s+to\b", t):
737
+ return True
738
+
739
+ if re.search(r"\bsolve for [a-z]\b", t) and q_vars:
740
+ mentioned = set(re.findall(r"\b[a-z]\b", t))
741
+ if mentioned - q_vars:
742
+ return True
743
+
744
+ if len(t.split()) > 35:
745
+ return True
746
+
747
+ return False
748
+
749
+
750
+ def _pick_teaching_line(
751
+ chunks: List[RetrievedChunk],
752
+ current_reply: str,
753
+ question_text: str,
754
+ topic: Optional[str] = None,
755
+ ) -> Optional[str]:
756
+ if not chunks:
757
+ return None
758
+
759
+ reply_keywords = _extract_keywords(current_reply)
760
+ desired_topic = (topic or "").lower().strip()
761
+
762
+ best_line = None
763
+ best_score = float("-inf")
764
+
765
+ topic_phrases = {
766
+ "algebra": ["equation", "isolate", "variable", "undo operations", "inverse operation"],
767
+ "percent": ["percent", "percentage", "base", "rate", "original value"],
768
+ "ratio": ["ratio", "proportion", "part", "share"],
769
+ "probability": ["probability", "outcome", "event", "sample space"],
770
+ "statistics": ["mean", "median", "average", "distribution"],
771
+ "geometry": ["angle", "triangle", "circle", "area", "perimeter"],
772
+ "number_theory": ["integer", "divisible", "remainder", "factor", "multiple", "prime"],
773
+ }
774
 
775
+ for chunk in chunks:
776
+ raw_text = (chunk.text or "").strip()
777
+ if not raw_text:
778
+ continue
779
 
780
+ text = _clean_teaching_text(raw_text)
 
781
  if not text:
782
  continue
 
 
 
 
 
 
 
783
 
784
+ lower_text = text.lower()
785
+ chunk_topic = (chunk.topic or "").lower().strip()
786
 
787
+ if _looks_question_specific(lower_text, question_text):
788
+ continue
789
+
790
+ chunk_keywords = _extract_keywords(lower_text)
791
+ novelty_vs_reply = len(chunk_keywords - reply_keywords)
792
+ overlap_with_reply = len(chunk_keywords & reply_keywords)
793
+
794
+ topic_bonus = 0.0
795
+ if desired_topic and chunk_topic == desired_topic:
796
+ topic_bonus += 3.0
797
+ elif desired_topic and desired_topic in chunk_topic:
798
+ topic_bonus += 2.0
799
+
800
+ phrase_bonus = 0.0
801
+ for phrase in topic_phrases.get(desired_topic, []):
802
+ if phrase in lower_text:
803
+ phrase_bonus += 1.0
804
+
805
+ score = (
806
+ topic_bonus
807
+ + phrase_bonus
808
+ + 1.2 * novelty_vs_reply
809
+ - 0.8 * overlap_with_reply
810
+ )
811
 
812
+ if len(text.split()) < 5:
813
+ score -= 2.0
 
 
814
 
815
+ if score > best_score:
816
+ best_score = score
817
+ best_line = text
 
818
 
819
+ if best_score < 2.5:
820
+ return None
821
 
822
+ return best_line
 
823
 
824
 
825
+ def _safe_meta_list(items: Any) -> List[str]:
826
+ if not items:
827
  return []
828
+ if isinstance(items, list):
829
+ return [str(x).strip() for x in items if str(x).strip()]
830
+ if isinstance(items, tuple):
831
+ return [str(x).strip() for x in items if str(x).strip()]
832
+ if isinstance(items, str):
833
+ text = items.strip()
834
  return [text] if text else []
835
  return []
836
 
837
 
838
+ def _safe_meta_text(value: Any) -> Optional[str]:
839
+ if value is None:
840
+ return None
841
+ text = str(value).strip()
842
+ return text or None
843
 
844
 
845
+ def _extract_explainer_scaffold(explainer_result: Any) -> Dict[str, Any]:
846
+ scaffold = getattr(explainer_result, "scaffold", None)
 
 
 
 
 
 
 
 
 
847
 
848
+ if scaffold is None:
849
+ return {}
850
+
851
+ return {
852
+ "concept": _safe_meta_text(getattr(scaffold, "concept", None)),
853
+ "ask": _safe_meta_text(getattr(scaffold, "ask", None)),
854
+ "givens": _safe_meta_list(getattr(scaffold, "givens", [])),
855
+ "target": _safe_meta_text(getattr(scaffold, "target", None)),
856
+ "setup_actions": _safe_meta_list(getattr(scaffold, "setup_actions", [])),
857
+ "intermediate_steps": _safe_meta_list(getattr(scaffold, "intermediate_steps", [])),
858
+ "first_move": _safe_meta_text(getattr(scaffold, "first_move", None)),
859
+ "next_hint": _safe_meta_text(getattr(scaffold, "next_hint", None)),
860
+ "common_traps": _safe_meta_list(getattr(scaffold, "common_traps", [])),
861
+ "variables_to_define": _safe_meta_list(getattr(scaffold, "variables_to_define", [])),
862
+ "equations_to_form": _safe_meta_list(getattr(scaffold, "equations_to_form", [])),
863
+ "answer_hidden": bool(getattr(scaffold, "answer_hidden", True)),
864
+ }
865
 
 
 
 
 
 
 
 
866
 
867
+ class ConversationEngine:
868
+ def __init__(
869
+ self,
870
+ retriever: Optional[RetrievalEngine] = None,
871
+ generator: Optional[GeneratorEngine] = None,
872
+ **kwargs,
873
+ ) -> None:
874
+ self.retriever = retriever
875
+ self.generator = generator
876
+
877
+ def generate_response(
878
+ self,
879
+ raw_user_text: Optional[str] = None,
880
+ tone: float = 0.5,
881
+ verbosity: float = 0.5,
882
+ transparency: float = 0.5,
883
+ intent: Optional[str] = None,
884
+ help_mode: Optional[str] = None,
885
+ retrieval_context: Optional[List[RetrievedChunk]] = None,
886
+ chat_history: Optional[List[Dict[str, Any]]] = None,
887
+ question_text: Optional[str] = None,
888
+ options_text: Optional[List[str]] = None,
889
+ **kwargs,
890
+ ) -> SolverResult:
891
+ solver_input = (question_text or raw_user_text or "").strip()
892
+ user_text = (raw_user_text or "").strip()
893
+
894
+ reply: Optional[str] = None
895
+ selected_chunks: List[RetrievedChunk] = []
896
+
897
+ category = normalize_category(kwargs.get("category"))
898
+ classification = classify_question(question_text=solver_input, category=category)
899
+ inferred_category = normalize_category(classification.get("category") or category)
900
+
901
+ question_topic = _normalize_classified_topic(
902
+ classification.get("topic"),
903
+ inferred_category,
904
+ solver_input,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
905
  )
906
+ question_type = classification.get("type")
907
+
908
+ resolved_intent = intent or detect_intent(user_text, help_mode)
909
+ resolved_help_mode = help_mode or intent_to_help_mode(resolved_intent)
910
+
911
+ is_quant = inferred_category == "Quantitative" or is_quant_question(solver_input)
912
+
913
+ result = SolverResult(
914
+ domain="quant" if is_quant else "general",
915
+ solved=False,
916
+ help_mode=resolved_help_mode,
917
+ answer_letter=None,
918
+ answer_value=None,
919
+ topic=question_topic,
920
+ used_retrieval=False,
921
+ used_generator=False,
922
+ internal_answer=None,
923
+ steps=[],
924
+ teaching_chunks=[],
925
+ meta={},
926
  )
927
 
928
+ # 1. explainer path first
929
+ if is_explainer_request(user_text or solver_input):
930
+ explainer_result = route_explainer(solver_input)
931
+
932
+ if explainer_result is not None and getattr(explainer_result, "understood", False):
933
+ reply = format_explainer_response(
934
+ result=explainer_result,
935
+ tone=tone,
936
+ verbosity=verbosity,
937
+ transparency=transparency,
938
+ )
939
+
940
+ scaffold_meta = _extract_explainer_scaffold(explainer_result)
941
+
942
+ result.domain = "quant" if is_quant else "general"
943
+ result.solved = False
944
+ result.help_mode = "explain"
945
+ result.topic = getattr(explainer_result, "topic", None) or question_topic
946
+ result.answer_letter = None
947
+ result.answer_value = None
948
+ result.internal_answer = None
949
+ result.used_retrieval = False
950
+ result.used_generator = False
951
+ result.reply = reply
952
+ result.meta = {
953
+ "intent": "explain_question",
954
+ "question_text": question_text or "",
955
+ "options_count": len(options_text or []),
956
+ "category": inferred_category,
957
+ "question_type": question_type,
958
+ "classified_topic": question_topic,
959
+ "explainer_used": True,
960
+ "bridge_ready": bool(getattr(explainer_result, "meta", {}).get("bridge_ready", False)),
961
+ "hint_style": getattr(explainer_result, "meta", {}).get("hint_style"),
962
+ "explainer_summary": getattr(explainer_result, "summary", None),
963
+ "explainer_teaching_points": _safe_meta_list(
964
+ getattr(explainer_result, "teaching_points", [])
965
+ ),
966
+ "scaffold": scaffold_meta,
967
+ }
968
+ return result
969
+
970
+ # 2. normal solver path
971
+ if is_quant:
972
+ solved_result = route_solver(solver_input)
973
+
974
+ if solved_result is not None:
975
+ result = solved_result
976
+
977
+ result.help_mode = resolved_help_mode
978
+
979
+ if not result.topic or result.topic in {"general_quant", "general", "unknown"}:
980
+ result.topic = question_topic
981
+
982
+ result.domain = "quant"
983
+
984
+ # 3. compose base reply
985
+ reply = _compose_reply(
986
+ result=result,
987
+ intent=resolved_intent,
988
+ verbosity=verbosity,
989
+ category=inferred_category,
990
  )
991
 
992
+ # 4. optional retrieval
993
+ allow_retrieval = should_retrieve(
994
+ intent=resolved_intent,
995
+ solved=bool(result.solved),
996
+ raw_user_text=user_text or solver_input,
997
+ category=inferred_category,
998
+ domain=result.domain,
999
+ topic=result.topic,
1000
  )
1001
 
1002
+ if allow_retrieval and reply and len(reply) < 220:
1003
+ if retrieval_context:
1004
+ filtered = _filter_retrieved_chunks(
1005
+ chunks=retrieval_context,
1006
+ intent=resolved_intent,
1007
+ topic=result.topic,
1008
+ question_text=solver_input,
1009
+ question_type=question_type,
1010
+ )
1011
+ if filtered:
1012
+ selected_chunks = filtered
1013
+ result.used_retrieval = True
1014
+ result.teaching_chunks = filtered
1015
+
1016
+ elif self.retriever is not None:
1017
+ retrieved = self.retriever.search(
1018
+ query=_build_retrieval_query(
1019
+ raw_user_text=user_text,
1020
+ question_text=solver_input,
1021
+ intent=resolved_intent,
1022
+ topic=result.topic,
1023
+ solved=bool(result.solved),
1024
+ question_type=question_type,
1025
+ category=inferred_category,
1026
+ ),
1027
+ topic=result.topic or "",
1028
+ intent=resolved_intent,
1029
+ k=6,
1030
+ )
1031
+ filtered = _filter_retrieved_chunks(
1032
+ chunks=retrieved,
1033
+ intent=resolved_intent,
1034
+ topic=result.topic,
1035
+ question_text=solver_input,
1036
+ question_type=question_type,
1037
+ )
1038
+ if filtered:
1039
+ selected_chunks = filtered
1040
+ result.used_retrieval = True
1041
+ result.teaching_chunks = filtered
1042
+
1043
+ if selected_chunks and resolved_help_mode in {"walkthrough", "step_by_step", "method", "explain", "concept"}:
1044
+ teaching_line = _pick_teaching_line(
1045
+ chunks=selected_chunks,
1046
+ current_reply=reply,
1047
+ question_text=solver_input,
1048
+ topic=result.topic,
1049
+ )
1050
+ if teaching_line:
1051
+ reply = f"{reply}\n\nKey idea: {teaching_line}"
1052
+
1053
+ # 5. generator only for non-quant
1054
+ should_try_generator = (
1055
+ self.generator is not None
1056
+ and not result.solved
1057
+ and resolved_help_mode not in {"hint", "instruction"}
1058
+ and result.domain != "quant"
1059
  )
1060
 
1061
+ if should_try_generator:
1062
+ try:
1063
+ generated = self.generator.generate(
1064
+ user_text=user_text or solver_input,
1065
+ question_text=solver_input,
1066
+ topic=result.topic or "",
1067
+ intent=resolved_intent,
1068
+ retrieval_context=selected_chunks,
1069
+ chat_history=chat_history or [],
1070
+ )
1071
+
1072
+ if generated and generated.strip():
1073
+ candidate = generated.strip()
1074
+
1075
+ if not _is_bad_generated_reply(candidate, user_text or solver_input):
1076
+ reply = candidate
1077
+ result.used_generator = True
1078
+ else:
1079
+ reply = _fallback_more_info_reply(
1080
+ category=inferred_category,
1081
+ topic=result.topic,
1082
+ intent=resolved_intent,
1083
+ )
1084
+ else:
1085
+ reply = _fallback_more_info_reply(
1086
+ category=inferred_category,
1087
+ topic=result.topic,
1088
+ intent=resolved_intent,
1089
+ )
1090
+
1091
+ except Exception:
1092
+ reply = _fallback_more_info_reply(
1093
+ category=inferred_category,
1094
+ topic=result.topic,
1095
+ intent=resolved_intent,
1096
+ )
1097
+
1098
+ # 6. final fallback
1099
+ if not reply:
1100
+ reply = _fallback_more_info_reply(
1101
+ category=inferred_category,
1102
+ topic=result.topic,
1103
+ intent=resolved_intent,
1104
+ )
1105
+
1106
+ reply = format_reply(reply, tone, verbosity, transparency, resolved_help_mode)
1107
+
1108
+ result.answer_letter = None
1109
+ result.answer_value = None
1110
+ result.internal_answer = None
1111
+ result.reply = reply
1112
+ result.help_mode = resolved_help_mode
1113
+ result.meta = {
1114
+ "intent": resolved_intent,
1115
+ "question_text": question_text or "",
1116
+ "options_count": len(options_text or []),
1117
+ "category": inferred_category,
1118
+ "question_type": question_type,
1119
+ "classified_topic": question_topic,
1120
+ "explainer_used": False,
1121
+ }
1122
+
1123
+ return result