"""PLM Agent — CodeAgent that produces precalculus perceptual-learning items. Its reasoning only picks WHICH category / WHAT difficulty; every item (stimulus + answer key) comes from the deterministic sympy-backed generator in src/generators/precalc.py. `guard_ground_truth` flags steps that look like they assert an answer without calling it. """ import re from smolagents import CodeAgent, Tool from src.config import make_llm, ITEMS_DIR, PLM_AGENT_MODEL from src.edtech_core.retrieval import RetrieveTextbookContextTool from src.generators import precalc as precalc_gen def _persist_item(item: dict) -> dict: """Save the stimulus image and return the answer key (with `correct_answer` pre-resolved so generated code never does its own off-by-one-prone `choices[correct]` indexing).""" out_dir = ITEMS_DIR / "PRECALC" out_dir.mkdir(parents=True, exist_ok=True) img_path = out_dir / f"{item['id']}.png" item["stimulus"]["image"].save(img_path) answer_key = {k: v for k, v in item.items() if k != "stimulus"} answer_key["image_path"] = str(img_path) answer_key["correct_answer"] = item["choices"][item["correct"]] return answer_key class GeneratePrecalcItemTool(Tool): name = "generate_precalc_item" description = ( "The ONLY way to create a precalculus perceptual-learning item. Never decide a function family or conic " "type yourself — the item is constructed and its key verified with sympy. Read `correct_answer` from the " "result directly." ) inputs = { "concept": {"type": "string", "description": f"One of: {', '.join(precalc_gen.CATEGORIES)}"}, "difficulty": {"type": "integer", "description": "Reserved — pass 1", "nullable": True}, } output_type = "object" def forward(self, concept: str, difficulty: int | None = 1) -> dict: return _persist_item(precalc_gen.make_item(concept, difficulty=difficulty or 1)) _GUARDED_TOOLS = ("generate_precalc_item",) _ASSERTION_PATTERN = re.compile(r"\b(correct|answer_key|ground_truth|is_correct)\s*=") def guard_ground_truth(memory_step, agent) -> None: """Non-blocking first line of defense: log steps that assign answer-key-looking variables without calling the sanctioned generator.""" code = getattr(memory_step, "code_action", None) if not code: return if _ASSERTION_PATTERN.search(code) and not any(n in code for n in _GUARDED_TOOLS): agent.logger.log( f"[guard_ground_truth] step {memory_step.step_number}: code assigns an answer-like variable without " f"calling {_GUARDED_TOOLS} — verify this isn't an LLM-asserted key:\n{code}", level=1, ) def build_plm_agent() -> CodeAgent: return CodeAgent( tools=[GeneratePrecalcItemTool(), RetrieveTextbookContextTool()], model=make_llm(PLM_AGENT_MODEL), step_callbacks=[guard_ground_truth], max_steps=5, name="plm_agent", description="Generates precalculus perceptual-learning items (GraphSense, ConicSense).", )