Skip to content
7 changes: 6 additions & 1 deletion backend/agents/_providers.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@
SAPLING_MODEL_SUMMARY=gemini-2.5-flash-lite
SAPLING_MODEL_CONCEPTS=gemini-2.5-flash
SAPLING_MODEL_SYLLABUS=gemini-2.5-flash
SAPLING_MODEL_QUIZ=gemini-2.5-flash-lite

Defaults are tuned per task: cheaper models for simpler classifications,
flagship Flash for tasks where output quality drives downstream UX.
Expand All@@ -23,7 +24,7 @@
from config import GEMINI_API_KEY


AgentTask = Literal["classifier", "summary", "concepts", "syllabus"]
AgentTask = Literal["classifier", "summary", "concepts", "syllabus", "quiz"]


# Defaults are conservative. Bumping a model up costs more; the env var
Expand All@@ -33,6 +34,10 @@
"summary": "gemini-2.5-flash-lite",
"concepts": "gemini-2.5-flash",
"syllabus": "gemini-2.5-flash",
# Quiz generation defaults to lite: it's a single-shot non-streaming
# call where the agent pulls structured graph data via tools, so the
# bulk of the value is in tool wiring, not raw model strength.
"quiz": "gemini-2.5-flash-lite",
}


Expand Down
111 changes: 111 additions & 0 deletions backend/agents/quiz.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
"""Quiz-generation agent.

Replaces routes/quiz.py:82's call_gemini_json + manual prompt-string
augmentation. The agent has tools to pull weak concepts + class
misconceptions on demand instead of pre-stuffing them into the prompt.

Per ADR 0003 convention 4: keep the output schema compact. Gemini's
structured-output API rejects rich nested schemas with too many states
for serving — Quiz is a flat top-level model with a list of
QuizQuestion items, no further nesting.
"""

from __future__ import annotations

import hashlib
from typing import Literal

from pydantic import BaseModel, Field
from pydantic_ai import Agent

from agents._providers import model_for
from agents.deps import SaplingDeps
from agents.tools.graph_read import (
read_concepts_for_user_tool,
read_misconceptions_for_course_tool,
)


# Difficulty + question type are Literals so Gemini's enum constraint
# applies and downstream UI can branch on stable strings.
#
# `QuizQuestionType` is intentionally MCQ-only today. The frontend
# `submitQuiz` flow grades by `q["options"][i].correct` lookup — there's
# no UI for free-text answers, no fuzzy-match grading, no LLM-judged
# scoring. Generating short-answer questions through this path would
# emit unrenderable, ungradable items. Keep the type narrow until real
# short-answer support exists; revisit when that lands.
QuizDifficulty = Literal["easy", "medium", "hard"]
QuizQuestionType = Literal["multiple_choice"]


class QuizQuestion(BaseModel):
"""A single multiple-choice quiz question. Kept small so the parent
Quiz schema doesn't trip Gemini's structured-output complexity limit."""

question: str = Field(max_length=600)
type: QuizQuestionType
difficulty: QuizDifficulty
# 3-6 options. The agent is required to populate this for every
# question and to make `correct_answer` match exactly one of them.
options: list[str] = Field(min_length=3, max_length=6)
# The option text the agent considers correct. Must appear verbatim
# in `options`; the route validates this and drops questions that
# violate the contract rather than silently mis-marking them.
correct_answer: str = Field(max_length=400)
explanation: str = Field(max_length=600)
# Concept the question is testing — must be one of the user's known
# concept_names per the prompt. Used by the route to award mastery
# on a correct answer.
concept: str = Field(max_length=120)


class Quiz(BaseModel):
"""The agent's structured output."""

questions: list[QuizQuestion] = Field(min_length=1, max_length=20)


_SYSTEM_PROMPT = (
"You generate adaptive multiple-choice quizzes for a student. Each "
"question must target a specific concept the student has weak "
"mastery on, OR address a class-level misconception you've seen.\n\n"
"Workflow:\n"
"1. Call `read_concepts_for_user` to see the student's mastery per "
" concept for this course (returned sorted by mastery ASC — "
" weakest first).\n"
"2. Call `read_misconceptions_for_course` to see anonymized class "
" misconceptions. Use these to phrase distractors and to write "
" a question that probes the misconception.\n"
"3. Compose `Quiz.questions` so the WEAKEST concepts get the most "
" questions, AND each item's `concept` field exactly matches a "
" concept_name returned by tool 1.\n\n"
"Per-question rules (multiple-choice only — the type field is "
"constrained to 'multiple_choice'):\n"
"- 4 options, exactly one correct. The text in `correct_answer` "
" MUST appear verbatim in `options` — character-for-character. "
" Questions that violate this are dropped at the route layer.\n"
"- Distractors should reflect plausible misconceptions, not random "
" noise. Use the read_misconceptions_for_course return value.\n"
"- explanation: 1-3 sentences explaining WHY the correct answer "
" is correct — used in the post-quiz review screen.\n"
"- difficulty: align with the student's mastery on the concept; "
" weakest concepts get easy/medium, strongest get hard.\n\n"
"Honor the requested num_questions and difficulty distribution "
"in the user message. Don't invent concepts the student doesn't "
"have."
)
Comment on lines +69 to +97

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bashset -euo pipefail
# Confirm the exact registered tool names and whether any aliasing is applied.
rg -n --type=py 'def read_concepts_for_user_tool|def read_misconceptions_for_course_tool|read_concepts_for_user\b|read_misconceptions_for_course\b|tools=\[' backend/agents

Repository: SaplingLearn/Sapling

Length of output: 1385


🏁 Script executed:

# Check the tools registration in quiz.py
sed -n '100,130p' backend/agents/quiz.py

Repository: SaplingLearn/Sapling

Length of output: 383


🏁 Script executed:

# Also check if pydantic-ai is imported and how it handles tool names
rg -n "from pydantic_ai|import.*pydantic_ai|agent.*tools" backend/agents/quiz.py -A 2 -B 2

Repository: SaplingLearn/Sapling

Length of output: 568


🏁 Script executed:

# Check pydantic-ai documentation or examples in the codebase for tool naming
rg -n "def.*_tool\(" backend/agents --type=py -B 5 | head -40

Repository: SaplingLearn/Sapling

Length of output: 1084


🏁 Script executed:

# Check if the _tool functions have any decorators or name parameters
rg -n "@|name\s*=" backend/agents/tools/graph_read.py -B 2 -A 8 | grep -A 10 "read_concepts_for_user_tool\|read_misconceptions_for_course_tool"

Repository: SaplingLearn/Sapling

Length of output: 46


🏁 Script executed:

# Search for pydantic_ai documentation or configuration in the codebase
rg -n "pydantic_ai.*tool|Tool.*name|tool.*alias" backend --type=py | head -20

Repository: SaplingLearn/Sapling

Length of output: 46


🌐 Web query:

pydantic-ai tool naming convention function name suffix

💡 Result:

Pydantic AI does not enforce a specific function name suffix or strict naming convention for tools beyond requiring unique tool names within a toolset or agent. The tool name defaults to the Python function name (snake_case convention in examples like 'roll_dice', 'get_player_name', 'customer_balance'), but can be explicitly overridden via the 'name' parameter in decorators (@agent.tool(name='custom_name'), Tool constructor, Tool.from_schema) or toolset methods. ToolDefinition names must be unique to avoid conflicts (raises UserError on duplicates), but no suffix like '_tool' is required or conventional. Use descriptive, unique names that clearly communicate purpose, following Python snake_case for functions.

Citations:


Fix tool name mismatch between prompt and registration.

The prompt instructs the agent to call read_concepts_for_user and read_misconceptions_for_course, but the registered tools are read_concepts_for_user_tool and read_misconceptions_for_course_tool. Pydantic-ai uses the function name directly as the tool name without auto-aliasing suffixes, so the agent will fail to locate these tools when following the prompt instructions.

Either rename the functions to remove the _tool suffix or update the prompt to reference the correct tool names.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@backend/agents/quiz.py` around lines 69 - 97, The system prompt
(_SYSTEM_PROMPT) tells the agent to call read_concepts_for_user and
read_misconceptions_for_course, but the actual registered tool functions are
named read_concepts_for_user_tool and read_misconceptions_for_course_tool, so
the agent will not find the tools; fix by making the names consistent: either
rename the tool functions (read_concepts_for_user_tool -> read_concepts_for_user
and read_misconceptions_for_course_tool -> read_misconceptions_for_course) or
update _SYSTEM_PROMPT to reference the actual registered names
(read_concepts_for_user_tool and read_misconceptions_for_course_tool) so the
prompt matches the function symbols used at registration.

_PROMPT_HASH = hashlib.sha256(_SYSTEM_PROMPT.encode("utf-8")).hexdigest()[:12]


quiz_agent = Agent[SaplingDeps, Quiz](
model=model_for("quiz"),
deps_type=SaplingDeps,
output_type=Quiz,
system_prompt=_SYSTEM_PROMPT,
metadata={"prompt_version": _PROMPT_HASH, "agent": "quiz"},
tools=[
read_concepts_for_user_tool,
read_misconceptions_for_course_tool,
],
)
163 changes: 163 additions & 0 deletions backend/agents/tools/graph_read.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
"""Read-side graph tools for Pydantic AI agents.

Per ADR 0004: the agent needs to pull mastery state + course-level
misconceptions when planning a quiz. These are the tool surfaces.
The pure-async functions are callable directly from routes;
the *_tool wrappers register on a Pydantic AI Agent.
"""

from __future__ import annotations

import asyncio
import logging
from typing import Any

from pydantic import BaseModel, Field
from pydantic_ai import RunContext

from agents.deps import SaplingDeps
from db.connection import table

logger = logging.getLogger(__name__)


# ── read_concepts_for_user ────────────────────────────────────────────────


class ConceptMastery(BaseModel):
"""Per-concept mastery state for the user in a course."""

concept_name: str
mastery: float = Field(ge=0.0, le=1.0)
last_reviewed_at: str | None = None


async def read_concepts_for_user(
user_id: str,
course_id: str | None,
) -> list[ConceptMastery]:
"""Return the user's concept mastery for a course (or globally if
course_id is None). Sorted by mastery ASC so the weakest concepts
appear first — quiz_agent uses this ordering to focus on weak areas.

Pure async, callable from routes. Wraps the underlying sync
Supabase read in asyncio.to_thread so it doesn't block the loop.

NOTE: The underlying `graph_nodes` table stores the mastery value as
`mastery_score` and the timestamp as `last_studied_at`. We map them
here to the agent-facing names (`mastery`, `last_reviewed_at`) so the
tool contract stays stable even if storage column names change.
"""

def _fetch() -> list[dict[str, Any]]:
filters = {"user_id": f"eq.{user_id}"}
if course_id:
filters["course_id"] = f"eq.{course_id}"
try:
Comment on lines +54 to +56

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Remove the unsupported course_id filter from graph_nodes reads.

On Line 55, filters["course_id"] is added, but the provided schema for graph_nodes (in backend/db/archive/schema.sql:11-22) has no course_id column. That causes the select to fail, then Lines 65-71 swallow it and return [], so weak-concept context is silently lost for course-scoped requests.

🔧 Proposed fix
 def _fetch() -> list[dict[str, Any]]:
filters = {"user_id": f"eq.{user_id}"}
- if course_id:- filters["course_id"] = f"eq.{course_id}"
try:
return (
table("graph_nodes").select(
"concept_name,mastery_score,last_studied_at",
filters=filters,
order="mastery_score.asc",
)
or []
)

Also applies to: 65-71

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@backend/agents/tools/graph_read.py` around lines 54 - 56, Remove the
unsupported course_id filter when querying graph_nodes: delete the line that
sets filters["course_id"] = f"eq.{course_id}" inside the graph_nodes read code
so you don't send a non-existent column to the DB; also stop silently swallowing
the resulting exception in the surrounding try/except (the block that currently
catches errors and returns []), instead let the exception propagate or log and
re-raise so callers know the read failed and course-scoped context isn’t
silently dropped. Reference the filters dict used for graph_nodes reads and the
try/except that returns an empty list to locate the changes.

return (
table("graph_nodes").select(
"concept_name,mastery_score,last_studied_at",
filters=filters,
order="mastery_score.asc",
)
or []
)
except Exception:
logger.exception(
"read_concepts_for_user failed for user=%s course=%s",
user_id,
course_id,
)
return []

rows = await asyncio.to_thread(_fetch)
return [
ConceptMastery(
concept_name=r.get("concept_name") or "",
mastery=float(r.get("mastery_score") or 0.0),
last_reviewed_at=r.get("last_studied_at"),
)
for r in rows
if r.get("concept_name")
]


async def read_concepts_for_user_tool(
ctx: RunContext[SaplingDeps],
) -> list[ConceptMastery]:
"""Pydantic AI tool wrapper. Reads from ctx.deps."""
return await read_concepts_for_user(ctx.deps.user_id, ctx.deps.course_id)


# ── read_misconceptions_for_course ────────────────────────────────────────


class Misconception(BaseModel):
"""A class-level misconception observed across student sessions."""

text: str
related_concept: str | None = None


async def read_misconceptions_for_course(
course_id: str | None,
) -> list[Misconception]:
"""Return aggregated misconception strings for a course. Anonymized
(sourced from class-wide patterns, not from any single student).
Returns [] when course_id is None or the underlying table is empty.

Source: `course_concept_stats` rows for the course. Each row
represents one concept and carries a `common_misconceptions` array
(populated by the hash-gated aggregation in
`services/course_context_service.py`). We flatten each array entry
into its own Misconception, tagging `related_concept` with the
concept name so the agent can route distractors per-concept.

The spec referenced a hypothetical `misconceptions` table — that
table does not exist in this schema. `course_concept_stats` is the
real source of class-wide misconception strings, so we read that.
The tool contract (returning Misconception[]) is unchanged.
"""
if not course_id:
return []

def _fetch() -> list[dict[str, Any]]:
try:
return (
table("course_concept_stats").select(
"concept_name,common_misconceptions",
filters={"course_id": f"eq.{course_id}"},
order="updated_at.desc",
limit=20,
)
or []
)
except Exception:
logger.exception(
"read_misconceptions_for_course failed for course=%s",
course_id,
)
return []

rows = await asyncio.to_thread(_fetch)
out: list[Misconception] = []
seen: set[str] = set()
for r in rows:
concept = r.get("concept_name") or None
for m in r.get("common_misconceptions") or []:
text = (m or "").strip() if isinstance(m, str) else ""
if not text:
continue
key = text.lower()
if key in seen:
continue
seen.add(key)
out.append(Misconception(text=text, related_concept=concept))
return out


async def read_misconceptions_for_course_tool(
ctx: RunContext[SaplingDeps],
) -> list[Misconception]:
"""Pydantic AI tool wrapper. Reads from ctx.deps."""
return await read_misconceptions_for_course(ctx.deps.course_id)
6 changes: 6 additions & 0 deletions backend/models/__init__.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,6 +44,12 @@ class GenerateQuizBody(BaseModel):
num_questions: int = 5
difficulty: str = "medium"
use_shared_context: bool = True
# Mirrors the Learn-route fast/smart toggle so quiz generation has
# the same per-request model-quality choice as chat tutoring.
# "fast" → gemini-2.5-flash, "smart" → gemini-2.5-pro. None falls
# through to whatever SAPLING_MODEL_QUIZ resolves to (default
# gemini-2.5-flash-lite per ADR 0008).
model_pref: Optional[Literal["fast", "smart"]] = None


