"""Research Agent — web research, cached; two jobs: 1. `get_concept_brief(topic_id)` — a precalculus concept brief (key facts, common misconceptions, canonical examples, prerequisites) used to word feedback and study tips. The textbook stays ground truth: the agent is *given* the relevant OpenStax passages and must list any web-vs-textbook disagreement instead of silently picking one. 2. `get_learning_science_brief(question)` — an evidence brief on a pedagogy question (e.g. "how much interleaving is optimal for math practice?") with findings, effect sizes and citations. These briefs are how the quiz policy in src/config.py is revisited as evidence accumulates; they never change it automatically. Never a source of answer keys. Runs once per topic/question and caches to disk. Fixes vs v2: - DuckDuckGoSearchTool needs the `ddgs` package (v2's requirements pinned the deprecated `duckduckgo-search`, so the tool failed to import on a clean install). - The "flag disagreements with the textbook" rule was unenforceable — the agent never saw the textbook. It now receives the top textbook passages for the topic. - Output schema is enforced with `final_answer_checks`, so a malformed brief makes the agent retry instead of being cached; `max_steps` bounds cost. - Cache paths are absolute (config.RESEARCH_CACHE_DIR), not cwd-relative. """ from __future__ import annotations import json import re from smolagents import CodeAgent, DuckDuckGoSearchTool, VisitWebpageTool from src.config import make_llm, COURSE_NAME, RESEARCH_AGENT_MODEL, RESEARCH_CACHE_DIR from src.edtech_core.curriculum import TOPIC_BY_ID CONCEPT_KEYS = ("key_facts", "misconceptions", "canonical_examples", "prerequisites", "disagreements", "sources") EVIDENCE_KEYS = ("question", "findings", "recommendations", "caveats", "sources") EVIDENCE_HINT = ( "Prefer peer-reviewed meta-analyses and reviews and government evidence clearinghouses (e.g. IES What Works " "Clearinghouse, APA/APS journals, Springer/Educational Psychology Review, PubMed Central) and well-known " "researcher sites (learningscientists.org, retrievalpractice.org). Avoid vendor marketing and forums." ) def _slug(text: str) -> str: return re.sub(r"[^a-z0-9]+", "_", text.lower()).strip("_")[:80] def _schema_check(keys: tuple[str, ...]): def check_schema(final_answer, memory, agent=None) -> bool: if not isinstance(final_answer, dict): raise ValueError("final_answer must be a dict") missing = [k for k in keys if k not in final_answer] if missing: raise ValueError(f"final_answer is missing keys {missing}") if not final_answer.get("sources"): raise ValueError("'sources' must list the URLs you actually visited") return True return check_schema def build_research_agent(keys: tuple[str, ...] = CONCEPT_KEYS, max_steps: int = 8) -> CodeAgent: return CodeAgent( tools=[DuckDuckGoSearchTool(max_results=6), VisitWebpageTool(max_output_length=12000)], model=make_llm(RESEARCH_AGENT_MODEL), final_answer_checks=[_schema_check(keys)], max_steps=max_steps, name="research_agent", description=("Researches a precalculus concept or a learning-science question on the web and returns a " "concise, cited, cached brief. Never a source of answer keys."), ) def _cached(path, build): if path.exists(): return json.loads(path.read_text()) brief = build() if not isinstance(brief, dict): raise RuntimeError(f"Research Agent returned a non-dict final answer: {brief!r}") path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(brief, indent=2, ensure_ascii=False)) return brief def get_concept_brief(topic_id: str, force_refresh: bool = False) -> dict: topic = TOPIC_BY_ID[topic_id] path = RESEARCH_CACHE_DIR / "concepts" / f"{topic_id}.json" if force_refresh and path.exists(): path.unlink() def build(): try: # textbook passages so disagreements can actually be detected from src.edtech_core.retrieval import retrieve_textbook_context passages = retrieve_textbook_context(topic.title, topic=topic_id, k=3) except Exception: passages = [] textbook = "\n\n".join(f"[§{p['section']} p.{p['page']}] {p['text'][:800]}" for p in passages) or "(none)" brief = build_research_agent(CONCEPT_KEYS).run( f"Research the {COURSE_NAME} topic '{topic.title}' (OpenStax Precalculus 2e sections " f"{', '.join(topic.sections)}). Search the web and visit 2-3 reputable educational pages. " f"{EVIDENCE_HINT}\n\nTextbook passages (ground truth):\n{textbook}\n\n" "Call final_answer with a dict with exactly these keys: " "'key_facts' (3-5 short strings), 'misconceptions' (2-4 common student errors, each with how to spot it), " "'canonical_examples' (1-2 short example descriptions), 'prerequisites' (topics a learner must already " "know), 'disagreements' (strings noting any place a web source conflicts with the textbook passages; " "[] if none), 'sources' (URLs you actually visited). Bullets, not paragraphs." ) return {"topic": topic_id, "title": topic.title, **brief} if isinstance(brief, dict) else brief return _cached(path, build) def get_learning_science_brief(question: str, force_refresh: bool = False) -> dict: path = RESEARCH_CACHE_DIR / "learning_science" / f"{_slug(question)}.json" if force_refresh and path.exists(): path.unlink() def build(): return build_research_agent(EVIDENCE_KEYS, max_steps=10).run( f"Learning-science question: {question}\n{EVIDENCE_HINT}\n" "Search, then visit 2-4 of the strongest sources. Call final_answer with a dict with exactly these keys: " "'question' (the question), 'findings' (list of dicts with 'claim', 'evidence' (study/meta-analysis, " "year, population, effect size if reported) and 'source' (URL)), 'recommendations' (concrete, " "actionable rules for designing math retrieval-practice quizzes), 'caveats' (limits, boundary " "conditions, conflicting results), 'sources' (URLs you actually visited). Do not invent effect sizes — " "omit them if the page doesn't state one." ) return _cached(path, build) # ============================================================================ tutoring role # The Research Agent also owns *teaching* with worked examples (src/edtech_core/worked_examples.py). # It receives the placement assessment from the Retrieval Agent's flow and turns it into a plan. # worked example + full problem + transfer quiz need several distinct problems on the topic MIN_TUTORING_PROBLEMS = 6 START_STAGE = {"gap": "worked_example", "partial": "faded", "unknown": "worked_example"} def receive_assessment(learner_id: str) -> dict: """Handoff target for the placement assessment. Builds the learning plan: topics in textbook order that need teaching, each with a starting stage chosen by level (expertise reversal: 'partial' skips the full worked example; 'solid' topics go straight to retrieval practice).""" from datetime import datetime, timezone from src.edtech_core.curriculum import TOPICS from src.edtech_core.learner_model import LearnerState from src.edtech_core.llm import LLMUnavailable, chat from src.edtech_core.worked_examples import _candidate_problems state = LearnerState.load(learner_id) levels = (state.assessment or {}).get("levels", {}) steps, retrieval_only, no_material = [], [], [] for t in TOPICS: level = levels.get(t.id, "unknown") if level == "solid": retrieval_only.append(t.id) elif len(_candidate_problems(t.id, set())) >= MIN_TUTORING_PROBLEMS: steps.append({"topic": t.id, "title": t.title, "level": level, "start_stage": START_STAGE[level], "reason": {"gap": "not yet learned → full worked example first", "partial": "some knowledge → start from a half-worked (faded) example", "unknown": "not assessed → full worked example first"}[level]}) else: no_material.append(t.id) try: summary = chat( "You are a warm, concise precalculus tutor. 4-6 sentences, no lists.", f"Placement results by topic: {json.dumps(levels)}. Plan (in order): " f"{[s['title'] + ' (' + s['start_stage'] + ')' for s in steps[:6]]}. Topics already solid: " f"{retrieval_only}. Explain to the learner where they are, what we'll do first and why worked " "examples then problems, and that solid topics will appear in mixed review quizzes.", max_tokens=1200) except LLMUnavailable: summary = "" plan = {"created": datetime.now(timezone.utc).isoformat(timespec="seconds"), "steps": steps, "retrieval_only": retrieval_only, "no_bank_material": no_material, "summary": summary, "source": "research_agent.receive_assessment"} state.learning_plan = plan state.save() return plan def build_research_coordinator(max_steps: int = 6) -> CodeAgent: """Agentic version of the hand-off: a Research CodeAgent that manages the Retrieval Agent and can ask it (in natural language) for a transfer quiz once a learner has mastered a worked example. The interactive tutor uses the same retrieval tool directly for latency (see worked_examples.py).""" from src.edtech_core.retrieval import build_retrieval_agent return CodeAgent( tools=[], model=make_llm(RESEARCH_AGENT_MODEL), managed_agents=[build_retrieval_agent()], max_steps=max_steps, name="research_coordinator", description="Research/tutoring agent that delegates quiz generation to the Retrieval Agent.", )