"""Precalculus EdTech agent — Gradio app. Learner journey (one learner id shared by every tab): 1. **Placement** — required first. One handwritten (photo) or typed problem per topic, with reasoning. Result → Research Agent → learning plan. 2. **Worked examples** — Research Agent tutoring: worked example → faded half → full problem → transfer quiz requested from the Retrieval Agent. 3. **Retrieval quiz** — mostly handwritten, interleaved retrieval practice (Retrieval Agent). 4. **Peer instruction** — Human-to-Agent peer instruction: solve + explain + confidence → peer feedback → revise. 5. **PLM drill** — perceptual fluency (GraphSense / ConicSense). 6. **Agent debug** — run the real smolagents agents from fixed dropdowns (no free-text prompt surface). """ import json import time import gradio as gr from smolagents import ActionStep from src.config import PROJECT_ROOT, QUIZ_DEFAULT_ITEMS from src.edtech_core import assessment as assess from src.edtech_core.arts import ArtsTracker, CategoryState from src.edtech_core.curriculum import TOPIC_BY_ID, TOPICS from src.edtech_core.judge import evaluate_work, format_feedback from src.edtech_core.learner_model import LearnerState from src.edtech_core.llm import LLMUnavailable, read_response from src.edtech_core.peer_instruction import PeerInstructionSession from src.edtech_core.quiz import AssessmentRequired, build_quiz, grade, record_quiz_results from src.edtech_core.worked_examples import WorkedExampleTutor from src.generators import precalc LATEX = [{"left": "$$", "right": "$$", "display": True}, {"left": "$", "right": "$", "display": False}, {"left": "\\(", "right": "\\)", "display": False}, {"left": "\\[", "right": "\\]", "display": True}] TOPIC_CHOICES = [(f"Ch {t.chapter} · {t.title}", t.id) for t in TOPICS] AUTO = "auto" def _lid(x: str) -> str: return (x or "").strip() or "demo" def _imgs(paths) -> gr.Gallery: full = [str(PROJECT_ROOT / p) for p in (paths or [])] return gr.Gallery(value=full or None, visible=bool(full)) def _read(img, txt) -> str: return read_response(img, txt) def _progress_rows(learner_id): s = LearnerState.load(_lid(learner_id)) rows = s.summary() for t, lvl in ((s.assessment or {}).get("levels") or {}).items(): if t not in s.covered: rows.append({"topic": t, "title": TOPIC_BY_ID[t].title, "status": f"placement: {lvl}"}) return rows # ============================================================================ 1 · placement def start_assessment(learner_id): a = assess.build_assessment(_lid(learner_id)) st = {"aid": a["assessment_id"], "idx": 0, "n": len(a["items"])} return (st, f"**{a['instructions']}**", *_assessment_item(_lid(learner_id), st), "", None, "", gr.Button(visible=True), gr.Button(visible=False)) def _assessment_item(learner_id, st): a = assess.load_assessment(learner_id, st["aid"]) it = a["items"][st["idx"]] head = f"### Placement {st['idx'] + 1}/{st['n']} · {it['topic_title']}" return head, it["statement"], _imgs(it["image_paths"]) def submit_assessment(learner_id, st, img, txt): if not st: return "Start the assessment first.", gr.Button(visible=False), gr.Button(visible=False) try: work = _read(img, txt) a = assess.load_assessment(_lid(learner_id), st["aid"]) ev = assess.submit_assessment_answer(_lid(learner_id), st["aid"], a["items"][st["idx"]]["n"], work) except LLMUnavailable as e: return f"⚠️ Model unavailable, try again: {e}", gr.Button(visible=False), gr.Button(visible=False) last = st["idx"] + 1 >= st["n"] shown = f"**Read as:**\n\n{work}\n\n---\n\n" if img else "" return shown + format_feedback(ev), gr.Button(visible=not last), gr.Button(visible=last) def next_assessment(learner_id, st): st["idx"] += 1 return (st, *_assessment_item(_lid(learner_id), st), "", None, "", gr.Button(visible=False)) def finish_assessment(learner_id, st): res = assess.finalize_assessment(_lid(learner_id), st["aid"]) a, plan = res["assessment"], res["learning_plan"] lines = [f"## Placement complete — {a['score']}", plan.get("summary", ""), "### Research Agent's plan"] lines += [f"{i}. **{s['title']}** — start: *{s['start_stage'].replace('_', ' ')}* ({s['reason']})" for i, s in enumerate(plan["steps"], 1)] if plan["retrieval_only"]: lines.append("Already solid (straight to mixed retrieval review): " + ", ".join(TOPIC_BY_ID[t].title for t in plan["retrieval_only"])) return "\n\n".join(lines), _progress_rows(learner_id), gr.Button(visible=False) # ============================================================================ 2 · worked examples _STAGES = [("explain", "Worked example"), ("faded", "Finish the half"), ("full", "Solve it yourself"), ("transfer", "Transfer check"), ("mastered", "Mastered")] def _stage_bar(stage: str | None, topic_title: str = "") -> str: order = [s for s, _ in _STAGES] cur = order.index(stage) if stage in order else -1 chips = "".join( f'
' f'{"✓" if i < cur else i + 1}{label}
' for i, (_, label) in enumerate(_STAGES)) title = f'
{topic_title}
' if topic_title else "" return f'
{title}
{chips}
' def _render_tutor(tut: WorkedExampleTutor): v = tut.current() md = [] if v["stage"] == "explain": md += ["### 💡 The idea", v.get("concept_overview", ""), "**Key ideas**\n" + "\n".join(f"- {k}" for k in v.get("key_ideas", [])), f"### 📝 Worked example\n{v['problem']}"] md += [f"**Step {i}.** {s}\n\n> {n}" for i, (s, n) in enumerate(zip(v["steps"], v["step_notes"]), 1)] md += [f"**Answer:** {v['answer']}", f"Steps source: {v['steps_source']}", "---\nWhen it makes sense, press **I understand**. I'll cut the example in half and you finish it."] elif v["stage"] == "faded": md += [f"### 📝 {v['problem']}"] + [f"**Step {i}.** {s}" for i, s in enumerate(v["shown_steps"], 1)] md += [f"*…{v['remaining']} step(s) left for you.*", f"---\n✍️ {v['prompt']}"] elif v["stage"] in ("full", "transfer"): if v.get("progress"): md.append(f"**Question {v['progress']}**") md += [f"### 📝 {v['problem']}", f"---\n✍️ {v['prompt']}"] else: md += ["### 🎉 Topic mastered", "It's now part of your mixed retrieval review. Start another topic, " "or head to **Retrieval quiz**."] return (_stage_bar(v["stage"], v["topic_title"]), "\n\n".join(md), _imgs(v.get("image_paths")), gr.Button(visible=v["stage"] == "explain"), gr.Button(visible=v["stage"] in ("faded", "full", "transfer"))) def start_tutor(learner_id, topic): try: tut = WorkedExampleTutor(_lid(learner_id), None if topic == AUTO else topic) except (AssessmentRequired, ValueError) as e: return (None, _stage_bar(None), f"⚠️ {e}", gr.Gallery(visible=False), gr.Button(visible=False), gr.Button(visible=False), "") return (tut, *_render_tutor(tut), "") def tutor_understood(tut): tut.understood() return (tut, *_render_tutor(tut), "") def tutor_submit(tut, img, txt): if tut is None: return (None, _stage_bar(None), "Start a session first.", gr.Gallery(visible=False), gr.Button(), gr.Button(), "", None, "") try: work = _read(img, txt) ev = tut.submit(work) except LLMUnavailable as e: return (tut, *_render_tutor(tut), f"⚠️ Model unavailable, try again: {e}", img, txt) fb = format_feedback(ev, show_key=ev.get("reveal_answer")) if ev.get("reveal_steps"): fb += "\n\n**How the example finishes:**\n\n" + "\n\n".join(ev["reveal_steps"]) fb += f"\n\n➡️ {ev.get('next', '')}" if img: fb = f"**Read as:**\n\n{work}\n\n---\n\n{fb}" return (tut, *_render_tutor(tut), fb, None, "") # ============================================================================ 3 · retrieval quiz def _quiz_item(quiz, idx): it = quiz["items"][idx] tag = {"free_recall": "🧠 free recall"}.get(it["kind"], "🔁 review" if it["is_review"] else "🆕 current topic") mode = "✍️ work it on paper, upload a photo" if it.get("response_mode", "handwritten") == "handwritten" \ else "🔤 pick a letter" header = (f"**Item {it['n']} / {len(quiz['items'])}** · {tag} · *{it['topic_title']}* · {mode} \n" f"why: {it['why']}") body = it["statement"] if it.get("options"): body += "\n\n" + "\n".join(f"- **{o['letter']}.** {o['value']}" for o in it["options"]) return header, body, _imgs(it.get("image_paths")) def start_quiz(learner_id, topic, n_items): try: quiz = build_quiz(_lid(learner_id), topic, int(n_items)) except AssessmentRequired as e: return None, f"⚠️ {e}", "", "", gr.Gallery(visible=False), "", gr.Row(visible=False), _progress_rows(learner_id) comp = ", ".join(f"{k}: {v}" for k, v in quiz["composition"].items()) info = (f"**Quiz {quiz['quiz_id']}** — {len(quiz['topics_covered'])} topic(s) covered · review share " f"{quiz['review_fraction']:.0%} · {comp}") return ({"quiz": quiz, "idx": 0, "results": []}, info, *_quiz_item(quiz, 0), "", gr.Row(visible=False), _progress_rows(learner_id)) def check_quiz(state, img, txt): if not state: return state, "Build a quiz first.", gr.Row(visible=False) it = state["quiz"]["items"][state["idx"]] try: work = _read(img, txt) except LLMUnavailable as e: return state, f"⚠️ {e}", gr.Row(visible=False) if it["kind"] == "free_recall": fb = (f"Compare what you wrote with OpenStax §{', §'.join(it['textbook_sections'])}. " "Did you recall the key definitions, formulas and how to recognize this kind of problem?") return state, fb, gr.Row(visible=True) if it["answer_format"] == "multiple_choice": verdict = grade(it, work) ev = {"verdict": "correct" if verdict else "incorrect", "answer_correct": verdict} else: try: ev = evaluate_work(it["statement"], it["answer_key"], work, mode="answer_only", answer_format=it["answer_format"], reveal_answer=True) verdict = ev["answer_correct"] except LLMUnavailable: verdict, ev = grade(it, work), {} fb = format_feedback(ev) if ev.get("verdict") else "" fb += f"\n\n**Answer key:** {it['answer_key']}" if it.get("solution"): fb += f"\n\n
Worked solution\n\n{it['solution']}\n\n
" fb += f"\n\n📖 Restudy: OpenStax Precalculus 2e §{', §'.join(it['textbook_sections'])}" if img: fb = f"**Read as:**\n\n{work}\n\n---\n\n{fb}" if verdict is not None: state["results"] = [r for r in state["results"] if r["n"] != it["n"]] + [{"n": it["n"], "correct": verdict}] return state, fb, gr.Row(visible=verdict is None) def self_mark(state, correct): it = state["quiz"]["items"][state["idx"]] state["results"] = [r for r in state["results"] if r["n"] != it["n"]] + [{"n": it["n"], "correct": correct}] return state, gr.Row(visible=False) def next_quiz(learner_id, state): if not state: return state, "", "", gr.Gallery(visible=False), "", None, "", [] quiz = state["quiz"] if state["idx"] + 1 >= len(quiz["items"]): out = record_quiz_results(quiz["learner_id"], quiz["quiz_id"], state["results"]) done = ", ".join(f"{t}: {'relearned ✅' if ok else 'back to 1-day interval 🔁'}" for t, ok in out.items()) return (state, "### 🎉 Quiz complete", f"Schedule updated — {done or 'no graded items'}", gr.Gallery(visible=False), "", None, "", _progress_rows(learner_id)) state["idx"] += 1 return (state, *_quiz_item(quiz, state["idx"]), "", None, "", _progress_rows(learner_id)) # ============================================================================ 4 · peer instruction def new_peer(learner_id, topic): try: s = PeerInstructionSession(_lid(learner_id), None if topic == AUTO else topic) except ValueError as e: return None, f"⚠️ {e}", gr.Gallery(visible=False), "" p = s.prompt() return s, f"## {p['topic_title']}\n\n{p['problem']}\n\n*{p['instructions']}*", _imgs(p["image_paths"]), "" def submit_peer(sess, img, txt, conf): if sess is None: return sess, "Get a problem first.", None, "" if sess.finished: return sess, "This one's finished — press **New problem**.", None, "" try: work = _read(img, txt) ev = sess.submit(work, int(conf)) except LLMUnavailable as e: return sess, f"⚠️ {e}", img, txt fb = format_feedback(ev) if ev.get("calibration"): fb += f"\n\n{ev['calibration']}" if ev.get("reveal"): fb += f"\n\n---\n**Answer key:** {ev['reveal']['answer_key']}" if ev["reveal"].get("solution"): fb += f"\n\n
Reference solution\n\n{ev['reveal']['solution']}\n\n
" elif ev.get("next"): fb += f"\n\n➡️ {ev['next']}" if img: fb = f"**Read as:**\n\n{work}\n\n---\n\n{fb}" return sess, fb, None, "" # ============================================================================ UI THEME = gr.themes.Soft( primary_hue="indigo", secondary_hue="teal", neutral_hue="slate", radius_size="lg", font=[gr.themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui", "sans-serif"], font_mono=[gr.themes.GoogleFont("JetBrains Mono"), "ui-monospace", "monospace"], ).set( body_background_fill="*neutral_50", body_background_fill_dark="*neutral_950", block_shadow="0 1px 2px rgba(15, 23, 42, .06), 0 4px 16px rgba(15, 23, 42, .04)", block_border_width="1px", block_title_text_weight="600", button_large_radius="*radius_lg", button_primary_background_fill="linear-gradient(135deg, *primary_500, *primary_600)", button_primary_background_fill_hover="linear-gradient(135deg, *primary_600, *primary_700)", button_primary_text_color="white", input_background_fill="*neutral_50", ) CSS = """ .gradio-container { max-width: 1180px !important; margin: 0 auto !important; } footer { display: none !important; } /* ---------- hero ---------- */ .hero { padding: 28px 30px 22px; border-radius: 20px; color: #fff; background: radial-gradient(1200px 300px at 0% 0%, rgba(255,255,255,.18), transparent 60%), linear-gradient(135deg, #4338ca 0%, #6366f1 45%, #0d9488 100%); box-shadow: 0 10px 30px rgba(67, 56, 202, .25); margin-bottom: 6px; } .hero, .hero * { color: #fff !important; } .hero .journey .num { color: #4338ca !important; } .hero h1 { margin: 0 0 4px; font-size: 1.9rem; font-weight: 750; letter-spacing: -.02em; color: #fff; } .hero p { margin: 0; opacity: .92; font-size: 1rem; } .journey { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 16px; } .journey .step { display: flex; align-items: center; gap: 8px; padding: 6px 12px 6px 6px; border-radius: 999px; background: rgba(255,255,255,.14); border: 1px solid rgba(255,255,255,.25); font-size: .86rem; font-weight: 500; backdrop-filter: blur(4px); } .journey .num { width: 22px; height: 22px; border-radius: 50%; background: #fff; color: #4338ca; display: grid; place-items: center; font-weight: 700; font-size: .78rem; } .journey .arrow { opacity: .6; align-self: center; } /* ---------- learner bar ---------- */ .learner-bar { align-items: end !important; } .learner-bar .hint { font-size: .85rem; opacity: .75; padding-bottom: 10px; } /* ---------- tabs ---------- */ .tabs > .tab-wrapper button, button[role="tab"] { font-weight: 600 !important; font-size: .95rem !important; } /* ---------- cards ---------- */ .intro { font-size: .95rem; opacity: .85; margin: 2px 0 6px; } .card { border-radius: 16px !important; padding: 18px 20px !important; background: var(--block-background-fill) !important; border: 1px solid var(--block-border-color) !important; } .problem-card { border-left: 4px solid var(--color-accent) !important; min-height: 120px; } .problem-card h3 { margin-top: .2em; } .problem-card blockquote { margin: .4em 0 1em; padding: .55em .9em; border-radius: 10px; border-left: 3px solid #14b8a6; background: rgba(20, 184, 166, .08); font-size: .92rem; } .feedback-card:not(:has(.md *)) { display: none !important; } /* hide until there's feedback */ .problem-card .block, .problem-card .form, .problem-card > div { border: none !important; box-shadow: none !important; background: transparent !important; } .placeholder { opacity: .6; font-style: italic; } .feedback-card { border-left: 4px solid #14b8a6 !important; } .answer-panel { border-radius: 16px !important; } .answer-panel .label-wrap span, .answer-panel label span { font-weight: 600; } /* ---------- worked-example stage tracker ---------- */ .stagebar-wrap { padding: 4px 2px 2px; } .stage-topic { font-weight: 700; font-size: 1.15rem; margin-bottom: 10px; } .stagebar { display: flex; gap: 6px; flex-wrap: wrap; } .stagebar .stage { display: flex; align-items: center; gap: 8px; padding: 6px 12px 6px 6px; border-radius: 999px; border: 1px solid var(--block-border-color); font-size: .84rem; opacity: .6; } .stagebar .dot { width: 22px; height: 22px; border-radius: 50%; display: grid; place-items: center; font-size: .75rem; font-weight: 700; background: var(--neutral-200); color: var(--neutral-700); } .stagebar .stage.active { opacity: 1; border-color: var(--color-accent); background: rgba(99, 102, 241, .08); font-weight: 600; } .stagebar .stage.active .dot { background: var(--color-accent); color: #fff; } .stagebar .stage.done { opacity: .9; } .stagebar .stage.done .dot { background: #14b8a6; color: #fff; } /* ---------- misc ---------- */ .primary-cta { min-height: 46px; } .choice-row button { min-height: 52px; font-size: 1rem !important; } @media (max-width: 720px) { .hero { padding: 20px; } .hero h1 { font-size: 1.45rem; } .journey .arrow { display: none; } } """ HERO = """

📐 Ed-Tech Studio

Learn by doing: work on paper, snap a photo, and get feedback on your reasoning, not just your answer.

1Placement
→
2Worked examples
→
3Retrieval quizzes
·
4Peer instruction
·
5Perceptual drills
""" def _answer_panel(button_label="Submit"): """Photo + typed answer, side panel. Returns (img, txt, submit_button).""" with gr.Column(scale=5, elem_classes="answer-panel"): gr.Markdown("#### ✍️ Your work") img = gr.Image(type="filepath", sources=["upload", "webcam", "clipboard"], label="Photo of your paper work", height=230) txt = gr.Textbox(label="…or type it (steps + the idea behind each)", lines=5, placeholder="Step 1: … because …") btn = gr.Button(button_label, variant="primary", elem_classes="primary-cta") return img, txt, btn with gr.Blocks(title="Ed-Tech Studio") as demo: gr.HTML(HERO) with gr.Row(elem_classes="learner-bar"): learner = gr.Textbox(value="demo", label="Learner id", max_lines=1, scale=2) gr.Markdown('
Use the same id across tabs; your progress, schedule and plan are saved ' 'under it. Start with Placement: quizzes unlock after it.
') # ------------------------------------------------------------------ 1 · placement with gr.Tab("① Placement"): gr.Markdown("One problem per topic. Show your steps and the idea behind each. Type *I don't know yet* " "for anything you haven't learned; that's useful, not a failure.", elem_classes="intro") a_state = gr.State(None) a_start = gr.Button("Start placement assessment", variant="primary", elem_classes="primary-cta") a_info = gr.Markdown() with gr.Row(equal_height=False): with gr.Column(scale=7): with gr.Group(elem_classes="card problem-card"): a_head = gr.Markdown('

Press Start placement assessment to get your first problem.

') a_body = gr.Markdown(latex_delimiters=LATEX) a_gal = gr.Gallery(visible=False, height=240, show_label=False) a_fb = gr.Markdown(latex_delimiters=LATEX, elem_classes="card feedback-card") with gr.Row(): a_next = gr.Button("Next problem →", visible=False) a_finish = gr.Button("Finish & send to the Research Agent ✓", visible=False, variant="primary") a_img, a_txt, a_submit = _answer_panel("Submit answer") a_result = gr.Markdown(latex_delimiters=LATEX, elem_classes="card feedback-card") with gr.Accordion("My topic levels", open=False): a_prog = gr.Dataframe(interactive=False) a_start.click(start_assessment, [learner], [a_state, a_info, a_head, a_body, a_gal, a_fb, a_img, a_txt, a_next, a_finish]) a_submit.click(submit_assessment, [learner, a_state, a_img, a_txt], [a_fb, a_next, a_finish]) a_next.click(next_assessment, [learner, a_state], [a_state, a_head, a_body, a_gal, a_fb, a_img, a_txt, a_next]) a_finish.click(finish_assessment, [learner, a_state], [a_result, a_prog, a_finish]) # ------------------------------------------------------------------ 2 · worked examples with gr.Tab("② Worked examples"): gr.Markdown("The Research Agent teaches with worked examples: study one, finish a half-worked one, solve " "one yourself, then pass a short transfer quiz in new contexts.", elem_classes="intro") w_state = gr.State(None) with gr.Row(equal_height=True): w_topic = gr.Dropdown(choices=[("Next topic in my plan", AUTO)] + TOPIC_CHOICES, value=AUTO, label="Topic", scale=4) w_start = gr.Button("Start session", variant="primary", scale=1, elem_classes="primary-cta") w_bar = gr.HTML(_stage_bar(None)) with gr.Row(equal_height=False): with gr.Column(scale=7): with gr.Group(elem_classes="card problem-card"): w_view = gr.Markdown('

Pick a topic (or keep \"Next topic in my plan\") and press Start session.

', latex_delimiters=LATEX) w_gal = gr.Gallery(visible=False, height=240, show_label=False) w_und = gr.Button("I understand — cut it in half ✂️", visible=False, variant="primary", elem_classes="primary-cta") w_fb = gr.Markdown(latex_delimiters=LATEX, elem_classes="card feedback-card") w_img, w_txt, w_submit = _answer_panel("Submit work + reasoning") w_outs = [w_state, w_bar, w_view, w_gal, w_und, w_submit, w_fb] w_start.click(start_tutor, [learner, w_topic], w_outs) w_und.click(tutor_understood, [w_state], w_outs) w_submit.click(tutor_submit, [w_state, w_img, w_txt], w_outs + [w_img, w_txt]) # ------------------------------------------------------------------ 3 · retrieval quiz with gr.Tab("③ Retrieval quiz"): gr.Markdown("Free recall first, then mostly handwritten problems. Earlier topics get mixed in as you cover " "more. Answer keys come from the datasets.", elem_classes="intro") with gr.Row(equal_height=True): q_topic = gr.Dropdown(choices=TOPIC_CHOICES, value=TOPICS[0].id, label="Topic just studied", scale=4) q_n = gr.Slider(4, 15, value=QUIZ_DEFAULT_ITEMS, step=1, label="Problems", scale=2) q_start = gr.Button("Build quiz", variant="primary", scale=1, elem_classes="primary-cta") q_state = gr.State(None) q_info = gr.Markdown() with gr.Row(equal_height=False): with gr.Column(scale=7): with gr.Group(elem_classes="card problem-card"): q_head = gr.Markdown('

Choose the topic you just studied and press Build quiz.

') q_body = gr.Markdown(latex_delimiters=LATEX) q_gal = gr.Gallery(visible=False, height=240, show_label=False) q_fb = gr.Markdown(latex_delimiters=LATEX, elem_classes="card feedback-card") with gr.Row(visible=False) as q_self: q_right = gr.Button("I got it ✅") q_wrong = gr.Button("I missed it ❌") q_next = gr.Button("Next item →") q_img, q_txt, q_check = _answer_panel("Check answer") with gr.Accordion("My schedule & progress", open=False): q_prog = gr.Dataframe(interactive=False) q_start.click(start_quiz, [learner, q_topic, q_n], [q_state, q_info, q_head, q_body, q_gal, q_fb, q_self, q_prog]) q_check.click(check_quiz, [q_state, q_img, q_txt], [q_state, q_fb, q_self]) q_right.click(lambda s: self_mark(s, True), [q_state], [q_state, q_self]) q_wrong.click(lambda s: self_mark(s, False), [q_state], [q_state, q_self]) q_next.click(next_quiz, [learner, q_state], [q_state, q_head, q_body, q_gal, q_fb, q_img, q_txt, q_prog]) # ------------------------------------------------------------------ 4 · peer instruction with gr.Tab("④ Peer instruction"): gr.Markdown("Solve it, explain your reasoning, rate your confidence. I'll answer like a peer: why you're " "right, or exactly where the reasoning breaks. You get one revision before I show the solution.", elem_classes="intro") p_state = gr.State(None) with gr.Row(equal_height=True): p_topic = gr.Dropdown(choices=[("Auto: my weakest covered topic", AUTO)] + TOPIC_CHOICES, value=AUTO, label="Topic", scale=4) p_new = gr.Button("New problem", variant="primary", scale=1, elem_classes="primary-cta") with gr.Row(equal_height=False): with gr.Column(scale=7): with gr.Group(elem_classes="card problem-card"): p_view = gr.Markdown('

Press New problem to get a problem from your peer.

', latex_delimiters=LATEX) p_gal = gr.Gallery(visible=False, height=240, show_label=False) p_fb = gr.Markdown(latex_delimiters=LATEX, elem_classes="card feedback-card") with gr.Column(scale=5, elem_classes="answer-panel"): gr.Markdown("#### ✍️ Your answer + reasoning") p_img = gr.Image(type="filepath", sources=["upload", "webcam", "clipboard"], label="Photo of your paper work", height=230) p_txt = gr.Textbox(label="…or type it", lines=5, placeholder="My answer is … because …") p_conf = gr.Slider(1, 5, value=3, step=1, label="How confident are you? (1 guessing · 5 certain)") p_submit = gr.Button("Submit to my peer", variant="primary", elem_classes="primary-cta") p_new.click(new_peer, [learner, p_topic], [p_state, p_view, p_gal, p_fb]) p_submit.click(submit_peer, [p_state, p_img, p_txt, p_conf], [p_state, p_fb, p_img, p_txt]) # ------------------------------------------------------------------ 5 · PLM drill with gr.Tab("⑤ Perceptual drill"): gr.Markdown("**GraphSense**: name the function family from its graph. **ConicSense**: name the conic " "from its equation. Answer fast; a category retires after 4 quick correct answers.", elem_classes="intro") MAX_CHOICES = max(len(c["choices"]) for c in precalc.CATEGORIES.values()) tracker_s, item_s, t0_s = gr.State(None), gr.State(None), gr.State(None) def _new_session(): return ArtsTracker([CategoryState(name=n, rt_threshold_s=s["rt_threshold_s"]) for n, s in precalc.CATEGORIES.items()]) def next_trial(tracker): tracker = tracker or _new_session() if tracker.all_retired() and tracker.trial > 0: return (tracker, None, gr.Image(visible=False), "### 🎉 All categories retired!", *[gr.Button(visible=False)] * MAX_CHOICES, tracker.summary(), None) item = precalc.make_item(tracker.next_category()) btns = [gr.Button(value=item["choices"][i], visible=True) if i < len(item["choices"]) else gr.Button(visible=False) for i in range(MAX_CHOICES)] return (tracker, item, gr.Image(value=item["stimulus"]["image"], visible=True), f"### {item['prompt']}", *btns, tracker.summary(), time.time()) def answer_trial(idx, tracker, item, t0): if item is None or t0 is None: return tracker, "Press **Next trial**.", tracker.summary() if tracker else [] rt = time.time() - t0 ok = idx == item["correct"] tracker.record(item["subcategory"], ok, rt) thr = precalc.CATEGORIES[item["subcategory"]]["rt_threshold_s"] v = "✅ **Correct**" if ok else f"❌ **Incorrect**: *{item['choices'][item['correct']]}*" return tracker, f"{v} · {rt:.1f}s ({'⚡ fluent' if rt < thr else '🐢 take it faster'})\n\n{item['feedback']}", \ tracker.summary() with gr.Row(equal_height=False): with gr.Column(scale=7): with gr.Group(elem_classes="card problem-card"): d_prompt = gr.Markdown("Press **Next trial** to begin.") d_img = gr.Image(visible=False, show_label=False, type="pil", height=360) with gr.Row(elem_classes="choice-row"): d_btns = [gr.Button(visible=False) for _ in range(MAX_CHOICES)] d_fb = gr.Markdown(elem_classes="card feedback-card") d_next = gr.Button("Next trial →", variant="primary", elem_classes="primary-cta") with gr.Column(scale=5): gr.Markdown("#### Session progress") d_stats = gr.Dataframe(interactive=False) d_outs = [tracker_s, item_s, d_img, d_prompt, *d_btns, d_stats, t0_s] d_next.click(next_trial, [tracker_s], d_outs).then(lambda: "", None, d_fb) for i, b in enumerate(d_btns): b.click(lambda tr, it, t0, i=i: answer_trial(i, tr, it, t0), [tracker_s, item_s, t0_s], [tracker_s, d_fb, d_stats]) # ------------------------------------------------------------------ 6 · agent debug with gr.Tab("⚙ Agent debug"): gr.Markdown("Runs the real smolagents CodeAgents (30–60 s). Inputs are fixed dropdowns on purpose.", elem_classes="intro") _agents: dict = {} def _agent(kind): if kind not in _agents: if kind == "retrieval": from src.edtech_core.retrieval import build_retrieval_agent _agents[kind] = build_retrieval_agent() elif kind == "coordinator": from src.edtech_core.research import build_research_coordinator _agents[kind] = build_research_coordinator() else: from src.edtech_core.plm_agent import build_plm_agent _agents[kind] = build_plm_agent() return _agents[kind] def _trace(agent): return "\n\n".join(f"--- step {s.step_number} ---\n{s.code_action}" for s in agent.memory.steps if isinstance(s, ActionStep) and s.code_action) or "(no steps captured)" def run_agent(kind, learner_id, topic): agent = _agent(kind) task = { "retrieval": f"Learner '{_lid(learner_id)}' just studied topic id '{topic}'. Give them what they need next " "(placement assessment if not assessed, otherwise a retrieval-practice quiz).", "coordinator": f"Learner '{_lid(learner_id)}' has mastered the worked examples for topic id '{topic}'. " "Ask the retrieval_agent to build a transfer quiz (build_transfer_quiz) for them and " "return the quiz_id.", "plm": "Generate one item for concept 'conic_type' with the sanctioned tool; report image_path and " "correct_answer.", }[kind] out = agent.run(task, reset=True) return json.dumps(out, indent=2, default=str), _trace(agent) with gr.Row(equal_height=True): g_kind = gr.Dropdown(choices=[("Retrieval Agent", "retrieval"), ("Research coordinator → Retrieval Agent (transfer quiz)", "coordinator"), ("PLM Agent", "plm")], value="retrieval", label="Agent", scale=3) g_topic = gr.Dropdown(choices=TOPIC_CHOICES, value="circles", label="Topic", scale=3) g_run = gr.Button("Run agent", variant="primary", scale=1) with gr.Row(): g_out = gr.Code(label="Final answer", language="json") g_trace = gr.Code(label="Agent code trace", language="python") g_run.click(run_agent, [g_kind, learner, g_topic], [g_out, g_trace]) if __name__ == "__main__": demo.launch(theme=THEME, css=CSS)