class AnswerItem(BaseModel):
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
refactor(quiz): convert generate_quiz to quiz_agent (refactor #2) by Jose-Gael-Cruz-Lopez · Pull Request #71 · SaplingLearn/Sapling · GitHub
Skip to content
7 changes: 6 additions & 1 deletion backend/agents/_providers.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@
SAPLING_MODEL_SUMMARY=gemini-2.5-flash-lite
SAPLING_MODEL_CONCEPTS=gemini-2.5-flash
SAPLING_MODEL_SYLLABUS=gemini-2.5-flash
SAPLING_MODEL_QUIZ=gemini-2.5-flash-lite

Defaults are tuned per task: cheaper models for simpler classifications,
flagship Flash for tasks where output quality drives downstream UX.
Expand All@@ -23,7 +24,7 @@
from config import GEMINI_API_KEY


AgentTask = Literal["classifier", "summary", "concepts", "syllabus"]
AgentTask = Literal["classifier", "summary", "concepts", "syllabus", "quiz"]


# Defaults are conservative. Bumping a model up costs more; the env var
Expand All@@ -33,6 +34,10 @@
"summary": "gemini-2.5-flash-lite",
"concepts": "gemini-2.5-flash",
"syllabus": "gemini-2.5-flash",
# Quiz generation defaults to lite: it's a single-shot non-streaming
# call where the agent pulls structured graph data via tools, so the
# bulk of the value is in tool wiring, not raw model strength.
"quiz": "gemini-2.5-flash-lite",
}


Expand Down
111 changes: 111 additions & 0 deletions backend/agents/quiz.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
"""Quiz-generation agent.

Replaces routes/quiz.py:82's call_gemini_json + manual prompt-string
augmentation. The agent has tools to pull weak concepts + class
misconceptions on demand instead of pre-stuffing them into the prompt.

Per ADR 0003 convention 4: keep the output schema compact. Gemini's
structured-output API rejects rich nested schemas with too many states
for serving — Quiz is a flat top-level model with a list of
QuizQuestion items, no further nesting.
"""

from __future__ import annotations

import hashlib
from typing import Literal

from pydantic import BaseModel, Field
from pydantic_ai import Agent

from agents._providers import model_for
from agents.deps import SaplingDeps
from agents.tools.graph_read import (
read_concepts_for_user_tool,
read_misconceptions_for_course_tool,
)


# Difficulty + question type are Literals so Gemini's enum constraint
# applies and downstream UI can branch on stable strings.
#
# `QuizQuestionType` is intentionally MCQ-only today. The frontend
# `submitQuiz` flow grades by `q["options"][i].correct` lookup — there's
# no UI for free-text answers, no fuzzy-match grading, no LLM-judged
# scoring. Generating short-answer questions through this path would
# emit unrenderable, ungradable items. Keep the type narrow until real
# short-answer support exists; revisit when that lands.
QuizDifficulty = Literal["easy", "medium", "hard"]
QuizQuestionType = Literal["multiple_choice"]


class QuizQuestion(BaseModel):
"""A single multiple-choice quiz question. Kept small so the parent
Quiz schema doesn't trip Gemini's structured-output complexity limit."""

question: str = Field(max_length=600)
type: QuizQuestionType
difficulty: QuizDifficulty
# 3-6 options. The agent is required to populate this for every
# question and to make `correct_answer` match exactly one of them.
options: list[str] = Field(min_length=3, max_length=6)
# The option text the agent considers correct. Must appear verbatim
# in `options`; the route validates this and drops questions that
# violate the contract rather than silently mis-marking them.
correct_answer: str = Field(max_length=400)
explanation: str = Field(max_length=600)
# Concept the question is testing — must be one of the user's known
# concept_names per the prompt. Used by the route to award mastery
# on a correct answer.
concept: str = Field(max_length=120)


class Quiz(BaseModel):
"""The agent's structured output."""

questions: list[QuizQuestion] = Field(min_length=1, max_length=20)


_SYSTEM_PROMPT = (
"You generate adaptive multiple-choice quizzes for a student. Each "
"question must target a specific concept the student has weak "
"mastery on, OR address a class-level misconception you've seen.\n\n"
"Workflow:\n"
"1. Call `read_concepts_for_user` to see the student's mastery per "
" concept for this course (returned sorted by mastery ASC — "
" weakest first).\n"
"2. Call `read_misconceptions_for_course` to see anonymized class "
" misconceptions. Use these to phrase distractors and to write "
" a question that probes the misconception.\n"
"3. Compose `Quiz.questions` so the WEAKEST concepts get the most "
" questions, AND each item's `concept` field exactly matches a "
" concept_name returned by tool 1.\n\n"
"Per-question rules (multiple-choice only — the type field is "
"constrained to 'multiple_choice'):\n"
"- 4 options, exactly one correct. The text in `correct_answer` "
" MUST appear verbatim in `options` — character-for-character. "
" Questions that violate this are dropped at the route layer.\n"
"- Distractors should reflect plausible misconceptions, not random "
" noise. Use the read_misconceptions_for_course return value.\n"
"- explanation: 1-3 sentences explaining WHY the correct answer "
" is correct — used in the post-quiz review screen.\n"
"- difficulty: align with the student's mastery on the concept; "
" weakest concepts get easy/medium, strongest get hard.\n\n"
"Honor the requested num_questions and difficulty distribution "
"in the user message. Don't invent concepts the student doesn't "
"have."
)
Comment on lines +69 to +97

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bashset -euo pipefail
# Confirm the exact registered tool names and whether any aliasing is applied.
rg -n --type=py 'def read_concepts_for_user_tool|def read_misconceptions_for_course_tool|read_concepts_for_user\b|read_misconceptions_for_course\b|tools=\[' backend/agents

Repository: SaplingLearn/Sapling

Length of output: 1385


🏁 Script executed:

# Check the tools registration in quiz.py
sed -n '100,130p' backend/agents/quiz.py

Repository: SaplingLearn/Sapling

Length of output: 383


🏁 Script executed:

# Also check if pydantic-ai is imported and how it handles tool names
rg -n "from pydantic_ai|import.*pydantic_ai|agent.*tools" backend/agents/quiz.py -A 2 -B 2

Repository: SaplingLearn/Sapling

Length of output: 568


🏁 Script executed:

# Check pydantic-ai documentation or examples in the codebase for tool naming
rg -n "def.*_tool\(" backend/agents --type=py -B 5 | head -40

Repository: SaplingLearn/Sapling

Length of output: 1084


🏁 Script executed:

# Check if the _tool functions have any decorators or name parameters
rg -n "@|name\s*=" backend/agents/tools/graph_read.py -B 2 -A 8 | grep -A 10 "read_concepts_for_user_tool\|read_misconceptions_for_course_tool"

Repository: SaplingLearn/Sapling

Length of output: 46


🏁 Script executed:

# Search for pydantic_ai documentation or configuration in the codebase
rg -n "pydantic_ai.*tool|Tool.*name|tool.*alias" backend --type=py | head -20

Repository: SaplingLearn/Sapling

Length of output: 46


🌐 Web query:

pydantic-ai tool naming convention function name suffix

💡 Result:

Pydantic AI does not enforce a specific function name suffix or strict naming convention for tools beyond requiring unique tool names within a toolset or agent. The tool name defaults to the Python function name (snake_case convention in examples like 'roll_dice', 'get_player_name', 'customer_balance'), but can be explicitly overridden via the 'name' parameter in decorators (@agent.tool(name='custom_name'), Tool constructor, Tool.from_schema) or toolset methods. ToolDefinition names must be unique to avoid conflicts (raises UserError on duplicates), but no suffix like '_tool' is required or conventional. Use descriptive, unique names that clearly communicate purpose, following Python snake_case for functions.

Citations:


Fix tool name mismatch between prompt and registration.

The prompt instructs the agent to call read_concepts_for_user and read_misconceptions_for_course, but the registered tools are read_concepts_for_user_tool and read_misconceptions_for_course_tool. Pydantic-ai uses the function name directly as the tool name without auto-aliasing suffixes, so the agent will fail to locate these tools when following the prompt instructions.

Either rename the functions to remove the _tool suffix or update the prompt to reference the correct tool names.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@backend/agents/quiz.py` around lines 69 - 97, The system prompt
(_SYSTEM_PROMPT) tells the agent to call read_concepts_for_user and
read_misconceptions_for_course, but the actual registered tool functions are
named read_concepts_for_user_tool and read_misconceptions_for_course_tool, so
the agent will not find the tools; fix by making the names consistent: either
rename the tool functions (read_concepts_for_user_tool -> read_concepts_for_user
and read_misconceptions_for_course_tool -> read_misconceptions_for_course) or
update _SYSTEM_PROMPT to reference the actual registered names
(read_concepts_for_user_tool and read_misconceptions_for_course_tool) so the
prompt matches the function symbols used at registration.

_PROMPT_HASH = hashlib.sha256(_SYSTEM_PROMPT.encode("utf-8")).hexdigest()[:12]


quiz_agent = Agent[SaplingDeps, Quiz](
model=model_for("quiz"),
deps_type=SaplingDeps,
output_type=Quiz,
system_prompt=_SYSTEM_PROMPT,
metadata={"prompt_version": _PROMPT_HASH, "agent": "quiz"},
tools=[
read_concepts_for_user_tool,
read_misconceptions_for_course_tool,
],
)
163 changes: 163 additions & 0 deletions backend/agents/tools/graph_read.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
"""Read-side graph tools for Pydantic AI agents.

Per ADR 0004: the agent needs to pull mastery state + course-level
misconceptions when planning a quiz. These are the tool surfaces.
The pure-async functions are callable directly from routes;
the *_tool wrappers register on a Pydantic AI Agent.
"""

from __future__ import annotations

import asyncio
import logging
from typing import Any

from pydantic import BaseModel, Field
from pydantic_ai import RunContext

from agents.deps import SaplingDeps
from db.connection import table

logger = logging.getLogger(__name__)


# ── read_concepts_for_user ────────────────────────────────────────────────


class ConceptMastery(BaseModel):
"""Per-concept mastery state for the user in a course."""

concept_name: str
mastery: float = Field(ge=0.0, le=1.0)
last_reviewed_at: str | None = None


async def read_concepts_for_user(
user_id: str,
course_id: str | None,
) -> list[ConceptMastery]:
"""Return the user's concept mastery for a course (or globally if
course_id is None). Sorted by mastery ASC so the weakest concepts
appear first — quiz_agent uses this ordering to focus on weak areas.

Pure async, callable from routes. Wraps the underlying sync
Supabase read in asyncio.to_thread so it doesn't block the loop.

NOTE: The underlying `graph_nodes` table stores the mastery value as
`mastery_score` and the timestamp as `last_studied_at`. We map them
here to the agent-facing names (`mastery`, `last_reviewed_at`) so the
tool contract stays stable even if storage column names change.
"""

def _fetch() -> list[dict[str, Any]]:
filters = {"user_id": f"eq.{user_id}"}
if course_id:
filters["course_id"] = f"eq.{course_id}"
try:
Comment on lines +54 to +56

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Remove the unsupported course_id filter from graph_nodes reads.

On Line 55, filters["course_id"] is added, but the provided schema for graph_nodes (in backend/db/archive/schema.sql:11-22) has no course_id column. That causes the select to fail, then Lines 65-71 swallow it and return [], so weak-concept context is silently lost for course-scoped requests.

🔧 Proposed fix
 def _fetch() -> list[dict[str, Any]]:
filters = {"user_id": f"eq.{user_id}"}
- if course_id:- filters["course_id"] = f"eq.{course_id}"
try:
return (
table("graph_nodes").select(
"concept_name,mastery_score,last_studied_at",
filters=filters,
order="mastery_score.asc",
)
or []
)

Also applies to: 65-71

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@backend/agents/tools/graph_read.py` around lines 54 - 56, Remove the
unsupported course_id filter when querying graph_nodes: delete the line that
sets filters["course_id"] = f"eq.{course_id}" inside the graph_nodes read code
so you don't send a non-existent column to the DB; also stop silently swallowing
the resulting exception in the surrounding try/except (the block that currently
catches errors and returns []), instead let the exception propagate or log and
re-raise so callers know the read failed and course-scoped context isn’t
silently dropped. Reference the filters dict used for graph_nodes reads and the
try/except that returns an empty list to locate the changes.

return (
table("graph_nodes").select(
"concept_name,mastery_score,last_studied_at",
filters=filters,
order="mastery_score.asc",
)
or []
)
except Exception:
logger.exception(
"read_concepts_for_user failed for user=%s course=%s",
user_id,
course_id,
)
return []

rows = await asyncio.to_thread(_fetch)
return [
ConceptMastery(
concept_name=r.get("concept_name") or "",
mastery=float(r.get("mastery_score") or 0.0),
last_reviewed_at=r.get("last_studied_at"),
)
for r in rows
if r.get("concept_name")
]


async def read_concepts_for_user_tool(
ctx: RunContext[SaplingDeps],
) -> list[ConceptMastery]:
"""Pydantic AI tool wrapper. Reads from ctx.deps."""
return await read_concepts_for_user(ctx.deps.user_id, ctx.deps.course_id)


# ── read_misconceptions_for_course ────────────────────────────────────────


class Misconception(BaseModel):
"""A class-level misconception observed across student sessions."""

text: str
related_concept: str | None = None


async def read_misconceptions_for_course(
course_id: str | None,
) -> list[Misconception]:
"""Return aggregated misconception strings for a course. Anonymized
(sourced from class-wide patterns, not from any single student).
Returns [] when course_id is None or the underlying table is empty.

Source: `course_concept_stats` rows for the course. Each row
represents one concept and carries a `common_misconceptions` array
(populated by the hash-gated aggregation in
`services/course_context_service.py`). We flatten each array entry
into its own Misconception, tagging `related_concept` with the
concept name so the agent can route distractors per-concept.

The spec referenced a hypothetical `misconceptions` table — that
table does not exist in this schema. `course_concept_stats` is the
real source of class-wide misconception strings, so we read that.
The tool contract (returning Misconception[]) is unchanged.
"""
if not course_id:
return []

def _fetch() -> list[dict[str, Any]]:
try:
return (
table("course_concept_stats").select(
"concept_name,common_misconceptions",
filters={"course_id": f"eq.{course_id}"},
order="updated_at.desc",
limit=20,
)
or []
)
except Exception:
logger.exception(
"read_misconceptions_for_course failed for course=%s",
course_id,
)
return []

rows = await asyncio.to_thread(_fetch)
out: list[Misconception] = []
seen: set[str] = set()
for r in rows:
concept = r.get("concept_name") or None
for m in r.get("common_misconceptions") or []:
text = (m or "").strip() if isinstance(m, str) else ""
if not text:
continue
key = text.lower()
if key in seen:
continue
seen.add(key)
out.append(Misconception(text=text, related_concept=concept))
return out


async def read_misconceptions_for_course_tool(
ctx: RunContext[SaplingDeps],
) -> list[Misconception]:
"""Pydantic AI tool wrapper. Reads from ctx.deps."""
return await read_misconceptions_for_course(ctx.deps.course_id)
6 changes: 6 additions & 0 deletions backend/models/__init__.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,6 +44,12 @@ class GenerateQuizBody(BaseModel):
num_questions: int = 5
difficulty: str = "medium"
use_shared_context: bool = True
# Mirrors the Learn-route fast/smart toggle so quiz generation has
# the same per-request model-quality choice as chat tutoring.
# "fast" → gemini-2.5-flash, "smart" → gemini-2.5-pro. None falls
# through to whatever SAPLING_MODEL_QUIZ resolves to (default
# gemini-2.5-flash-lite per ADR 0008).
model_pref: Optional[Literal["fast", "smart"]] = None


