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