"""Retrieval Agent — builds retrieval-practice quizzes that interleave more as more precalculus is covered, grounded on the textbook and the HF problem banks. Task change vs v2: v2's Retrieval Agent only answered "what does the textbook say about X" for the PLM Agent. Now its job is *retrieval practice* (in the learning-science sense): it turns a learner's coverage + memory state into a quiz via deterministic tools, and uses textbook search only to ground the explanation/feedback it gives around that quiz. Fixes vs v2: - Chunks/problems are tagged by section + curriculum topic, so search can be filtered to a topic instead of returning whatever page happens to be nearest. - Distances are returned and weak matches dropped (v2 returned top-k no matter how bad). - Collections are created with cosine space (bge-m3 vectors are normalized for cosine). - Explicit agent `instructions` + `max_steps`, and the agent never sees or writes answer keys (they stay in the persisted quiz file; the agent passes around `quiz_id`). - Paths are absolute (config.PROJECT_ROOT), not cwd-relative. """ from __future__ import annotations import json import time import chromadb from smolagents import CodeAgent, Tool from src.config import make_llm, CHROMA_COLLECTIONS, CHROMA_PATH, QUIZ_DEFAULT_ITEMS, RETRIEVAL_AGENT_MODEL, TRANSFER_QUIZ_ITEMS from src.edtech_core.curriculum import TOPIC_BY_ID, topic_catalog from src.edtech_core.embeddings import embed_query from src.edtech_core.learner_model import LearnerState from src.edtech_core.quiz import build_quiz, build_transfer_quiz _client = None MAX_COSINE_DISTANCE = 0.65 # bge-m3 cosine distance; beyond this the hit is rarely on-topic def _collection(kind: str): global _client if _client is None: _client = chromadb.PersistentClient(path=CHROMA_PATH) return _client.get_collection(CHROMA_COLLECTIONS[kind]) def _query(kind: str, query: str, k: int, topic: str | None) -> dict: where = {"topic": topic} if topic else None return _collection(kind).query(query_embeddings=[embed_query(query)], n_results=k, where=where, include=["documents", "metadatas", "distances"]) def retrieve_textbook_context(query: str, topic: str | None = None, k: int = 4) -> list[dict]: """Semantic search over OpenStax Precalculus 2e, optionally restricted to a topic.""" if topic and topic not in TOPIC_BY_ID: raise ValueError(f"unknown topic {topic!r}") res = _query("textbook", query, k, topic) out = [] for doc, meta, dist in zip(res["documents"][0], res["metadatas"][0], res["distances"][0]): if dist <= MAX_COSINE_DISTANCE: out.append({"text": doc, "section": meta["section"], "section_title": meta["section_title"], "page": meta["page"], "topic": meta["topic"], "distance": round(dist, 3)}) return out def search_problem_bank(query: str, topic: str | None = None, k: int = 5) -> list[dict]: """Semantic search over the problem bank. Statements only — no answer keys.""" res = _query("problems", query, k, topic) return [{"problem_id": pid, "topic": meta["topic"], "source": meta["source"], "answer_format": meta["answer_format"], "statement": doc[:600], "distance": round(dist, 3)} for pid, doc, meta, dist in zip(res["ids"][0], res["documents"][0], res["metadatas"][0], res["distances"][0])] # ------------------------------------------------------------------------------ tools class ListTopicsTool(Tool): name = "list_precalc_topics" description = ("Lists the precalculus curriculum topics in textbook order: id, title, chapter, sections, and " "which topics are easily confused with each. Use it to map a learner's words to a topic id.") inputs = {} output_type = "array" def forward(self) -> list: return topic_catalog() class LearnerProgressTool(Tool): name = "get_learner_progress" description = ("Returns the learner's covered topics (in order) and per-topic retrieval history: attempts, " "accuracy, spaced successes, and whether the topic is due, scheduled or durable.") inputs = {"learner_id": {"type": "string", "description": "Learner id"}} output_type = "object" def forward(self, learner_id: str) -> dict: s = LearnerState.load(learner_id) return {"learner_id": learner_id, "covered": s.covered, "current_topic": s.current_topic, "topics": s.summary(), "quizzes_taken": len(s.quiz_ids), "assessed": s.assessed, "assessment_levels": (s.assessment or {}).get("levels"), "learning_plan": [st["topic"] for st in (s.learning_plan or {}).get("steps", [])]} class BuildRetrievalQuizTool(Tool): name = "build_retrieval_quiz" description = ( "The ONLY way to create a quiz. Builds and saves a retrieval-practice quiz from the problem bank: a " "free-recall prompt on the current topic, then problems where the share of interleaved review from " "earlier topics grows with how much the learner has covered (review topics chosen by spacing schedule, " "error rate, and confusability with the current topic). Answer keys come from the datasets and are NOT " "returned here — never write or guess answers yourself. Returns quiz_id plus an item outline." ) inputs = { "learner_id": {"type": "string", "description": "Learner id"}, "current_topic": {"type": "string", "nullable": True, "description": "Topic id just studied (from list_precalc_topics). Marks it covered. " "Omit to quiz on the learner's latest covered topic."}, "n_items": {"type": "integer", "nullable": True, "description": f"Problems (default {QUIZ_DEFAULT_ITEMS})"}, } output_type = "object" IDEMPOTENCY_WINDOW_S = 600 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._recent: dict[tuple, tuple[float, dict]] = {} def forward(self, learner_id: str, current_topic: str | None = None, n_items: int | None = None) -> dict: # CodeAgents often re-run a whole code block after an error in a later line; without # this, each retry persisted another quiz (observed in live runs). key = (learner_id, current_topic, n_items or QUIZ_DEFAULT_ITEMS) cached = self._recent.get(key) if cached and time.time() - cached[0] < self.IDEMPOTENCY_WINDOW_S: return cached[1] quiz = build_quiz(learner_id, current_topic, n_items or QUIZ_DEFAULT_ITEMS) result = { "quiz_id": quiz["quiz_id"], "current_topic": quiz["current_topic"], "topics_covered": quiz["topics_covered"], "review_fraction": quiz["review_fraction"], "composition": quiz["composition"], # Exact sections per quiz topic, so study tips cite real sections instead of guesses. "textbook_sections": {t: list(TOPIC_BY_ID[t].sections) for t in quiz["composition"]}, "outline": [{"n": it["n"], "kind": it["kind"], "topic": it["topic"], "is_review": it["is_review"], "why": it["why"], "statement_preview": it["statement"][:160]} for it in quiz["items"]], } self._recent[key] = (time.time(), result) return result class RetrieveTextbookContextTool(Tool): name = "retrieve_textbook_context" description = ("Semantic search over OpenStax Precalculus 2e. Returns passages with section number, title and " "page. Use it to ground explanations and to point learners at the exact section to restudy.") inputs = { "query": {"type": "string", "description": "Concept, term or question to look up"}, "topic": {"type": "string", "nullable": True, "description": "Optional topic id to restrict the search"}, } output_type = "array" def forward(self, query: str, topic: str | None = None) -> list: return retrieve_textbook_context(query, topic) class SearchProblemBankTool(Tool): name = "search_problem_bank" description = ("Semantic search over the precalculus problem bank (U-MATH precalculus + MathCanvas analytic " "geometry). Returns problem statements and ids, without answers.") inputs = { "query": {"type": "string", "description": "What kind of problem to find"}, "topic": {"type": "string", "nullable": True, "description": "Optional topic id filter"}, } output_type = "array" def forward(self, query: str, topic: str | None = None) -> list: return search_problem_bank(query, topic) # ------------------------------------------------------------------ assessment + transfer (new) def request_transfer_quiz(learner_id: str, topic: str, exclude_ids: list[str] | None = None, requested_by: str = "research_agent", n_items: int = TRANSFER_QUIZ_ITEMS) -> dict: """Hand-off endpoint: the Research Agent's tutor asks the Retrieval Agent for a 2-3 question transfer quiz once a learner has every concept right. Logged so the agent conversation is auditable.""" quiz = build_transfer_quiz(learner_id, topic, exclude_ids=exclude_ids, n_items=n_items) state = LearnerState.load(learner_id) log = state.quiz_dir().parent / "handoffs.jsonl" with log.open("a") as f: f.write(json.dumps({"t": quiz["created"], "from": requested_by, "to": "retrieval_agent", "request": {"kind": "transfer_quiz", "topic": topic, "n_items": n_items, "exclude": exclude_ids or []}, "response": {"quiz_id": quiz["quiz_id"], "problem_ids": [it["problem_id"] for it in quiz["items"]]}}) + "\n") return quiz class BuildAssessmentTool(Tool): name = "build_placement_assessment" description = ("Creates the learner's placement assessment (one handwritten, show-your-reasoning problem per " "assessable topic). MUST be done before any quiz for a learner who hasn't been assessed. " "Returns the assessment id and topic outline (no answer keys).") inputs = {"learner_id": {"type": "string", "description": "Learner id"}} output_type = "object" def forward(self, learner_id: str) -> dict: from src.edtech_core.assessment import build_assessment a = build_assessment(learner_id) return {"assessment_id": a["assessment_id"], "instructions": a["instructions"], "outline": [{"n": it["n"], "topic": it["topic"]} for it in a["items"]]} class TransferQuizTool(Tool): name = "build_transfer_quiz" description = ("Builds a 2-3 question handwritten quiz on ONE topic whose problems differ in context/surface from " "what the learner just practiced (transfer check against the illusion of fluency). Use when the " "Research Agent reports a learner has mastered a worked example. Answer keys are not returned.") inputs = { "learner_id": {"type": "string", "description": "Learner id"}, "topic": {"type": "string", "description": "Topic id"}, "exclude_ids": {"type": "array", "nullable": True, "description": "Problem ids already used in tutoring"}, } output_type = "object" def forward(self, learner_id: str, topic: str, exclude_ids: list | None = None) -> dict: q = request_transfer_quiz(learner_id, topic, exclude_ids, requested_by="research_coordinator(agent)") return {"quiz_id": q["quiz_id"], "topic": topic, "outline": [{"n": it["n"], "statement_preview": it["statement"][:160]} for it in q["items"]]} RETRIEVAL_AGENT_INSTRUCTIONS = """\ You are the Retrieval Agent of a precalculus learning system. Your job is retrieval practice: mostly HANDWRITTEN quizzes (learners work on paper and upload a photo) that make them pull knowledge out of memory, interleaved across topics as coverage grows. Rules: 0. Check get_learner_progress first. If `assessed` is false, create the placement assessment with build_placement_assessment and return its id — no quiz may be given before it is completed. 1. Map whatever topic the user names to an id with list_precalc_topics. If it is ambiguous, pick the closest id and say which one you used. 2. Create quizzes ONLY with build_retrieval_quiz (or build_transfer_quiz when the Research Agent asks for a transfer check), and call it exactly ONCE per request — store its result in a variable and reuse it in later steps (variables persist between steps). Never write quiz questions or answers yourself, and never state an answer key — keys live in the saved quiz file. 3. Cite ONLY section numbers that appear in tool outputs (the quiz result's `textbook_sections`, or the `section` field of retrieve_textbook_context results). Never guess a section number. 4. Final answer: a dict with keys quiz_id (or assessment_id), current_topic, review_fraction, composition, and study_tips (2-4 short strings citing section numbers; remind them to show their work by hand). """ def build_retrieval_agent(max_steps: int = 6) -> CodeAgent: """CodeAgent (not ToolCallingAgent): the HF providers serving Qwen2.5-Coder-32B reject native tools/tool_choice params, so tools are driven through generated Python instead.""" return CodeAgent( tools=[ListTopicsTool(), LearnerProgressTool(), BuildAssessmentTool(), BuildRetrievalQuizTool(), TransferQuizTool(), RetrieveTextbookContextTool(), SearchProblemBankTool()], model=make_llm(RETRIEVAL_AGENT_MODEL), instructions=RETRIEVAL_AGENT_INSTRUCTIONS, max_steps=max_steps, name="retrieval_agent", description=("Builds handwritten retrieval-practice precalculus quizzes (after a placement assessment), " "interleaving earlier topics as coverage grows, and 2-3 question transfer quizzes on request. " "Give it a learner_id and the topic (and for transfer quizzes, the problem ids to avoid)."), )