class AnswerItem(BaseModel):
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' refactor(quiz): convert generate_quiz to quiz_agent (refactor #2) by Jose-Gael-Cruz-Lopez · Pull Request #71 · SaplingLearn/Sapling · GitHub
Skip to content
7 changes: 6 additions & 1 deletion backend/agents/_providers.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@
SAPLING_MODEL_SUMMARY=gemini-2.5-flash-lite
SAPLING_MODEL_CONCEPTS=gemini-2.5-flash
SAPLING_MODEL_SYLLABUS=gemini-2.5-flash
SAPLING_MODEL_QUIZ=gemini-2.5-flash-lite

Defaults are tuned per task: cheaper models for simpler classifications,
flagship Flash for tasks where output quality drives downstream UX.
Expand All@@ -23,7 +24,7 @@
from config import GEMINI_API_KEY


AgentTask = Literal["classifier", "summary", "concepts", "syllabus"]
AgentTask = Literal["classifier", "summary", "concepts", "syllabus", "quiz"]


# Defaults are conservative. Bumping a model up costs more; the env var
Expand All@@ -33,6 +34,10 @@
"summary": "gemini-2.5-flash-lite",
"concepts": "gemini-2.5-flash",
"syllabus": "gemini-2.5-flash",
# Quiz generation defaults to lite: it's a single-shot non-streaming
# call where the agent pulls structured graph data via tools, so the
# bulk of the value is in tool wiring, not raw model strength.
"quiz": "gemini-2.5-flash-lite",
}


Expand Down
111 changes: 111 additions & 0 deletions backend/agents/quiz.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
"""Quiz-generation agent.

Replaces routes/quiz.py:82's call_gemini_json + manual prompt-string
augmentation. The agent has tools to pull weak concepts + class
misconceptions on demand instead of pre-stuffing them into the prompt.

Per ADR 0003 convention 4: keep the output schema compact. Gemini's
structured-output API rejects rich nested schemas with too many states
for serving — Quiz is a flat top-level model with a list of
QuizQuestion items, no further nesting.
"""

from __future__ import annotations

import hashlib
from typing import Literal

from pydantic import BaseModel, Field
from pydantic_ai import Agent

from agents._providers import model_for
from agents.deps import SaplingDeps
from agents.tools.graph_read import (
read_concepts_for_user_tool,
read_misconceptions_for_course_tool,
)


# Difficulty + question type are Literals so Gemini's enum constraint
# applies and downstream UI can branch on stable strings.
#
# `QuizQuestionType` is intentionally MCQ-only today. The frontend
# `submitQuiz` flow grades by `q["options"][i].correct` lookup — there's
# no UI for free-text answers, no fuzzy-match grading, no LLM-judged
# scoring. Generating short-answer questions through this path would
# emit unrenderable, ungradable items. Keep the type narrow until real
# short-answer support exists; revisit when that lands.
QuizDifficulty = Literal["easy", "medium", "hard"]
QuizQuestionType = Literal["multiple_choice"]


class QuizQuestion(BaseModel):
"""A single multiple-choice quiz question. Kept small so the parent
Quiz schema doesn't trip Gemini's structured-output complexity limit."""

question: str = Field(max_length=600)
type: QuizQuestionType
difficulty: QuizDifficulty
# 3-6 options. The agent is required to populate this for every
# question and to make `correct_answer` match exactly one of them.
options: list[str] = Field(min_length=3, max_length=6)
# The option text the agent considers correct. Must appear verbatim
# in `options`; the route validates this and drops questions that
# violate the contract rather than silently mis-marking them.
correct_answer: str = Field(max_length=400)
explanation: str = Field(max_length=600)
# Concept the question is testing — must be one of the user's known
# concept_names per the prompt. Used by the route to award mastery
# on a correct answer.
concept: str = Field(max_length=120)


class Quiz(BaseModel):
"""The agent's structured output."""

questions: list[QuizQuestion] = Field(min_length=1, max_length=20)


_SYSTEM_PROMPT = (
"You generate adaptive multiple-choice quizzes for a student. Each "
"question must target a specific concept the student has weak "
"mastery on, OR address a class-level misconception you've seen.\n\n"
"Workflow:\n"
"1. Call `read_concepts_for_user` to see the student's mastery per "
" concept for this course (returned sorted by mastery ASC — "
" weakest first).\n"
"2. Call `read_misconceptions_for_course` to see anonymized class "
" misconceptions. Use these to phrase distractors and to write "
" a question that probes the misconception.\n"
"3. Compose `Quiz.questions` so the WEAKEST concepts get the most "
" questions, AND each item's `concept` field exactly matches a "
" concept_name returned by tool 1.\n\n"
"Per-question rules (multiple-choice only — the type field is "
"constrained to 'multiple_choice'):\n"
"- 4 options, exactly one correct. The text in `correct_answer` "
" MUST appear verbatim in `options` — character-for-character. "
" Questions that violate this are dropped at the route layer.\n"
"- Distractors should reflect plausible misconceptions, not random "
" noise. Use the read_misconceptions_for_course return value.\n"
"- explanation: 1-3 sentences explaining WHY the correct answer "
" is correct — used in the post-quiz review screen.\n"
"- difficulty: align with the student's mastery on the concept; "
" weakest concepts get easy/medium, strongest get hard.\n\n"
"Honor the requested num_questions and difficulty distribution "
"in the user message. Don't invent concepts the student doesn't "
"have."
)
Comment on lines +69 to +97

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bashset -euo pipefail
# Confirm the exact registered tool names and whether any aliasing is applied.
rg -n --type=py 'def read_concepts_for_user_tool|def read_misconceptions_for_course_tool|read_concepts_for_user\b|read_misconceptions_for_course\b|tools=\[' backend/agents

Repository: SaplingLearn/Sapling

Length of output: 1385


🏁 Script executed:

# Check the tools registration in quiz.py
sed -n '100,130p' backend/agents/quiz.py

Repository: SaplingLearn/Sapling

Length of output: 383


🏁 Script executed:

# Also check if pydantic-ai is imported and how it handles tool names
rg -n "from pydantic_ai|import.*pydantic_ai|agent.*tools" backend/agents/quiz.py -A 2 -B 2

Repository: SaplingLearn/Sapling

Length of output: 568


🏁 Script executed:

# Check pydantic-ai documentation or examples in the codebase for tool naming
rg -n "def.*_tool\(" backend/agents --type=py -B 5 | head -40

Repository: SaplingLearn/Sapling

Length of output: 1084


🏁 Script executed:

# Check if the _tool functions have any decorators or name parameters
rg -n "@|name\s*=" backend/agents/tools/graph_read.py -B 2 -A 8 | grep -A 10 "read_concepts_for_user_tool\|read_misconceptions_for_course_tool"

Repository: SaplingLearn/Sapling

Length of output: 46


🏁 Script executed:

# Search for pydantic_ai documentation or configuration in the codebase
rg -n "pydantic_ai.*tool|Tool.*name|tool.*alias" backend --type=py | head -20

Repository: SaplingLearn/Sapling

Length of output: 46


🌐 Web query:

pydantic-ai tool naming convention function name suffix

💡 Result:

Pydantic AI does not enforce a specific function name suffix or strict naming convention for tools beyond requiring unique tool names within a toolset or agent. The tool name defaults to the Python function name (snake_case convention in examples like 'roll_dice', 'get_player_name', 'customer_balance'), but can be explicitly overridden via the 'name' parameter in decorators (@agent.tool(name='custom_name'), Tool constructor, Tool.from_schema) or toolset methods. ToolDefinition names must be unique to avoid conflicts (raises UserError on duplicates), but no suffix like '_tool' is required or conventional. Use descriptive, unique names that clearly communicate purpose, following Python snake_case for functions.

Citations:


Fix tool name mismatch between prompt and registration.

The prompt instructs the agent to call read_concepts_for_user and read_misconceptions_for_course, but the registered tools are read_concepts_for_user_tool and read_misconceptions_for_course_tool. Pydantic-ai uses the function name directly as the tool name without auto-aliasing suffixes, so the agent will fail to locate these tools when following the prompt instructions.

Either rename the functions to remove the _tool suffix or update the prompt to reference the correct tool names.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@backend/agents/quiz.py` around lines 69 - 97, The system prompt
(_SYSTEM_PROMPT) tells the agent to call read_concepts_for_user and
read_misconceptions_for_course, but the actual registered tool functions are
named read_concepts_for_user_tool and read_misconceptions_for_course_tool, so
the agent will not find the tools; fix by making the names consistent: either
rename the tool functions (read_concepts_for_user_tool -> read_concepts_for_user
and read_misconceptions_for_course_tool -> read_misconceptions_for_course) or
update _SYSTEM_PROMPT to reference the actual registered names
(read_concepts_for_user_tool and read_misconceptions_for_course_tool) so the
prompt matches the function symbols used at registration.

_PROMPT_HASH = hashlib.sha256(_SYSTEM_PROMPT.encode("utf-8")).hexdigest()[:12]


quiz_agent = Agent[SaplingDeps, Quiz](
model=model_for("quiz"),
deps_type=SaplingDeps,
output_type=Quiz,
system_prompt=_SYSTEM_PROMPT,
metadata={"prompt_version": _PROMPT_HASH, "agent": "quiz"},
tools=[
read_concepts_for_user_tool,
read_misconceptions_for_course_tool,
],
)
163 changes: 163 additions & 0 deletions backend/agents/tools/graph_read.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
"""Read-side graph tools for Pydantic AI agents.

Per ADR 0004: the agent needs to pull mastery state + course-level
misconceptions when planning a quiz. These are the tool surfaces.
The pure-async functions are callable directly from routes;
the *_tool wrappers register on a Pydantic AI Agent.
"""

from __future__ import annotations

import asyncio
import logging
from typing import Any

from pydantic import BaseModel, Field
from pydantic_ai import RunContext

from agents.deps import SaplingDeps
from db.connection import table

logger = logging.getLogger(__name__)


# ── read_concepts_for_user ────────────────────────────────────────────────


class ConceptMastery(BaseModel):
"""Per-concept mastery state for the user in a course."""

concept_name: str
mastery: float = Field(ge=0.0, le=1.0)
last_reviewed_at: str | None = None


async def read_concepts_for_user(
user_id: str,
course_id: str | None,
) -> list[ConceptMastery]:
"""Return the user's concept mastery for a course (or globally if
course_id is None). Sorted by mastery ASC so the weakest concepts
appear first — quiz_agent uses this ordering to focus on weak areas.

Pure async, callable from routes. Wraps the underlying sync
Supabase read in asyncio.to_thread so it doesn't block the loop.

NOTE: The underlying `graph_nodes` table stores the mastery value as
`mastery_score` and the timestamp as `last_studied_at`. We map them
here to the agent-facing names (`mastery`, `last_reviewed_at`) so the
tool contract stays stable even if storage column names change.
"""

def _fetch() -> list[dict[str, Any]]:
filters = {"user_id": f"eq.{user_id}"}
if course_id:
filters["course_id"] = f"eq.{course_id}"
try:
Comment on lines +54 to +56

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Remove the unsupported course_id filter from graph_nodes reads.

On Line 55, filters["course_id"] is added, but the provided schema for graph_nodes (in backend/db/archive/schema.sql:11-22) has no course_id column. That causes the select to fail, then Lines 65-71 swallow it and return [], so weak-concept context is silently lost for course-scoped requests.

🔧 Proposed fix
 def _fetch() -> list[dict[str, Any]]:
filters = {"user_id": f"eq.{user_id}"}
- if course_id:- filters["course_id"] = f"eq.{course_id}"
try:
return (
table("graph_nodes").select(
"concept_name,mastery_score,last_studied_at",
filters=filters,
order="mastery_score.asc",
)
or []
)

Also applies to: 65-71

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@backend/agents/tools/graph_read.py` around lines 54 - 56, Remove the
unsupported course_id filter when querying graph_nodes: delete the line that
sets filters["course_id"] = f"eq.{course_id}" inside the graph_nodes read code
so you don't send a non-existent column to the DB; also stop silently swallowing
the resulting exception in the surrounding try/except (the block that currently
catches errors and returns []), instead let the exception propagate or log and
re-raise so callers know the read failed and course-scoped context isn’t
silently dropped. Reference the filters dict used for graph_nodes reads and the
try/except that returns an empty list to locate the changes.

return (
table("graph_nodes").select(
"concept_name,mastery_score,last_studied_at",
filters=filters,
order="mastery_score.asc",
)
or []
)
except Exception:
logger.exception(
"read_concepts_for_user failed for user=%s course=%s",
user_id,
course_id,
)
return []

rows = await asyncio.to_thread(_fetch)
return [
ConceptMastery(
concept_name=r.get("concept_name") or "",
mastery=float(r.get("mastery_score") or 0.0),
last_reviewed_at=r.get("last_studied_at"),
)
for r in rows
if r.get("concept_name")
]


async def read_concepts_for_user_tool(
ctx: RunContext[SaplingDeps],
) -> list[ConceptMastery]:
"""Pydantic AI tool wrapper. Reads from ctx.deps."""
return await read_concepts_for_user(ctx.deps.user_id, ctx.deps.course_id)


# ── read_misconceptions_for_course ────────────────────────────────────────


class Misconception(BaseModel):
"""A class-level misconception observed across student sessions."""

text: str
related_concept: str | None = None


async def read_misconceptions_for_course(
course_id: str | None,
) -> list[Misconception]:
"""Return aggregated misconception strings for a course. Anonymized
(sourced from class-wide patterns, not from any single student).
Returns [] when course_id is None or the underlying table is empty.

Source: `course_concept_stats` rows for the course. Each row
represents one concept and carries a `common_misconceptions` array
(populated by the hash-gated aggregation in
`services/course_context_service.py`). We flatten each array entry
into its own Misconception, tagging `related_concept` with the
concept name so the agent can route distractors per-concept.

The spec referenced a hypothetical `misconceptions` table — that
table does not exist in this schema. `course_concept_stats` is the
real source of class-wide misconception strings, so we read that.
The tool contract (returning Misconception[]) is unchanged.
"""
if not course_id:
return []

def _fetch() -> list[dict[str, Any]]:
try:
return (
table("course_concept_stats").select(
"concept_name,common_misconceptions",
filters={"course_id": f"eq.{course_id}"},
order="updated_at.desc",
limit=20,
)
or []
)
except Exception:
logger.exception(
"read_misconceptions_for_course failed for course=%s",
course_id,
)
return []

rows = await asyncio.to_thread(_fetch)
out: list[Misconception] = []
seen: set[str] = set()
for r in rows:
concept = r.get("concept_name") or None
for m in r.get("common_misconceptions") or []:
text = (m or "").strip() if isinstance(m, str) else ""
if not text:
continue
key = text.lower()
if key in seen:
continue
seen.add(key)
out.append(Misconception(text=text, related_concept=concept))
return out


async def read_misconceptions_for_course_tool(
ctx: RunContext[SaplingDeps],
) -> list[Misconception]:
"""Pydantic AI tool wrapper. Reads from ctx.deps."""
return await read_misconceptions_for_course(ctx.deps.course_id)
6 changes: 6 additions & 0 deletions backend/models/__init__.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,6 +44,12 @@ class GenerateQuizBody(BaseModel):
num_questions: int = 5
difficulty: str = "medium"
use_shared_context: bool = True
# Mirrors the Learn-route fast/smart toggle so quiz generation has
# the same per-request model-quality choice as chat tutoring.
# "fast" → gemini-2.5-flash, "smart" → gemini-2.5-pro. None falls
# through to whatever SAPLING_MODEL_QUIZ resolves to (default
# gemini-2.5-flash-lite per ADR 0008).
model_pref: Optional[Literal["fast", "smart"]] = None


