Define the tutoring contract before choosing a model
The phrase “first wrong step” needs an operational definition. For this narrow algebra scope, each written line represents a set of possible values for x. A transition is valid when the new line has exactly the same solution set as the line above. The first wrong step is the first transition that changes that set. Later lines are ignored, even if they contain additional mistakes.
That definition produces a clean responsibility split:
- The verifier decides: supported notation, equivalence between adjacent lines, first wrong step ID, and a coarse error class.
- The model phrases: exactly one hint at the requested level, using only the first-error packet.
- The leak gate decides: whether the hint can be shown or must be rejected.
- The learner decides: the next revised line. The tutor waits instead of completing the chain.
This is deliberately not a general mathematics engine. The included parser accepts integers, decimals represented exactly as fractions, parentheses, unary signs, the four basic operations, implicit multiplication such as 3x, and one variable named x. It rejects powers, products of variables, variable denominators, multiple variables, division by zero, unbalanced syntax, and unknown symbols. Rejection returns needs_review; it does not invite the model to guess.
Keep teacher truth separate from the visible attempt
The evidence kit stores two files for a reason. The problem pack contains the original equation, private expected solution, and corrected equations that the leak gate must never release. The attempt pack contains ordered step IDs, typed equations, and independently authored expected diagnosis labels.
Do not combine these files into one model prompt. The optional model packet contains only five fields: first wrong step ID, requested hint level, coarse error code, the line before the break, and the changed line. It omits the teacher solution, later work, personal identifiers, grades, and account data. Less context is a safety feature here because the model cannot disclose information it never receives.
Minimal packet
{
"step_id": "s1",
"hint_level": 1,
"error_code": "distribution_mismatch",
"previous_equation": "3(x + 2) = 15",
"current_equation": "3x + 2 = 15"
}

If you adapt the kit, create teacher truth before generating any hint. That prevents a model-written “expected answer” from grading its own output. It also gives the leak checker concrete forbidden strings instead of relying on a vague instruction such as “do not reveal too much.”
Run the exact first-error checker
Download the tutor script, the two JSON packs, and the hint policy into one folder. The script uses only the Python standard library for offline diagnosis and controlled hints.
python3 ai-math-first-error-tutor.py diagnose \
--problems ai-math-problem-pack.json \
--attempts ai-math-student-attempts.json \
--case M04
The checker parses each side into an exact linear form, moves both sides conceptually into one coefficient and one constant, and classifies the solution set as one value, all rational values, or no values. It compares the original equation with step one, then step one with step two, continuing only while equivalence is preserved. Case M04 intentionally has a valid first transition and an invalid second transition, so the result points to s2, not merely the first submitted line.
The diagnosis object never includes the solved value. It returns a short error signature derived from the case, step, rule class, and two adjacent lines. That signature controls progression: a request for more help on the same error advances by one level; a revised attempt with a new error resets to level one.

Release only the next hint layer
The included state machine has three levels. It never jumps from the first prompt to an answer and never creates a fourth, increasingly explicit layer.
| Layer | Allowed move | Forbidden move |
|---|---|---|
| H1: locate | Point to the first suspect step and ask about the invariant. | No calculation, rule lecture, corrected equation, or solved value. |
| H2: name the rule | Name one operation or property to inspect. | No rewritten line, chained instructions, or later-step advice. |
| H3: analogy | Give one similar prompt using y and different numbers. | Do not solve the analogy or map it back into the learner's answer. |
The following retained frames use the same synthetic error signature, so the reader can inspect exactly what changes—and what remains hidden—as help advances one layer at a time.
H1 points to the place to recheck

H2 names one rule

H3 uses an unsolved analogy