class AnswerItem(BaseModel):
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' refactor(quiz): convert generate_quiz to quiz_agent (refactor #2) by Jose-Gael-Cruz-Lopez · Pull Request #71 · SaplingLearn/Sapling · GitHub
Skip to content
7 changes: 6 additions & 1 deletion backend/agents/_providers.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@
SAPLING_MODEL_SUMMARY=gemini-2.5-flash-lite
SAPLING_MODEL_CONCEPTS=gemini-2.5-flash
SAPLING_MODEL_SYLLABUS=gemini-2.5-flash
SAPLING_MODEL_QUIZ=gemini-2.5-flash-lite

Defaults are tuned per task: cheaper models for simpler classifications,
flagship Flash for tasks where output quality drives downstream UX.
Expand All@@ -23,7 +24,7 @@
from config import GEMINI_API_KEY


AgentTask = Literal["classifier", "summary", "concepts", "syllabus"]
AgentTask = Literal["classifier", "summary", "concepts", "syllabus", "quiz"]


# Defaults are conservative. Bumping a model up costs more; the env var
Expand All@@ -33,6 +34,10 @@
"summary": "gemini-2.5-flash-lite",
"concepts": "gemini-2.5-flash",
"syllabus": "gemini-2.5-flash",
# Quiz generation defaults to lite: it's a single-shot non-streaming
# call where the agent pulls structured graph data via tools, so the
# bulk of the value is in tool wiring, not raw model strength.
"quiz": "gemini-2.5-flash-lite",
}


Expand Down
111 changes: 111 additions & 0 deletions backend/agents/quiz.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
"""Quiz-generation agent.

Replaces routes/quiz.py:82's call_gemini_json + manual prompt-string
augmentation. The agent has tools to pull weak concepts + class
misconceptions on demand instead of pre-stuffing them into the prompt.

Per ADR 0003 convention 4: keep the output schema compact. Gemini's
structured-output API rejects rich nested schemas with too many states
for serving — Quiz is a flat top-level model with a list of
QuizQuestion items, no further nesting.
"""

from __future__ import annotations

import hashlib
from typing import Literal

from pydantic import BaseModel, Field
from pydantic_ai import Agent

from agents._providers import model_for
from agents.deps import SaplingDeps
from agents.tools.graph_read import (
read_concepts_for_user_tool,
read_misconceptions_for_course_tool,
)


# Difficulty + question type are Literals so Gemini's enum constraint
# applies and downstream UI can branch on stable strings.
#
# `QuizQuestionType` is intentionally MCQ-only today. The frontend
# `submitQuiz` flow grades by `q["options"][i].correct` lookup — there's
# no UI for free-text answers, no fuzzy-match grading, no LLM-judged
# scoring. Generating short-answer questions through this path would
# emit unrenderable, ungradable items. Keep the type narrow until real
# short-answer support exists; revisit when that lands.
QuizDifficulty = Literal["easy", "medium", "hard"]
QuizQuestionType = Literal["multiple_choice"]


class QuizQuestion(BaseModel):
"""A single multiple-choice quiz question. Kept small so the parent
Quiz schema doesn't trip Gemini's structured-output complexity limit."""

question: str = Field(max_length=600)
type: QuizQuestionType
difficulty: QuizDifficulty
# 3-6 options. The agent is required to populate this for every
# question and to make `correct_answer` match exactly one of them.
options: list[str] = Field(min_length=3, max_length=6)
# The option text the agent considers correct. Must appear verbatim
# in `options`; the route validates this and drops questions that
# violate the contract rather than silently mis-marking them.
correct_answer: str = Field(max_length=400)
explanation: str = Field(max_length=600)
# Concept the question is testing — must be one of the user's known
# concept_names per the prompt. Used by the route to award mastery
# on a correct answer.
concept: str = Field(max_length=120)


class Quiz(BaseModel):
"""The agent's structured output."""

questions: list[QuizQuestion] = Field(min_length=1, max_length=20)


_SYSTEM_PROMPT = (
"You generate adaptive multiple-choice quizzes for a student. Each "
"question must target a specific concept the student has weak "
"mastery on, OR address a class-level misconception you've seen.\n\n"
"Workflow:\n"
"1. Call `read_concepts_for_user` to see the student's mastery per "
" concept for this course (returned sorted by mastery ASC — "
" weakest first).\n"
"2. Call `read_misconceptions_for_course` to see anonymized class "
" misconceptions. Use these to phrase distractors and to write "
" a question that probes the misconception.\n"
"3. Compose `Quiz.questions` so the WEAKEST concepts get the most "
" questions, AND each item's `concept` field exactly matches a "
" concept_name returned by tool 1.\n\n"
"Per-question rules (multiple-choice only — the type field is "
"constrained to 'multiple_choice'):\n"
"- 4 options, exactly one correct. The text in `correct_answer` "
" MUST appear verbatim in `options` — character-for-character. "
" Questions that violate this are dropped at the route layer.\n"
"- Distractors should reflect plausible misconceptions, not random "
" noise. Use the read_misconceptions_for_course return value.\n"
"- explanation: 1-3 sentences explaining WHY the correct answer "
" is correct — used in the post-quiz review screen.\n"
"- difficulty: align with the student's mastery on the concept; "
" weakest concepts get easy/medium, strongest get hard.\n\n"
"Honor the requested num_questions and difficulty distribution "
"in the user message. Don't invent concepts the student doesn't "
"have."
)
Comment on lines +69 to +97

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bashset -euo pipefail
# Confirm the exact registered tool names and whether any aliasing is applied.
rg -n --type=py 'def read_concepts_for_user_tool|def read_misconceptions_for_course_tool|read_concepts_for_user\b|read_misconceptions_for_course\b|tools=\[' backend/agents

Repository: SaplingLearn/Sapling

Length of output: 1385


🏁 Script executed:

# Check the tools registration in quiz.py
sed -n '100,130p' backend/agents/quiz.py

Repository: SaplingLearn/Sapling

Length of output: 383


🏁 Script executed:

# Also check if pydantic-ai is imported and how it handles tool names
rg -n "from pydantic_ai|import.*pydantic_ai|agent.*tools" backend/agents/quiz.py -A 2 -B 2

Repository: SaplingLearn/Sapling

Length of output: 568


🏁 Script executed:

# Check pydantic-ai documentation or examples in the codebase for tool naming
rg -n "def.*_tool\(" backend/agents --type=py -B 5 | head -40

Repository: SaplingLearn/Sapling

Length of output: 1084


🏁 Script executed:

# Check if the _tool functions have any decorators or name parameters
rg -n "@|name\s*=" backend/agents/tools/graph_read.py -B 2 -A 8 | grep -A 10 "read_concepts_for_user_tool\|read_misconceptions_for_course_tool"

Repository: SaplingLearn/Sapling

Length of output: 46


🏁 Script executed:

# Search for pydantic_ai documentation or configuration in the codebase
rg -n "pydantic_ai.*tool|Tool.*name|tool.*alias" backend --type=py | head -20

Repository: SaplingLearn/Sapling

Length of output: 46


🌐 Web query:

pydantic-ai tool naming convention function name suffix

💡 Result:

Pydantic AI does not enforce a specific function name suffix or strict naming convention for tools beyond requiring unique tool names within a toolset or agent. The tool name defaults to the Python function name (snake_case convention in examples like 'roll_dice', 'get_player_name', 'customer_balance'), but can be explicitly overridden via the 'name' parameter in decorators (@agent.tool(name='custom_name'), Tool constructor, Tool.from_schema) or toolset methods. ToolDefinition names must be unique to avoid conflicts (raises UserError on duplicates), but no suffix like '_tool' is required or conventional. Use descriptive, unique names that clearly communicate purpose, following Python snake_case for functions.

Citations:


Fix tool name mismatch between prompt and registration.

The prompt instructs the agent to call read_concepts_for_user and read_misconceptions_for_course, but the registered tools are read_concepts_for_user_tool and read_misconceptions_for_course_tool. Pydantic-ai uses the function name directly as the tool name without auto-aliasing suffixes, so the agent will fail to locate these tools when following the prompt instructions.

Either rename the functions to remove the _tool suffix or update the prompt to reference the correct tool names.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@backend/agents/quiz.py` around lines 69 - 97, The system prompt
(_SYSTEM_PROMPT) tells the agent to call read_concepts_for_user and
read_misconceptions_for_course, but the actual registered tool functions are
named read_concepts_for_user_tool and read_misconceptions_for_course_tool, so
the agent will not find the tools; fix by making the names consistent: either
rename the tool functions (read_concepts_for_user_tool -> read_concepts_for_user
and read_misconceptions_for_course_tool -> read_misconceptions_for_course) or
update _SYSTEM_PROMPT to reference the actual registered names
(read_concepts_for_user_tool and read_misconceptions_for_course_tool) so the
prompt matches the function symbols used at registration.

_PROMPT_HASH = hashlib.sha256(_SYSTEM_PROMPT.encode("utf-8")).hexdigest()[:12]


quiz_agent = Agent[SaplingDeps, Quiz](
model=model_for("quiz"),
deps_type=SaplingDeps,
output_type=Quiz,
system_prompt=_SYSTEM_PROMPT,
metadata={"prompt_version": _PROMPT_HASH, "agent": "quiz"},
tools=[
read_concepts_for_user_tool,
read_misconceptions_for_course_tool,
],
)
163 changes: 163 additions & 0 deletions backend/agents/tools/graph_read.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
"""Read-side graph tools for Pydantic AI agents.

Per ADR 0004: the agent needs to pull mastery state + course-level
misconceptions when planning a quiz. These are the tool surfaces.
The pure-async functions are callable directly from routes;
the *_tool wrappers register on a Pydantic AI Agent.
"""

from __future__ import annotations

import asyncio
import logging
from typing import Any

from pydantic import BaseModel, Field
from pydantic_ai import RunContext

from agents.deps import SaplingDeps
from db.connection import table

logger = logging.getLogger(__name__)


# ── read_concepts_for_user ────────────────────────────────────────────────


class ConceptMastery(BaseModel):
"""Per-concept mastery state for the user in a course."""

concept_name: str
mastery: float = Field(ge=0.0, le=1.0)
last_reviewed_at: str | None = None


async def read_concepts_for_user(
user_id: str,
course_id: str | None,
) -> list[ConceptMastery]:
"""Return the user's concept mastery for a course (or globally if
course_id is None). Sorted by mastery ASC so the weakest concepts
appear first — quiz_agent uses this ordering to focus on weak areas.

Pure async, callable from routes. Wraps the underlying sync
Supabase read in asyncio.to_thread so it doesn't block the loop.

NOTE: The underlying `graph_nodes` table stores the mastery value as
`mastery_score` and the timestamp as `last_studied_at`. We map them
here to the agent-facing names (`mastery`, `last_reviewed_at`) so the
tool contract stays stable even if storage column names change.
"""

def _fetch() -> list[dict[str, Any]]:
filters = {"user_id": f"eq.{user_id}"}
if course_id:
filters["course_id"] = f"eq.{course_id}"
try:
Comment on lines +54 to +56

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Remove the unsupported course_id filter from graph_nodes reads.

On Line 55, filters["course_id"] is added, but the provided schema for graph_nodes (in backend/db/archive/schema.sql:11-22) has no course_id column. That causes the select to fail, then Lines 65-71 swallow it and return [], so weak-concept context is silently lost for course-scoped requests.

🔧 Proposed fix
 def _fetch() -> list[dict[str, Any]]:
filters = {"user_id": f"eq.{user_id}"}
- if course_id:- filters["course_id"] = f"eq.{course_id}"
try:
return (
table("graph_nodes").select(
"concept_name,mastery_score,last_studied_at",
filters=filters,
order="mastery_score.asc",
)
or []
)

Also applies to: 65-71

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@backend/agents/tools/graph_read.py` around lines 54 - 56, Remove the
unsupported course_id filter when querying graph_nodes: delete the line that
sets filters["course_id"] = f"eq.{course_id}" inside the graph_nodes read code
so you don't send a non-existent column to the DB; also stop silently swallowing
the resulting exception in the surrounding try/except (the block that currently
catches errors and returns []), instead let the exception propagate or log and
re-raise so callers know the read failed and course-scoped context isn’t
silently dropped. Reference the filters dict used for graph_nodes reads and the
try/except that returns an empty list to locate the changes.

return (
table("graph_nodes").select(
"concept_name,mastery_score,last_studied_at",
filters=filters,
order="mastery_score.asc",
)
or []
)
except Exception:
logger.exception(
"read_concepts_for_user failed for user=%s course=%s",
user_id,
course_id,
)
return []

rows = await asyncio.to_thread(_fetch)
return [
ConceptMastery(
concept_name=r.get("concept_name") or "",
mastery=float(r.get("mastery_score") or 0.0),
last_reviewed_at=r.get("last_studied_at"),
)
for r in rows
if r.get("concept_name")
]


async def read_concepts_for_user_tool(
ctx: RunContext[SaplingDeps],
) -> list[ConceptMastery]:
"""Pydantic AI tool wrapper. Reads from ctx.deps."""
return await read_concepts_for_user(ctx.deps.user_id, ctx.deps.course_id)


# ── read_misconceptions_for_course ────────────────────────────────────────


class Misconception(BaseModel):
"""A class-level misconception observed across student sessions."""

text: str
related_concept: str | None = None


async def read_misconceptions_for_course(
course_id: str | None,
) -> list[Misconception]:
"""Return aggregated misconception strings for a course. Anonymized
(sourced from class-wide patterns, not from any single student).
Returns [] when course_id is None or the underlying table is empty.

Source: `course_concept_stats` rows for the course. Each row
represents one concept and carries a `common_misconceptions` array
(populated by the hash-gated aggregation in
`services/course_context_service.py`). We flatten each array entry
into its own Misconception, tagging `related_concept` with the
concept name so the agent can route distractors per-concept.

The spec referenced a hypothetical `misconceptions` table — that
table does not exist in this schema. `course_concept_stats` is the
real source of class-wide misconception strings, so we read that.
The tool contract (returning Misconception[]) is unchanged.
"""
if not course_id:
return []

def _fetch() -> list[dict[str, Any]]:
try:
return (
table("course_concept_stats").select(
"concept_name,common_misconceptions",
filters={"course_id": f"eq.{course_id}"},
order="updated_at.desc",
limit=20,
)
or []
)
except Exception:
logger.exception(
"read_misconceptions_for_course failed for course=%s",
course_id,
)
return []

rows = await asyncio.to_thread(_fetch)
out: list[Misconception] = []
seen: set[str] = set()
for r in rows:
concept = r.get("concept_name") or None
for m in r.get("common_misconceptions") or []:
text = (m or "").strip() if isinstance(m, str) else ""
if not text:
continue
key = text.lower()
if key in seen:
continue
seen.add(key)
out.append(Misconception(text=text, related_concept=concept))
return out


async def read_misconceptions_for_course_tool(
ctx: RunContext[SaplingDeps],
) -> list[Misconception]:
"""Pydantic AI tool wrapper. Reads from ctx.deps."""
return await read_misconceptions_for_course(ctx.deps.course_id)
6 changes: 6 additions & 0 deletions backend/models/__init__.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,6 +44,12 @@ class GenerateQuizBody(BaseModel):
num_questions: int = 5
difficulty: str = "medium"
use_shared_context: bool = True
# Mirrors the Learn-route fast/smart toggle so quiz generation has
# the same per-request model-quality choice as chat tutoring.
# "fast" → gemini-2.5-flash, "smart" → gemini-2.5-pro. None falls
# through to whatever SAPLING_MODEL_QUIZ resolves to (default
# gemini-2.5-flash-lite per ADR 0008).
model_pref: Optional[Literal["fast", "smart"]] = None


class AnswerItem(BaseModel):
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' refactor(quiz): convert generate_quiz to quiz_agent (refactor #2) by Jose-Gael-Cruz-Lopez · Pull Request #71 · SaplingLearn/Sapling · GitHub
Skip to content
7 changes: 6 additions & 1 deletion backend/agents/_providers.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@
SAPLING_MODEL_SUMMARY=gemini-2.5-flash-lite
SAPLING_MODEL_CONCEPTS=gemini-2.5-flash
SAPLING_MODEL_SYLLABUS=gemini-2.5-flash
SAPLING_MODEL_QUIZ=gemini-2.5-flash-lite

Defaults are tuned per task: cheaper models for simpler classifications,
flagship Flash for tasks where output quality drives downstream UX.
Expand All@@ -23,7 +24,7 @@
from config import GEMINI_API_KEY


AgentTask = Literal["classifier", "summary", "concepts", "syllabus"]
AgentTask = Literal["classifier", "summary", "concepts", "syllabus", "quiz"]


# Defaults are conservative. Bumping a model up costs more; the env var
Expand All@@ -33,6 +34,10 @@
"summary": "gemini-2.5-flash-lite",
"concepts": "gemini-2.5-flash",
"syllabus": "gemini-2.5-flash",
# Quiz generation defaults to lite: it's a single-shot non-streaming
# call where the agent pulls structured graph data via tools, so the
# bulk of the value is in tool wiring, not raw model strength.
"quiz": "gemini-2.5-flash-lite",
}


Expand Down
111 changes: 111 additions & 0 deletions backend/agents/quiz.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
"""Quiz-generation agent.

Replaces routes/quiz.py:82's call_gemini_json + manual prompt-string
augmentation. The agent has tools to pull weak concepts + class
misconceptions on demand instead of pre-stuffing them into the prompt.

Per ADR 0003 convention 4: keep the output schema compact. Gemini's
structured-output API rejects rich nested schemas with too many states
for serving — Quiz is a flat top-level model with a list of
QuizQuestion items, no further nesting.
"""

from __future__ import annotations

import hashlib
from typing import Literal

from pydantic import BaseModel, Field
from pydantic_ai import Agent

from agents._providers import model_for
from agents.deps import SaplingDeps
from agents.tools.graph_read import (
read_concepts_for_user_tool,
read_misconceptions_for_course_tool,
)


# Difficulty + question type are Literals so Gemini's enum constraint
# applies and downstream UI can branch on stable strings.
#
# `QuizQuestionType` is intentionally MCQ-only today. The frontend
# `submitQuiz` flow grades by `q["options"][i].correct` lookup — there's
# no UI for free-text answers, no fuzzy-match grading, no LLM-judged
# scoring. Generating short-answer questions through this path would
# emit unrenderable, ungradable items. Keep the type narrow until real
# short-answer support exists; revisit when that lands.
QuizDifficulty = Literal["easy", "medium", "hard"]
QuizQuestionType = Literal["multiple_choice"]


class QuizQuestion(BaseModel):
"""A single multiple-choice quiz question. Kept small so the parent
Quiz schema doesn't trip Gemini's structured-output complexity limit."""

question: str = Field(max_length=600)
type: QuizQuestionType
difficulty: QuizDifficulty
# 3-6 options. The agent is required to populate this for every
# question and to make `correct_answer` match exactly one of them.
options: list[str] = Field(min_length=3, max_length=6)
# The option text the agent considers correct. Must appear verbatim
# in `options`; the route validates this and drops questions that
# violate the contract rather than silently mis-marking them.
correct_answer: str = Field(max_length=400)
explanation: str = Field(max_length=600)
# Concept the question is testing — must be one of the user's known
# concept_names per the prompt. Used by the route to award mastery
# on a correct answer.
concept: str = Field(max_length=120)


class Quiz(BaseModel):
"""The agent's structured output."""

questions: list[QuizQuestion] = Field(min_length=1, max_length=20)


_SYSTEM_PROMPT = (
"You generate adaptive multiple-choice quizzes for a student. Each "
"question must target a specific concept the student has weak "
"mastery on, OR address a class-level misconception you've seen.\n\n"
"Workflow:\n"
"1. Call `read_concepts_for_user` to see the student's mastery per "
" concept for this course (returned sorted by mastery ASC — "
" weakest first).\n"
"2. Call `read_misconceptions_for_course` to see anonymized class "
" misconceptions. Use these to phrase distractors and to write "
" a question that probes the misconception.\n"
"3. Compose `Quiz.questions` so the WEAKEST concepts get the most "
" questions, AND each item's `concept` field exactly matches a "
" concept_name returned by tool 1.\n\n"
"Per-question rules (multiple-choice only — the type field is "
"constrained to 'multiple_choice'):\n"
"- 4 options, exactly one correct. The text in `correct_answer` "
" MUST appear verbatim in `options` — character-for-character. "
" Questions that violate this are dropped at the route layer.\n"
"- Distractors should reflect plausible misconceptions, not random "
" noise. Use the read_misconceptions_for_course return value.\n"
"- explanation: 1-3 sentences explaining WHY the correct answer "
" is correct — used in the post-quiz review screen.\n"
"- difficulty: align with the student's mastery on the concept; "
" weakest concepts get easy/medium, strongest get hard.\n\n"
"Honor the requested num_questions and difficulty distribution "
"in the user message. Don't invent concepts the student doesn't "
"have."
)
Comment on lines +69 to +97

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bashset -euo pipefail
# Confirm the exact registered tool names and whether any aliasing is applied.
rg -n --type=py 'def read_concepts_for_user_tool|def read_misconceptions_for_course_tool|read_concepts_for_user\b|read_misconceptions_for_course\b|tools=\[' backend/agents

Repository: SaplingLearn/Sapling

Length of output: 1385


🏁 Script executed:

# Check the tools registration in quiz.py
sed -n '100,130p' backend/agents/quiz.py

Repository: SaplingLearn/Sapling

Length of output: 383


🏁 Script executed:

# Also check if pydantic-ai is imported and how it handles tool names
rg -n "from pydantic_ai|import.*pydantic_ai|agent.*tools" backend/agents/quiz.py -A 2 -B 2

Repository: SaplingLearn/Sapling

Length of output: 568


🏁 Script executed:

# Check pydantic-ai documentation or examples in the codebase for tool naming
rg -n "def.*_tool\(" backend/agents --type=py -B 5 | head -40

Repository: SaplingLearn/Sapling

Length of output: 1084


🏁 Script executed:

# Check if the _tool functions have any decorators or name parameters
rg -n "@|name\s*=" backend/agents/tools/graph_read.py -B 2 -A 8 | grep -A 10 "read_concepts_for_user_tool\|read_misconceptions_for_course_tool"

Repository: SaplingLearn/Sapling

Length of output: 46


🏁 Script executed:

# Search for pydantic_ai documentation or configuration in the codebase
rg -n "pydantic_ai.*tool|Tool.*name|tool.*alias" backend --type=py | head -20

Repository: SaplingLearn/Sapling

Length of output: 46


🌐 Web query:

pydantic-ai tool naming convention function name suffix

💡 Result:

Pydantic AI does not enforce a specific function name suffix or strict naming convention for tools beyond requiring unique tool names within a toolset or agent. The tool name defaults to the Python function name (snake_case convention in examples like 'roll_dice', 'get_player_name', 'customer_balance'), but can be explicitly overridden via the 'name' parameter in decorators (@agent.tool(name='custom_name'), Tool constructor, Tool.from_schema) or toolset methods. ToolDefinition names must be unique to avoid conflicts (raises UserError on duplicates), but no suffix like '_tool' is required or conventional. Use descriptive, unique names that clearly communicate purpose, following Python snake_case for functions.

Citations:


Fix tool name mismatch between prompt and registration.

The prompt instructs the agent to call read_concepts_for_user and read_misconceptions_for_course, but the registered tools are read_concepts_for_user_tool and read_misconceptions_for_course_tool. Pydantic-ai uses the function name directly as the tool name without auto-aliasing suffixes, so the agent will fail to locate these tools when following the prompt instructions.

Either rename the functions to remove the _tool suffix or update the prompt to reference the correct tool names.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@backend/agents/quiz.py` around lines 69 - 97, The system prompt
(_SYSTEM_PROMPT) tells the agent to call read_concepts_for_user and
read_misconceptions_for_course, but the actual registered tool functions are
named read_concepts_for_user_tool and read_misconceptions_for_course_tool, so
the agent will not find the tools; fix by making the names consistent: either
rename the tool functions (read_concepts_for_user_tool -> read_concepts_for_user
and read_misconceptions_for_course_tool -> read_misconceptions_for_course) or
update _SYSTEM_PROMPT to reference the actual registered names
(read_concepts_for_user_tool and read_misconceptions_for_course_tool) so the
prompt matches the function symbols used at registration.

_PROMPT_HASH = hashlib.sha256(_SYSTEM_PROMPT.encode("utf-8")).hexdigest()[:12]


quiz_agent = Agent[SaplingDeps, Quiz](
model=model_for("quiz"),
deps_type=SaplingDeps,
output_type=Quiz,
system_prompt=_SYSTEM_PROMPT,
metadata={"prompt_version": _PROMPT_HASH, "agent": "quiz"},
tools=[
read_concepts_for_user_tool,
read_misconceptions_for_course_tool,
],
)
163 changes: 163 additions & 0 deletions backend/agents/tools/graph_read.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
"""Read-side graph tools for Pydantic AI agents.

Per ADR 0004: the agent needs to pull mastery state + course-level
misconceptions when planning a quiz. These are the tool surfaces.
The pure-async functions are callable directly from routes;
the *_tool wrappers register on a Pydantic AI Agent.
"""

from __future__ import annotations

import asyncio
import logging
from typing import Any

from pydantic import BaseModel, Field
from pydantic_ai import RunContext

from agents.deps import SaplingDeps
from db.connection import table

logger = logging.getLogger(__name__)


# ── read_concepts_for_user ────────────────────────────────────────────────


class ConceptMastery(BaseModel):
"""Per-concept mastery state for the user in a course."""

concept_name: str
mastery: float = Field(ge=0.0, le=1.0)
last_reviewed_at: str | None = None


async def read_concepts_for_user(
user_id: str,
course_id: str | None,
) -> list[ConceptMastery]:
"""Return the user's concept mastery for a course (or globally if
course_id is None). Sorted by mastery ASC so the weakest concepts
appear first — quiz_agent uses this ordering to focus on weak areas.

Pure async, callable from routes. Wraps the underlying sync
Supabase read in asyncio.to_thread so it doesn't block the loop.

NOTE: The underlying `graph_nodes` table stores the mastery value as
`mastery_score` and the timestamp as `last_studied_at`. We map them
here to the agent-facing names (`mastery`, `last_reviewed_at`) so the
tool contract stays stable even if storage column names change.
"""

def _fetch() -> list[dict[str, Any]]:
filters = {"user_id": f"eq.{user_id}"}
if course_id:
filters["course_id"] = f"eq.{course_id}"
try:
Comment on lines +54 to +56

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Remove the unsupported course_id filter from graph_nodes reads.

On Line 55, filters["course_id"] is added, but the provided schema for graph_nodes (in backend/db/archive/schema.sql:11-22) has no course_id column. That causes the select to fail, then Lines 65-71 swallow it and return [], so weak-concept context is silently lost for course-scoped requests.

🔧 Proposed fix
 def _fetch() -> list[dict[str, Any]]:
filters = {"user_id": f"eq.{user_id}"}
- if course_id:- filters["course_id"] = f"eq.{course_id}"
try:
return (
table("graph_nodes").select(
"concept_name,mastery_score,last_studied_at",
filters=filters,
order="mastery_score.asc",
)
or []
)

Also applies to: 65-71

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@backend/agents/tools/graph_read.py` around lines 54 - 56, Remove the
unsupported course_id filter when querying graph_nodes: delete the line that
sets filters["course_id"] = f"eq.{course_id}" inside the graph_nodes read code
so you don't send a non-existent column to the DB; also stop silently swallowing
the resulting exception in the surrounding try/except (the block that currently
catches errors and returns []), instead let the exception propagate or log and
re-raise so callers know the read failed and course-scoped context isn’t
silently dropped. Reference the filters dict used for graph_nodes reads and the
try/except that returns an empty list to locate the changes.

return (
table("graph_nodes").select(
"concept_name,mastery_score,last_studied_at",
filters=filters,
order="mastery_score.asc",
)
or []
)
except Exception:
logger.exception(
"read_concepts_for_user failed for user=%s course=%s",
user_id,
course_id,
)
return []

rows = await asyncio.to_thread(_fetch)
return [
ConceptMastery(
concept_name=r.get("concept_name") or "",
mastery=float(r.get("mastery_score") or 0.0),
last_reviewed_at=r.get("last_studied_at"),
)
for r in rows
if r.get("concept_name")
]


async def read_concepts_for_user_tool(
ctx: RunContext[SaplingDeps],
) -> list[ConceptMastery]:
"""Pydantic AI tool wrapper. Reads from ctx.deps."""
return await read_concepts_for_user(ctx.deps.user_id, ctx.deps.course_id)


# ── read_misconceptions_for_course ────────────────────────────────────────


class Misconception(BaseModel):
"""A class-level misconception observed across student sessions."""

text: str
related_concept: str | None = None


async def read_misconceptions_for_course(
course_id: str | None,
) -> list[Misconception]:
"""Return aggregated misconception strings for a course. Anonymized
(sourced from class-wide patterns, not from any single student).
Returns [] when course_id is None or the underlying table is empty.

Source: `course_concept_stats` rows for the course. Each row
represents one concept and carries a `common_misconceptions` array
(populated by the hash-gated aggregation in
`services/course_context_service.py`). We flatten each array entry
into its own Misconception, tagging `related_concept` with the
concept name so the agent can route distractors per-concept.

The spec referenced a hypothetical `misconceptions` table — that
table does not exist in this schema. `course_concept_stats` is the
real source of class-wide misconception strings, so we read that.
The tool contract (returning Misconception[]) is unchanged.
"""
if not course_id:
return []

def _fetch() -> list[dict[str, Any]]:
try:
return (
table("course_concept_stats").select(
"concept_name,common_misconceptions",
filters={"course_id": f"eq.{course_id}"},
order="updated_at.desc",
limit=20,
)
or []
)
except Exception:
logger.exception(
"read_misconceptions_for_course failed for course=%s",
course_id,
)
return []

rows = await asyncio.to_thread(_fetch)
out: list[Misconception] = []
seen: set[str] = set()
for r in rows:
concept = r.get("concept_name") or None
for m in r.get("common_misconceptions") or []:
text = (m or "").strip() if isinstance(m, str) else ""
if not text:
continue
key = text.lower()
if key in seen:
continue
seen.add(key)
out.append(Misconception(text=text, related_concept=concept))
return out


async def read_misconceptions_for_course_tool(
ctx: RunContext[SaplingDeps],
) -> list[Misconception]:
"""Pydantic AI tool wrapper. Reads from ctx.deps."""
return await read_misconceptions_for_course(ctx.deps.course_id)
6 changes: 6 additions & 0 deletions backend/models/__init__.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,6 +44,12 @@ class GenerateQuizBody(BaseModel):
num_questions: int = 5
difficulty: str = "medium"
use_shared_context: bool = True
# Mirrors the Learn-route fast/smart toggle so quiz generation has
# the same per-request model-quality choice as chat tutoring.
# "fast" → gemini-2.5-flash, "smart" → gemini-2.5-pro. None falls
# through to whatever SAPLING_MODEL_QUIZ resolves to (default
# gemini-2.5-flash-lite per ADR 0008).
model_pref: Optional[Literal["fast", "smart"]] = None