After H3, stop. Ask the learner to show a smaller substep or hand the attempt to a human teacher. “More help” must not become an unbounded countdown to the solution.
python3 ai-math-first-error-tutor.py hint \
--problems ai-math-problem-pack.json \
--attempts ai-math-student-attempts.json \
--policy ai-math-hint-policy.json \
--case M04 --level 2 --provider template
The offline template provider is intentionally plain. It exists to prove the state and leak controls without pretending that a language model ran. Replace it with a model only when you are ready to retain dated output and review failures.
Add a structured AI phrasing step
The optional provider in the script is pinned to gpt-5.4-mini-2026-03-17. Current OpenAI model documentation lists Responses API and Structured Outputs support for GPT-5.4 mini. The implementation sends the tutoring contract as higher-priority instructions, submits the minimal JSON packet as input, requests a strict five-field JSON schema, limits output length, and sets store=False.
Keep the API key outside the repository. Install the current official OpenAI Python package in an isolated environment, set OPENAI_API_KEY, and use --provider openai. Recheck the current official API reference before running because model snapshots and SDK shapes can change.
Structured output constrains shape, not pedagogy. Schema-conforming JSON may still hide a corrected equation or direct answer. Therefore every live output must pass the same independent leak gate before it reaches a learner.
Block answer leakage locally
The output schema allows exactly five fields: step ID, hint level, hint text, a true stop-and-wait flag, and a false answer-reveal flag. The local gate then applies semantic checks that schema alone cannot express.
- The step ID must equal the verifier's first wrong step.
- The requested level must be one, two, or three and fit that level's word limit.
- Early layers cannot contain an equals sign.
- The hint cannot contain a private solved value, a forbidden corrected equation, or direct-answer phrases.
- The hint cannot contain a list, multiple prompts, or several questions.
- The output must explicitly stop for revision and mark itself as not revealing the answer.


A failed hint is not softened and displayed. Reject it, log the reason without personal data, and either retry once under the same level or fall back to a reviewed template. Repeated failure should hand off to a person.
Reproduce the retained evidence
Download the complete evidence kit or inspect the evidence README. Run the evidence gate from the extracted folder:
python3 ai-math-evidence-gate.py
The retained result covers exactly 24 synthetic attempts: seven correct and complete, one correct but incomplete, ten with one error, four with multiple errors, and two unsupported or malformed cases. The verifier matched all expected labels. Fourteen supported error cases produced three controlled hint layers each, for 42 leak-checked outputs. Eight damaging mutations were rejected.
The mutations matter because a green result without a demonstrated red path is easy to overread. The gate deliberately changes a first-error label, inserts a direct answer, inserts a corrected equation, jumps to level four, supplies a stale signature, marks unsupported math as valid, erases the synthetic-data boundary, and expands the policy beyond three layers. The retained test result records the output set, hashes, runtime, public release with limitations, and a separate instructional-use HOLD.

Know what the PASS does not prove
The offline PASS means the code, fixtures, expected labels, template hints, hashes, and mutation checks agree. It does not mean that an AI-generated hint is instructionally sound, that a learner will understand it, or that the system improves learning. It does not cover handwritten images, geometry, proofs, word problems, inequalities, units, multiple variables, or ambiguous reasoning.
Research on stepwise remediation supports evaluating error localization separately from the response to that error. Research on generative tutoring also warns that answer-oriented assistance without pedagogical guardrails can undermine the intended learning process. Those findings motivate this architecture; they do not validate this specific implementation. The hint-generation source in the references also uses a different domain and simulated learners, so its conclusions should not be transferred to algebra without review.
Privacy, classroom policy, and stop conditions
Use anonymous case IDs. Do not send names, contact details, school identifiers, disability information, grades, teacher comments, account IDs, or images of people. Confirm the school or organization's rules before sending assessment work to an external service. For minors, use an institution-approved system and data agreement rather than asking a learner to create a personal account.
Stop automated tutoring when notation is unsupported, the parser cannot determine equivalence, the work may have more than one interpretation, the same learner has exhausted H3, the hint gate fails twice, or the problem is part of a restricted assessment. A human teacher should also review cases involving persistent misconceptions, emotional distress, accessibility needs, or curriculum-specific methods.
Before classroom deployment
- Replace the synthetic cases with authorized, de-identified, curriculum-specific fixtures while retaining a separate teacher-truth file.
- Add expected first-error labels before running a model, then have a second reviewer inspect disagreements.
- Run all three hint levels through the leak gate with a dated model snapshot and retain the exact outputs and hashes.
- Ask a qualified mathematics educator to rate correctness, relevance, cognitive demand, clarity, and answer leakage for every retained hint.
- Add adversarial notation and misconception cases, prove they fail closed, and rerun the negative mutations.
- Document privacy authority, retention, deletion, access control, fallback behavior, and the human handoff path.
- Change the instructional-use HOLD only after the owner and educator approve the evidence, not merely because the script exits successfully.
The finished user experience should remain simple: submit ordered work, see the first step worth revisiting, receive one clue, and try again. Everything else in this kit exists to keep that small interaction honest.