class AnswerItem(BaseModel):
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' refactor(quiz): convert generate_quiz to quiz_agent (refactor #2) by Jose-Gael-Cruz-Lopez · Pull Request #71 · SaplingLearn/Sapling · GitHub
Skip to content
7 changes: 6 additions & 1 deletion backend/agents/_providers.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@
SAPLING_MODEL_SUMMARY=gemini-2.5-flash-lite
SAPLING_MODEL_CONCEPTS=gemini-2.5-flash
SAPLING_MODEL_SYLLABUS=gemini-2.5-flash
SAPLING_MODEL_QUIZ=gemini-2.5-flash-lite

Defaults are tuned per task: cheaper models for simpler classifications,
flagship Flash for tasks where output quality drives downstream UX.
Expand All@@ -23,7 +24,7 @@
from config import GEMINI_API_KEY


AgentTask = Literal["classifier", "summary", "concepts", "syllabus"]
AgentTask = Literal["classifier", "summary", "concepts", "syllabus", "quiz"]


# Defaults are conservative. Bumping a model up costs more; the env var
Expand All@@ -33,6 +34,10 @@
"summary": "gemini-2.5-flash-lite",
"concepts": "gemini-2.5-flash",
"syllabus": "gemini-2.5-flash",
# Quiz generation defaults to lite: it's a single-shot non-streaming
# call where the agent pulls structured graph data via tools, so the
# bulk of the value is in tool wiring, not raw model strength.
"quiz": "gemini-2.5-flash-lite",
}


Expand Down
111 changes: 111 additions & 0 deletions backend/agents/quiz.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
"""Quiz-generation agent.

Replaces routes/quiz.py:82's call_gemini_json + manual prompt-string
augmentation. The agent has tools to pull weak concepts + class
misconceptions on demand instead of pre-stuffing them into the prompt.

Per ADR 0003 convention 4: keep the output schema compact. Gemini's
structured-output API rejects rich nested schemas with too many states
for serving — Quiz is a flat top-level model with a list of
QuizQuestion items, no further nesting.
"""

from __future__ import annotations

import hashlib
from typing import Literal

from pydantic import BaseModel, Field
from pydantic_ai import Agent

from agents._providers import model_for
from agents.deps import SaplingDeps
from agents.tools.graph_read import (
read_concepts_for_user_tool,
read_misconceptions_for_course_tool,
)


# Difficulty + question type are Literals so Gemini's enum constraint
# applies and downstream UI can branch on stable strings.
#
# `QuizQuestionType` is intentionally MCQ-only today. The frontend
# `submitQuiz` flow grades by `q["options"][i].correct` lookup — there's
# no UI for free-text answers, no fuzzy-match grading, no LLM-judged
# scoring. Generating short-answer questions through this path would
# emit unrenderable, ungradable items. Keep the type narrow until real
# short-answer support exists; revisit when that lands.
QuizDifficulty = Literal["easy", "medium", "hard"]
QuizQuestionType = Literal["multiple_choice"]


class QuizQuestion(BaseModel):
"""A single multiple-choice quiz question. Kept small so the parent
Quiz schema doesn't trip Gemini's structured-output complexity limit."""

question: str = Field(max_length=600)
type: QuizQuestionType
difficulty: QuizDifficulty
# 3-6 options. The agent is required to populate this for every
# question and to make `correct_answer` match exactly one of them.
options: list[str] = Field(min_length=3, max_length=6)
# The option text the agent considers correct. Must appear verbatim
# in `options`; the route validates this and drops questions that
# violate the contract rather than silently mis-marking them.
correct_answer: str = Field(max_length=400)
explanation: str = Field(max_length=600)
# Concept the question is testing — must be one of the user's known
# concept_names per the prompt. Used by the route to award mastery
# on a correct answer.
concept: str = Field(max_length=120)


class Quiz(BaseModel):
"""The agent's structured output."""

questions: list[QuizQuestion] = Field(min_length=1, max_length=20)


_SYSTEM_PROMPT = (
"You generate adaptive multiple-choice quizzes for a student. Each "
"question must target a specific concept the student has weak "
"mastery on, OR address a class-level misconception you've seen.\n\n"
"Workflow:\n"
"1. Call `read_concepts_for_user` to see the student's mastery per "
" concept for this course (returned sorted by mastery ASC — "
" weakest first).\n"
"2. Call `read_misconceptions_for_course` to see anonymized class "
" misconceptions. Use these to phrase distractors and to write "
" a question that probes the misconception.\n"
"3. Compose `Quiz.questions` so the WEAKEST concepts get the most "
" questions, AND each item's `concept` field exactly matches a "
" concept_name returned by tool 1.\n\n"
"Per-question rules (multiple-choice only — the type field is "
"constrained to 'multiple_choice'):\n"
"- 4 options, exactly one correct. The text in `correct_answer` "
" MUST appear verbatim in `options` — character-for-character. "
" Questions that violate this are dropped at the route layer.\n"
"- Distractors should reflect plausible misconceptions, not random "
" noise. Use the read_misconceptions_for_course return value.\n"
"- explanation: 1-3 sentences explaining WHY the correct answer "
" is correct — used in the post-quiz review screen.\n"
"- difficulty: align with the student's mastery on the concept; "
" weakest concepts get easy/medium, strongest get hard.\n\n"
"Honor the requested num_questions and difficulty distribution "
"in the user message. Don't invent concepts the student doesn't "
"have."
)
Comment on lines +69 to +97

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bashset -euo pipefail
# Confirm the exact registered tool names and whether any aliasing is applied.
rg -n --type=py 'def read_concepts_for_user_tool|def read_misconceptions_for_course_tool|read_concepts_for_user\b|read_misconceptions_for_course\b|tools=\[' backend/agents

Repository: SaplingLearn/Sapling

Length of output: 1385


🏁 Script executed:

# Check the tools registration in quiz.py
sed -n '100,130p' backend/agents/quiz.py

Repository: SaplingLearn/Sapling

Length of output: 383


🏁 Script executed:

# Also check if pydantic-ai is imported and how it handles tool names
rg -n "from pydantic_ai|import.*pydantic_ai|agent.*tools" backend/agents/quiz.py -A 2 -B 2

Repository: SaplingLearn/Sapling

Length of output: 568


🏁 Script executed:

# Check pydantic-ai documentation or examples in the codebase for tool naming
rg -n "def.*_tool\(" backend/agents --type=py -B 5 | head -40

Repository: SaplingLearn/Sapling

Length of output: 1084


🏁 Script executed:

# Check if the _tool functions have any decorators or name parameters
rg -n "@|name\s*=" backend/agents/tools/graph_read.py -B 2 -A 8 | grep -A 10 "read_concepts_for_user_tool\|read_misconceptions_for_course_tool"

Repository: SaplingLearn/Sapling

Length of output: 46


🏁 Script executed:

# Search for pydantic_ai documentation or configuration in the codebase
rg -n "pydantic_ai.*tool|Tool.*name|tool.*alias" backend --type=py | head -20

Repository: SaplingLearn/Sapling

Length of output: 46


🌐 Web query:

pydantic-ai tool naming convention function name suffix

💡 Result:

Pydantic AI does not enforce a specific function name suffix or strict naming convention for tools beyond requiring unique tool names within a toolset or agent. The tool name defaults to the Python function name (snake_case convention in examples like 'roll_dice', 'get_player_name', 'customer_balance'), but can be explicitly overridden via the 'name' parameter in decorators (@agent.tool(name='custom_name'), Tool constructor, Tool.from_schema) or toolset methods. ToolDefinition names must be unique to avoid conflicts (raises UserError on duplicates), but no suffix like '_tool' is required or conventional. Use descriptive, unique names that clearly communicate purpose, following Python snake_case for functions.

Citations:


Fix tool name mismatch between prompt and registration.

The prompt instructs the agent to call read_concepts_for_user and read_misconceptions_for_course, but the registered tools are read_concepts_for_user_tool and read_misconceptions_for_course_tool. Pydantic-ai uses the function name directly as the tool name without auto-aliasing suffixes, so the agent will fail to locate these tools when following the prompt instructions.

Either rename the functions to remove the _tool suffix or update the prompt to reference the correct tool names.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@backend/agents/quiz.py` around lines 69 - 97, The system prompt
(_SYSTEM_PROMPT) tells the agent to call read_concepts_for_user and
read_misconceptions_for_course, but the actual registered tool functions are
named read_concepts_for_user_tool and read_misconceptions_for_course_tool, so
the agent will not find the tools; fix by making the names consistent: either
rename the tool functions (read_concepts_for_user_tool -> read_concepts_for_user
and read_misconceptions_for_course_tool -> read_misconceptions_for_course) or
update _SYSTEM_PROMPT to reference the actual registered names
(read_concepts_for_user_tool and read_misconceptions_for_course_tool) so the
prompt matches the function symbols used at registration.

_PROMPT_HASH = hashlib.sha256(_SYSTEM_PROMPT.encode("utf-8")).hexdigest()[:12]


quiz_agent = Agent[SaplingDeps, Quiz](
model=model_for("quiz"),
deps_type=SaplingDeps,
output_type=Quiz,
system_prompt=_SYSTEM_PROMPT,
metadata={"prompt_version": _PROMPT_HASH, "agent": "quiz"},
tools=[
read_concepts_for_user_tool,
read_misconceptions_for_course_tool,
],
)
163 changes: 163 additions & 0 deletions backend/agents/tools/graph_read.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
"""Read-side graph tools for Pydantic AI agents.

Per ADR 0004: the agent needs to pull mastery state + course-level
misconceptions when planning a quiz. These are the tool surfaces.
The pure-async functions are callable directly from routes;
the *_tool wrappers register on a Pydantic AI Agent.
"""

from __future__ import annotations

import asyncio
import logging
from typing import Any

from pydantic import BaseModel, Field
from pydantic_ai import RunContext

from agents.deps import SaplingDeps
from db.connection import table

logger = logging.getLogger(__name__)


# ── read_concepts_for_user ────────────────────────────────────────────────


class ConceptMastery(BaseModel):
"""Per-concept mastery state for the user in a course."""

concept_name: str
mastery: float = Field(ge=0.0, le=1.0)
last_reviewed_at: str | None = None


async def read_concepts_for_user(
user_id: str,
course_id: str | None,
) -> list[ConceptMastery]:
"""Return the user's concept mastery for a course (or globally if
course_id is None). Sorted by mastery ASC so the weakest concepts
appear first — quiz_agent uses this ordering to focus on weak areas.

Pure async, callable from routes. Wraps the underlying sync
Supabase read in asyncio.to_thread so it doesn't block the loop.

NOTE: The underlying `graph_nodes` table stores the mastery value as
`mastery_score` and the timestamp as `last_studied_at`. We map them
here to the agent-facing names (`mastery`, `last_reviewed_at`) so the
tool contract stays stable even if storage column names change.
"""

def _fetch() -> list[dict[str, Any]]:
filters = {"user_id": f"eq.{user_id}"}
if course_id:
filters["course_id"] = f"eq.{course_id}"
try:
Comment on lines +54 to +56

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Remove the unsupported course_id filter from graph_nodes reads.

On Line 55, filters["course_id"] is added, but the provided schema for graph_nodes (in backend/db/archive/schema.sql:11-22) has no course_id column. That causes the select to fail, then Lines 65-71 swallow it and return [], so weak-concept context is silently lost for course-scoped requests.

🔧 Proposed fix
 def _fetch() -> list[dict[str, Any]]:
filters = {"user_id": f"eq.{user_id}"}
- if course_id:- filters["course_id"] = f"eq.{course_id}"
try:
return (
table("graph_nodes").select(
"concept_name,mastery_score,last_studied_at",
filters=filters,
order="mastery_score.asc",
)
or []
)

Also applies to: 65-71

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@backend/agents/tools/graph_read.py` around lines 54 - 56, Remove the
unsupported course_id filter when querying graph_nodes: delete the line that
sets filters["course_id"] = f"eq.{course_id}" inside the graph_nodes read code
so you don't send a non-existent column to the DB; also stop silently swallowing
the resulting exception in the surrounding try/except (the block that currently
catches errors and returns []), instead let the exception propagate or log and
re-raise so callers know the read failed and course-scoped context isn’t
silently dropped. Reference the filters dict used for graph_nodes reads and the
try/except that returns an empty list to locate the changes.

return (
table("graph_nodes").select(
"concept_name,mastery_score,last_studied_at",
filters=filters,
order="mastery_score.asc",
)
or []
)
except Exception:
logger.exception(
"read_concepts_for_user failed for user=%s course=%s",
user_id,
course_id,
)
return []

rows = await asyncio.to_thread(_fetch)
return [
ConceptMastery(
concept_name=r.get("concept_name") or "",
mastery=float(r.get("mastery_score") or 0.0),
last_reviewed_at=r.get("last_studied_at"),
)
for r in rows
if r.get("concept_name")
]


async def read_concepts_for_user_tool(
ctx: RunContext[SaplingDeps],
) -> list[ConceptMastery]:
"""Pydantic AI tool wrapper. Reads from ctx.deps."""
return await read_concepts_for_user(ctx.deps.user_id, ctx.deps.course_id)


# ── read_misconceptions_for_course ────────────────────────────────────────


class Misconception(BaseModel):
"""A class-level misconception observed across student sessions."""

text: str
related_concept: str | None = None


async def read_misconceptions_for_course(
course_id: str | None,
) -> list[Misconception]:
"""Return aggregated misconception strings for a course. Anonymized
(sourced from class-wide patterns, not from any single student).
Returns [] when course_id is None or the underlying table is empty.

Source: `course_concept_stats` rows for the course. Each row
represents one concept and carries a `common_misconceptions` array
(populated by the hash-gated aggregation in
`services/course_context_service.py`). We flatten each array entry
into its own Misconception, tagging `related_concept` with the
concept name so the agent can route distractors per-concept.

The spec referenced a hypothetical `misconceptions` table — that
table does not exist in this schema. `course_concept_stats` is the
real source of class-wide misconception strings, so we read that.
The tool contract (returning Misconception[]) is unchanged.
"""
if not course_id:
return []

def _fetch() -> list[dict[str, Any]]:
try:
return (
table("course_concept_stats").select(
"concept_name,common_misconceptions",
filters={"course_id": f"eq.{course_id}"},
order="updated_at.desc",
limit=20,
)
or []
)
except Exception:
logger.exception(
"read_misconceptions_for_course failed for course=%s",
course_id,
)
return []

rows = await asyncio.to_thread(_fetch)
out: list[Misconception] = []
seen: set[str] = set()
for r in rows:
concept = r.get("concept_name") or None
for m in r.get("common_misconceptions") or []:
text = (m or "").strip() if isinstance(m, str) else ""
if not text:
continue
key = text.lower()
if key in seen:
continue
seen.add(key)
out.append(Misconception(text=text, related_concept=concept))
return out


async def read_misconceptions_for_course_tool(
ctx: RunContext[SaplingDeps],
) -> list[Misconception]:
"""Pydantic AI tool wrapper. Reads from ctx.deps."""
return await read_misconceptions_for_course(ctx.deps.course_id)
6 changes: 6 additions & 0 deletions backend/models/__init__.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,6 +44,12 @@ class GenerateQuizBody(BaseModel):
num_questions: int = 5
difficulty: str = "medium"
use_shared_context: bool = True
# Mirrors the Learn-route fast/smart toggle so quiz generation has
# the same per-request model-quality choice as chat tutoring.
# "fast" → gemini-2.5-flash, "smart" → gemini-2.5-pro. None falls
# through to whatever SAPLING_MODEL_QUIZ resolves to (default
# gemini-2.5-flash-lite per ADR 0008).
model_pref: Optional[Literal["fast", "smart"]] = None


class AnswerItem(BaseModel):
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' refactor(quiz): convert generate_quiz to quiz_agent (refactor #2) by Jose-Gael-Cruz-Lopez · Pull Request #71 · SaplingLearn/Sapling · GitHub
Skip to content
7 changes: 6 additions & 1 deletion backend/agents/_providers.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@
SAPLING_MODEL_SUMMARY=gemini-2.5-flash-lite
SAPLING_MODEL_CONCEPTS=gemini-2.5-flash
SAPLING_MODEL_SYLLABUS=gemini-2.5-flash
SAPLING_MODEL_QUIZ=gemini-2.5-flash-lite

Defaults are tuned per task: cheaper models for simpler classifications,
flagship Flash for tasks where output quality drives downstream UX.
Expand All@@ -23,7 +24,7 @@
from config import GEMINI_API_KEY


AgentTask = Literal["classifier", "summary", "concepts", "syllabus"]
AgentTask = Literal["classifier", "summary", "concepts", "syllabus", "quiz"]


# Defaults are conservative. Bumping a model up costs more; the env var
Expand All@@ -33,6 +34,10 @@
"summary": "gemini-2.5-flash-lite",
"concepts": "gemini-2.5-flash",
"syllabus": "gemini-2.5-flash",
# Quiz generation defaults to lite: it's a single-shot non-streaming
# call where the agent pulls structured graph data via tools, so the
# bulk of the value is in tool wiring, not raw model strength.
"quiz": "gemini-2.5-flash-lite",
}


Expand Down
111 changes: 111 additions & 0 deletions backend/agents/quiz.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
"""Quiz-generation agent.

Replaces routes/quiz.py:82's call_gemini_json + manual prompt-string
augmentation. The agent has tools to pull weak concepts + class
misconceptions on demand instead of pre-stuffing them into the prompt.

Per ADR 0003 convention 4: keep the output schema compact. Gemini's
structured-output API rejects rich nested schemas with too many states
for serving — Quiz is a flat top-level model with a list of
QuizQuestion items, no further nesting.
"""

from __future__ import annotations

import hashlib
from typing import Literal

from pydantic import BaseModel, Field
from pydantic_ai import Agent

from agents._providers import model_for
from agents.deps import SaplingDeps
from agents.tools.graph_read import (
read_concepts_for_user_tool,
read_misconceptions_for_course_tool,
)


# Difficulty + question type are Literals so Gemini's enum constraint
# applies and downstream UI can branch on stable strings.
#
# `QuizQuestionType` is intentionally MCQ-only today. The frontend
# `submitQuiz` flow grades by `q["options"][i].correct` lookup — there's
# no UI for free-text answers, no fuzzy-match grading, no LLM-judged
# scoring. Generating short-answer questions through this path would
# emit unrenderable, ungradable items. Keep the type narrow until real
# short-answer support exists; revisit when that lands.
QuizDifficulty = Literal["easy", "medium", "hard"]
QuizQuestionType = Literal["multiple_choice"]


class QuizQuestion(BaseModel):
"""A single multiple-choice quiz question. Kept small so the parent
Quiz schema doesn't trip Gemini's structured-output complexity limit."""

question: str = Field(max_length=600)
type: QuizQuestionType
difficulty: QuizDifficulty
# 3-6 options. The agent is required to populate this for every
# question and to make `correct_answer` match exactly one of them.
options: list[str] = Field(min_length=3, max_length=6)
# The option text the agent considers correct. Must appear verbatim
# in `options`; the route validates this and drops questions that
# violate the contract rather than silently mis-marking them.
correct_answer: str = Field(max_length=400)
explanation: str = Field(max_length=600)
# Concept the question is testing — must be one of the user's known
# concept_names per the prompt. Used by the route to award mastery
# on a correct answer.
concept: str = Field(max_length=120)


class Quiz(BaseModel):
"""The agent's structured output."""

questions: list[QuizQuestion] = Field(min_length=1, max_length=20)


_SYSTEM_PROMPT = (
"You generate adaptive multiple-choice quizzes for a student. Each "
"question must target a specific concept the student has weak "
"mastery on, OR address a class-level misconception you've seen.\n\n"
"Workflow:\n"
"1. Call `read_concepts_for_user` to see the student's mastery per "
" concept for this course (returned sorted by mastery ASC — "
" weakest first).\n"
"2. Call `read_misconceptions_for_course` to see anonymized class "
" misconceptions. Use these to phrase distractors and to write "
" a question that probes the misconception.\n"
"3. Compose `Quiz.questions` so the WEAKEST concepts get the most "
" questions, AND each item's `concept` field exactly matches a "
" concept_name returned by tool 1.\n\n"
"Per-question rules (multiple-choice only — the type field is "
"constrained to 'multiple_choice'):\n"
"- 4 options, exactly one correct. The text in `correct_answer` "
" MUST appear verbatim in `options` — character-for-character. "
" Questions that violate this are dropped at the route layer.\n"
"- Distractors should reflect plausible misconceptions, not random "
" noise. Use the read_misconceptions_for_course return value.\n"
"- explanation: 1-3 sentences explaining WHY the correct answer "
" is correct — used in the post-quiz review screen.\n"
"- difficulty: align with the student's mastery on the concept; "
" weakest concepts get easy/medium, strongest get hard.\n\n"
"Honor the requested num_questions and difficulty distribution "
"in the user message. Don't invent concepts the student doesn't "
"have."
)
Comment on lines +69 to +97

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bashset -euo pipefail
# Confirm the exact registered tool names and whether any aliasing is applied.
rg -n --type=py 'def read_concepts_for_user_tool|def read_misconceptions_for_course_tool|read_concepts_for_user\b|read_misconceptions_for_course\b|tools=\[' backend/agents

Repository: SaplingLearn/Sapling

Length of output: 1385


🏁 Script executed:

# Check the tools registration in quiz.py
sed -n '100,130p' backend/agents/quiz.py

Repository: SaplingLearn/Sapling

Length of output: 383


🏁 Script executed:

# Also check if pydantic-ai is imported and how it handles tool names
rg -n "from pydantic_ai|import.*pydantic_ai|agent.*tools" backend/agents/quiz.py -A 2 -B 2

Repository: SaplingLearn/Sapling

Length of output: 568


🏁 Script executed:

# Check pydantic-ai documentation or examples in the codebase for tool naming
rg -n "def.*_tool\(" backend/agents --type=py -B 5 | head -40

Repository: SaplingLearn/Sapling

Length of output: 1084


🏁 Script executed:

# Check if the _tool functions have any decorators or name parameters
rg -n "@|name\s*=" backend/agents/tools/graph_read.py -B 2 -A 8 | grep -A 10 "read_concepts_for_user_tool\|read_misconceptions_for_course_tool"

Repository: SaplingLearn/Sapling

Length of output: 46


🏁 Script executed:

# Search for pydantic_ai documentation or configuration in the codebase
rg -n "pydantic_ai.*tool|Tool.*name|tool.*alias" backend --type=py | head -20

Repository: SaplingLearn/Sapling

Length of output: 46


🌐 Web query:

pydantic-ai tool naming convention function name suffix

💡 Result:

Pydantic AI does not enforce a specific function name suffix or strict naming convention for tools beyond requiring unique tool names within a toolset or agent. The tool name defaults to the Python function name (snake_case convention in examples like 'roll_dice', 'get_player_name', 'customer_balance'), but can be explicitly overridden via the 'name' parameter in decorators (@agent.tool(name='custom_name'), Tool constructor, Tool.from_schema) or toolset methods. ToolDefinition names must be unique to avoid conflicts (raises UserError on duplicates), but no suffix like '_tool' is required or conventional. Use descriptive, unique names that clearly communicate purpose, following Python snake_case for functions.

Citations:


Fix tool name mismatch between prompt and registration.

The prompt instructs the agent to call read_concepts_for_user and read_misconceptions_for_course, but the registered tools are read_concepts_for_user_tool and read_misconceptions_for_course_tool. Pydantic-ai uses the function name directly as the tool name without auto-aliasing suffixes, so the agent will fail to locate these tools when following the prompt instructions.

Either rename the functions to remove the _tool suffix or update the prompt to reference the correct tool names.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@backend/agents/quiz.py` around lines 69 - 97, The system prompt
(_SYSTEM_PROMPT) tells the agent to call read_concepts_for_user and
read_misconceptions_for_course, but the actual registered tool functions are
named read_concepts_for_user_tool and read_misconceptions_for_course_tool, so
the agent will not find the tools; fix by making the names consistent: either
rename the tool functions (read_concepts_for_user_tool -> read_concepts_for_user
and read_misconceptions_for_course_tool -> read_misconceptions_for_course) or
update _SYSTEM_PROMPT to reference the actual registered names
(read_concepts_for_user_tool and read_misconceptions_for_course_tool) so the
prompt matches the function symbols used at registration.

_PROMPT_HASH = hashlib.sha256(_SYSTEM_PROMPT.encode("utf-8")).hexdigest()[:12]


quiz_agent = Agent[SaplingDeps, Quiz](
model=model_for("quiz"),
deps_type=SaplingDeps,
output_type=Quiz,
system_prompt=_SYSTEM_PROMPT,
metadata={"prompt_version": _PROMPT_HASH, "agent": "quiz"},
tools=[
read_concepts_for_user_tool,
read_misconceptions_for_course_tool,
],
)
163 changes: 163 additions & 0 deletions backend/agents/tools/graph_read.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
"""Read-side graph tools for Pydantic AI agents.

Per ADR 0004: the agent needs to pull mastery state + course-level
misconceptions when planning a quiz. These are the tool surfaces.
The pure-async functions are callable directly from routes;
the *_tool wrappers register on a Pydantic AI Agent.
"""

from __future__ import annotations

import asyncio
import logging
from typing import Any

from pydantic import BaseModel, Field
from pydantic_ai import RunContext

from agents.deps import SaplingDeps
from db.connection import table

logger = logging.getLogger(__name__)


# ── read_concepts_for_user ────────────────────────────────────────────────


class ConceptMastery(BaseModel):
"""Per-concept mastery state for the user in a course."""

concept_name: str
mastery: float = Field(ge=0.0, le=1.0)
last_reviewed_at: str | None = None


async def read_concepts_for_user(
user_id: str,
course_id: str | None,
) -> list[ConceptMastery]:
"""Return the user's concept mastery for a course (or globally if
course_id is None). Sorted by mastery ASC so the weakest concepts
appear first — quiz_agent uses this ordering to focus on weak areas.

Pure async, callable from routes. Wraps the underlying sync
Supabase read in asyncio.to_thread so it doesn't block the loop.

NOTE: The underlying `graph_nodes` table stores the mastery value as
`mastery_score` and the timestamp as `last_studied_at`. We map them
here to the agent-facing names (`mastery`, `last_reviewed_at`) so the
tool contract stays stable even if storage column names change.
"""

def _fetch() -> list[dict[str, Any]]:
filters = {"user_id": f"eq.{user_id}"}
if course_id:
filters["course_id"] = f"eq.{course_id}"
try:
Comment on lines +54 to +56

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Remove the unsupported course_id filter from graph_nodes reads.

On Line 55, filters["course_id"] is added, but the provided schema for graph_nodes (in backend/db/archive/schema.sql:11-22) has no course_id column. That causes the select to fail, then Lines 65-71 swallow it and return [], so weak-concept context is silently lost for course-scoped requests.

🔧 Proposed fix
 def _fetch() -> list[dict[str, Any]]:
filters = {"user_id": f"eq.{user_id}"}
- if course_id:- filters["course_id"] = f"eq.{course_id}"
try:
return (
table("graph_nodes").select(
"concept_name,mastery_score,last_studied_at",
filters=filters,
order="mastery_score.asc",
)
or []
)

Also applies to: 65-71

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@backend/agents/tools/graph_read.py` around lines 54 - 56, Remove the
unsupported course_id filter when querying graph_nodes: delete the line that
sets filters["course_id"] = f"eq.{course_id}" inside the graph_nodes read code
so you don't send a non-existent column to the DB; also stop silently swallowing
the resulting exception in the surrounding try/except (the block that currently
catches errors and returns []), instead let the exception propagate or log and
re-raise so callers know the read failed and course-scoped context isn’t
silently dropped. Reference the filters dict used for graph_nodes reads and the
try/except that returns an empty list to locate the changes.

return (
table("graph_nodes").select(
"concept_name,mastery_score,last_studied_at",
filters=filters,
order="mastery_score.asc",
)
or []
)
except Exception:
logger.exception(
"read_concepts_for_user failed for user=%s course=%s",
user_id,
course_id,
)
return []

rows = await asyncio.to_thread(_fetch)
return [
ConceptMastery(
concept_name=r.get("concept_name") or "",
mastery=float(r.get("mastery_score") or 0.0),
last_reviewed_at=r.get("last_studied_at"),
)
for r in rows
if r.get("concept_name")
]


async def read_concepts_for_user_tool(
ctx: RunContext[SaplingDeps],
) -> list[ConceptMastery]:
"""Pydantic AI tool wrapper. Reads from ctx.deps."""
return await read_concepts_for_user(ctx.deps.user_id, ctx.deps.course_id)


# ── read_misconceptions_for_course ────────────────────────────────────────


class Misconception(BaseModel):
"""A class-level misconception observed across student sessions."""

text: str
related_concept: str | None = None


async def read_misconceptions_for_course(
course_id: str | None,
) -> list[Misconception]:
"""Return aggregated misconception strings for a course. Anonymized
(sourced from class-wide patterns, not from any single student).
Returns [] when course_id is None or the underlying table is empty.

Source: `course_concept_stats` rows for the course. Each row
represents one concept and carries a `common_misconceptions` array
(populated by the hash-gated aggregation in
`services/course_context_service.py`). We flatten each array entry
into its own Misconception, tagging `related_concept` with the
concept name so the agent can route distractors per-concept.

The spec referenced a hypothetical `misconceptions` table — that
table does not exist in this schema. `course_concept_stats` is the
real source of class-wide misconception strings, so we read that.
The tool contract (returning Misconception[]) is unchanged.
"""
if not course_id:
return []

def _fetch() -> list[dict[str, Any]]:
try:
return (
table("course_concept_stats").select(
"concept_name,common_misconceptions",
filters={"course_id": f"eq.{course_id}"},
order="updated_at.desc",
limit=20,
)
or []
)
except Exception:
logger.exception(
"read_misconceptions_for_course failed for course=%s",
course_id,
)
return []

rows = await asyncio.to_thread(_fetch)
out: list[Misconception] = []
seen: set[str] = set()
for r in rows:
concept = r.get("concept_name") or None
for m in r.get("common_misconceptions") or []:
text = (m or "").strip() if isinstance(m, str) else ""
if not text:
continue
key = text.lower()
if key in seen:
continue
seen.add(key)
out.append(Misconception(text=text, related_concept=concept))
return out


async def read_misconceptions_for_course_tool(
ctx: RunContext[SaplingDeps],
) -> list[Misconception]:
"""Pydantic AI tool wrapper. Reads from ctx.deps."""
return await read_misconceptions_for_course(ctx.deps.course_id)
6 changes: 6 additions & 0 deletions backend/models/__init__.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,6 +44,12 @@ class GenerateQuizBody(BaseModel):
num_questions: int = 5
difficulty: str = "medium"
use_shared_context: bool = True
# Mirrors the Learn-route fast/smart toggle so quiz generation has
# the same per-request model-quality choice as chat tutoring.
# "fast" → gemini-2.5-flash, "smart" → gemini-2.5-pro. None falls
# through to whatever SAPLING_MODEL_QUIZ resolves to (default
# gemini-2.5-flash-lite per ADR 0008).
model_pref: Optional[Literal["fast", "smart"]] = None


class AnswerItem(BaseModel):
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); refactor(quiz): convert generate_quiz to quiz_agent (refactor #2) by Jose-Gael-Cruz-Lopez · Pull Request #71 · SaplingLearn/Sapling · GitHub
Skip to content
7 changes: 6 additions & 1 deletion backend/agents/_providers.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@
SAPLING_MODEL_SUMMARY=gemini-2.5-flash-lite
SAPLING_MODEL_CONCEPTS=gemini-2.5-flash
SAPLING_MODEL_SYLLABUS=gemini-2.5-flash
SAPLING_MODEL_QUIZ=gemini-2.5-flash-lite

Defaults are tuned per task: cheaper models for simpler classifications,
flagship Flash for tasks where output quality drives downstream UX.
Expand All@@ -23,7 +24,7 @@
from config import GEMINI_API_KEY


AgentTask = Literal["classifier", "summary", "concepts", "syllabus"]
AgentTask = Literal["classifier", "summary", "concepts", "syllabus", "quiz"]


# Defaults are conservative. Bumping a model up costs more; the env var
Expand All@@ -33,6 +34,10 @@
"summary": "gemini-2.5-flash-lite",
"concepts": "gemini-2.5-flash",
"syllabus": "gemini-2.5-flash",
# Quiz generation defaults to lite: it's a single-shot non-streaming
# call where the agent pulls structured graph data via tools, so the
# bulk of the value is in tool wiring, not raw model strength.
"quiz": "gemini-2.5-flash-lite",
}


Expand Down
111 changes: 111 additions & 0 deletions backend/agents/quiz.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
"""Quiz-generation agent.

Replaces routes/quiz.py:82's call_gemini_json + manual prompt-string
augmentation. The agent has tools to pull weak concepts + class
misconceptions on demand instead of pre-stuffing them into the prompt.

Per ADR 0003 convention 4: keep the output schema compact. Gemini's
structured-output API rejects rich nested schemas with too many states
for serving — Quiz is a flat top-level model with a list of
QuizQuestion items, no further nesting.
"""

from __future__ import annotations

import hashlib
from typing import Literal

from pydantic import BaseModel, Field
from pydantic_ai import Agent

from agents._providers import model_for
from agents.deps import SaplingDeps
from agents.tools.graph_read import (
read_concepts_for_user_tool,
read_misconceptions_for_course_tool,
)


# Difficulty + question type are Literals so Gemini's enum constraint
# applies and downstream UI can branch on stable strings.
#
# `QuizQuestionType` is intentionally MCQ-only today. The frontend
# `submitQuiz` flow grades by `q["options"][i].correct` lookup — there's
# no UI for free-text answers, no fuzzy-match grading, no LLM-judged
# scoring. Generating short-answer questions through this path would
# emit unrenderable, ungradable items. Keep the type narrow until real
# short-answer support exists; revisit when that lands.
QuizDifficulty = Literal["easy", "medium", "hard"]
QuizQuestionType = Literal["multiple_choice"]


class QuizQuestion(BaseModel):
"""A single multiple-choice quiz question. Kept small so the parent
Quiz schema doesn't trip Gemini's structured-output complexity limit."""

question: str = Field(max_length=600)
type: QuizQuestionType
difficulty: QuizDifficulty
# 3-6 options. The agent is required to populate this for every
# question and to make `correct_answer` match exactly one of them.
options: list[str] = Field(min_length=3, max_length=6)
# The option text the agent considers correct. Must appear verbatim
# in `options`; the route validates this and drops questions that
# violate the contract rather than silently mis-marking them.
correct_answer: str = Field(max_length=400)
explanation: str = Field(max_length=600)
# Concept the question is testing — must be one of the user's known
# concept_names per the prompt. Used by the route to award mastery
# on a correct answer.
concept: str = Field(max_length=120)


class Quiz(BaseModel):
"""The agent's structured output."""

questions: list[QuizQuestion] = Field(min_length=1, max_length=20)


_SYSTEM_PROMPT = (
"You generate adaptive multiple-choice quizzes for a student. Each "
"question must target a specific concept the student has weak "
"mastery on, OR address a class-level misconception you've seen.\n\n"
"Workflow:\n"
"1. Call `read_concepts_for_user` to see the student's mastery per "
" concept for this course (returned sorted by mastery ASC — "
" weakest first).\n"
"2. Call `read_misconceptions_for_course` to see anonymized class "
" misconceptions. Use these to phrase distractors and to write "
" a question that probes the misconception.\n"
"3. Compose `Quiz.questions` so the WEAKEST concepts get the most "
" questions, AND each item's `concept` field exactly matches a "
" concept_name returned by tool 1.\n\n"
"Per-question rules (multiple-choice only — the type field is "
"constrained to 'multiple_choice'):\n"
"- 4 options, exactly one correct. The text in `correct_answer` "
" MUST appear verbatim in `options` — character-for-character. "
" Questions that violate this are dropped at the route layer.\n"
"- Distractors should reflect plausible misconceptions, not random "
" noise. Use the read_misconceptions_for_course return value.\n"
"- explanation: 1-3 sentences explaining WHY the correct answer "
" is correct — used in the post-quiz review screen.\n"
"- difficulty: align with the student's mastery on the concept; "
" weakest concepts get easy/medium, strongest get hard.\n\n"
"Honor the requested num_questions and difficulty distribution "
"in the user message. Don't invent concepts the student doesn't "
"have."
)
Comment on lines +69 to +97

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bashset -euo pipefail
# Confirm the exact registered tool names and whether any aliasing is applied.
rg -n --type=py 'def read_concepts_for_user_tool|def read_misconceptions_for_course_tool|read_concepts_for_user\b|read_misconceptions_for_course\b|tools=\[' backend/agents

Repository: SaplingLearn/Sapling

Length of output: 1385


🏁 Script executed:

# Check the tools registration in quiz.py
sed -n '100,130p' backend/agents/quiz.py

Repository: SaplingLearn/Sapling

Length of output: 383


🏁 Script executed:

# Also check if pydantic-ai is imported and how it handles tool names
rg -n "from pydantic_ai|import.*pydantic_ai|agent.*tools" backend/agents/quiz.py -A 2 -B 2

Repository: SaplingLearn/Sapling

Length of output: 568


🏁 Script executed:

# Check pydantic-ai documentation or examples in the codebase for tool naming
rg -n "def.*_tool\(" backend/agents --type=py -B 5 | head -40

Repository: SaplingLearn/Sapling

Length of output: 1084


🏁 Script executed:

# Check if the _tool functions have any decorators or name parameters
rg -n "@|name\s*=" backend/agents/tools/graph_read.py -B 2 -A 8 | grep -A 10 "read_concepts_for_user_tool\|read_misconceptions_for_course_tool"

Repository: SaplingLearn/Sapling

Length of output: 46


🏁 Script executed:

# Search for pydantic_ai documentation or configuration in the codebase
rg -n "pydantic_ai.*tool|Tool.*name|tool.*alias" backend --type=py | head -20

Repository: SaplingLearn/Sapling

Length of output: 46


🌐 Web query:

pydantic-ai tool naming convention function name suffix

💡 Result:

Pydantic AI does not enforce a specific function name suffix or strict naming convention for tools beyond requiring unique tool names within a toolset or agent. The tool name defaults to the Python function name (snake_case convention in examples like 'roll_dice', 'get_player_name', 'customer_balance'), but can be explicitly overridden via the 'name' parameter in decorators (@agent.tool(name='custom_name'), Tool constructor, Tool.from_schema) or toolset methods. ToolDefinition names must be unique to avoid conflicts (raises UserError on duplicates), but no suffix like '_tool' is required or conventional. Use descriptive, unique names that clearly communicate purpose, following Python snake_case for functions.

Citations:


Fix tool name mismatch between prompt and registration.

The prompt instructs the agent to call read_concepts_for_user and read_misconceptions_for_course, but the registered tools are read_concepts_for_user_tool and read_misconceptions_for_course_tool. Pydantic-ai uses the function name directly as the tool name without auto-aliasing suffixes, so the agent will fail to locate these tools when following the prompt instructions.

Either rename the functions to remove the _tool suffix or update the prompt to reference the correct tool names.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@backend/agents/quiz.py` around lines 69 - 97, The system prompt
(_SYSTEM_PROMPT) tells the agent to call read_concepts_for_user and
read_misconceptions_for_course, but the actual registered tool functions are
named read_concepts_for_user_tool and read_misconceptions_for_course_tool, so
the agent will not find the tools; fix by making the names consistent: either
rename the tool functions (read_concepts_for_user_tool -> read_concepts_for_user
and read_misconceptions_for_course_tool -> read_misconceptions_for_course) or
update _SYSTEM_PROMPT to reference the actual registered names
(read_concepts_for_user_tool and read_misconceptions_for_course_tool) so the
prompt matches the function symbols used at registration.

_PROMPT_HASH = hashlib.sha256(_SYSTEM_PROMPT.encode("utf-8")).hexdigest()[:12]


quiz_agent = Agent[SaplingDeps, Quiz](
model=model_for("quiz"),
deps_type=SaplingDeps,
output_type=Quiz,
system_prompt=_SYSTEM_PROMPT,
metadata={"prompt_version": _PROMPT_HASH, "agent": "quiz"},
tools=[
read_concepts_for_user_tool,
read_misconceptions_for_course_tool,
],
)
163 changes: 163 additions & 0 deletions backend/agents/tools/graph_read.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
"""Read-side graph tools for Pydantic AI agents.

Per ADR 0004: the agent needs to pull mastery state + course-level
misconceptions when planning a quiz. These are the tool surfaces.
The pure-async functions are callable directly from routes;
the *_tool wrappers register on a Pydantic AI Agent.
"""

from __future__ import annotations

import asyncio
import logging
from typing import Any

from pydantic import BaseModel, Field
from pydantic_ai import RunContext

from agents.deps import SaplingDeps
from db.connection import table

logger = logging.getLogger(__name__)


# ── read_concepts_for_user ────────────────────────────────────────────────


class ConceptMastery(BaseModel):
"""Per-concept mastery state for the user in a course."""

concept_name: str
mastery: float = Field(ge=0.0, le=1.0)
last_reviewed_at: str | None = None


async def read_concepts_for_user(
user_id: str,
course_id: str | None,
) -> list[ConceptMastery]:
"""Return the user's concept mastery for a course (or globally if
course_id is None). Sorted by mastery ASC so the weakest concepts
appear first — quiz_agent uses this ordering to focus on weak areas.

Pure async, callable from routes. Wraps the underlying sync
Supabase read in asyncio.to_thread so it doesn't block the loop.

NOTE: The underlying `graph_nodes` table stores the mastery value as
`mastery_score` and the timestamp as `last_studied_at`. We map them
here to the agent-facing names (`mastery`, `last_reviewed_at`) so the
tool contract stays stable even if storage column names change.
"""

def _fetch() -> list[dict[str, Any]]:
filters = {"user_id": f"eq.{user_id}"}
if course_id:
filters["course_id"] = f"eq.{course_id}"
try:
Comment on lines +54 to +56

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Remove the unsupported course_id filter from graph_nodes reads.

On Line 55, filters["course_id"] is added, but the provided schema for graph_nodes (in backend/db/archive/schema.sql:11-22) has no course_id column. That causes the select to fail, then Lines 65-71 swallow it and return [], so weak-concept context is silently lost for course-scoped requests.

🔧 Proposed fix
 def _fetch() -> list[dict[str, Any]]:
filters = {"user_id": f"eq.{user_id}"}
- if course_id:- filters["course_id"] = f"eq.{course_id}"
try:
return (
table("graph_nodes").select(
"concept_name,mastery_score,last_studied_at",
filters=filters,
order="mastery_score.asc",
)
or []
)

Also applies to: 65-71

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@backend/agents/tools/graph_read.py` around lines 54 - 56, Remove the
unsupported course_id filter when querying graph_nodes: delete the line that
sets filters["course_id"] = f"eq.{course_id}" inside the graph_nodes read code
so you don't send a non-existent column to the DB; also stop silently swallowing
the resulting exception in the surrounding try/except (the block that currently
catches errors and returns []), instead let the exception propagate or log and
re-raise so callers know the read failed and course-scoped context isn’t
silently dropped. Reference the filters dict used for graph_nodes reads and the
try/except that returns an empty list to locate the changes.

return (
table("graph_nodes").select(
"concept_name,mastery_score,last_studied_at",
filters=filters,
order="mastery_score.asc",
)
or []
)
except Exception:
logger.exception(
"read_concepts_for_user failed for user=%s course=%s",
user_id,
course_id,
)
return []

rows = await asyncio.to_thread(_fetch)
return [
ConceptMastery(
concept_name=r.get("concept_name") or "",
mastery=float(r.get("mastery_score") or 0.0),
last_reviewed_at=r.get("last_studied_at"),
)
for r in rows
if r.get("concept_name")
]


async def read_concepts_for_user_tool(
ctx: RunContext[SaplingDeps],
) -> list[ConceptMastery]:
"""Pydantic AI tool wrapper. Reads from ctx.deps."""
return await read_concepts_for_user(ctx.deps.user_id, ctx.deps.course_id)


# ── read_misconceptions_for_course ────────────────────────────────────────


class Misconception(BaseModel):
"""A class-level misconception observed across student sessions."""

text: str
related_concept: str | None = None


async def read_misconceptions_for_course(
course_id: str | None,
) -> list[Misconception]:
"""Return aggregated misconception strings for a course. Anonymized
(sourced from class-wide patterns, not from any single student).
Returns [] when course_id is None or the underlying table is empty.

Source: `course_concept_stats` rows for the course. Each row
represents one concept and carries a `common_misconceptions` array
(populated by the hash-gated aggregation in
`services/course_context_service.py`). We flatten each array entry
into its own Misconception, tagging `related_concept` with the
concept name so the agent can route distractors per-concept.

The spec referenced a hypothetical `misconceptions` table — that
table does not exist in this schema. `course_concept_stats` is the
real source of class-wide misconception strings, so we read that.
The tool contract (returning Misconception[]) is unchanged.
"""
if not course_id:
return []

def _fetch() -> list[dict[str, Any]]:
try:
return (
table("course_concept_stats").select(
"concept_name,common_misconceptions",
filters={"course_id": f"eq.{course_id}"},
order="updated_at.desc",
limit=20,
)
or []
)
except Exception:
logger.exception(
"read_misconceptions_for_course failed for course=%s",
course_id,
)
return []

rows = await asyncio.to_thread(_fetch)
out: list[Misconception] = []
seen: set[str] = set()
for r in rows:
concept = r.get("concept_name") or None
for m in r.get("common_misconceptions") or []:
text = (m or "").strip() if isinstance(m, str) else ""
if not text:
continue
key = text.lower()
if key in seen:
continue
seen.add(key)
out.append(Misconception(text=text, related_concept=concept))
return out


async def read_misconceptions_for_course_tool(
ctx: RunContext[SaplingDeps],
) -> list[Misconception]:
"""Pydantic AI tool wrapper. Reads from ctx.deps."""
return await read_misconceptions_for_course(ctx.deps.course_id)
6 changes: 6 additions & 0 deletions backend/models/__init__.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,6 +44,12 @@ class GenerateQuizBody(BaseModel):
num_questions: int = 5
difficulty: str = "medium"
use_shared_context: bool = True
# Mirrors the Learn-route fast/smart toggle so quiz generation has
# the same per-request model-quality choice as chat tutoring.
# "fast" → gemini-2.5-flash, "smart" → gemini-2.5-pro. None falls
# through to whatever SAPLING_MODEL_QUIZ resolves to (default
# gemini-2.5-flash-lite per ADR 0008).
model_pref: Optional[Literal["fast", "smart"]] = None


class AnswerItem(BaseModel):
Expand Down
Loading
Loading