Beating LLM hallucinations in O-Level math
Elijah Chew, ACS (International)
A lot of “AI math” products are one chat box. The model reads the question, reads the student’s answer, and decides if they are right. That feels magical until it quietly marks a wrong fraction as correct, or invents a step that does not follow from the working. For Singapore O-Level E-Math, that failure mode is not a bug report. It is a student walking into an exam with false confidence.
Bridging is built on a split I care about: deterministic code owns truth. The OpenAI API owns language, on a short leash, when a student asks for a hint. This post is how that split is wired.
Do not let the LLM grade math
Large models are good at sounding like a tutor. They are unreliable as a marking engine. Equivalence is the hard part: 0.75, 3/4, and 6/8 are the same value but not the same form; x^2 - 9 and (x-3)(x+3) are equivalent expressions; a set answer might be written in roster or set-builder notation. A general model will sometimes agree with a student because the prose looks plausible.
So Bridging’s /api/practice/mark route never asks GPT whether an attempt is correct. It loads the question from Supabase (model answer, question type, tolerances, accepted variants, unit rules), then runs a TypeScript marker that normalizes input and applies validators.
// api/practice/mark.ts (simplified)
const mark = markMathAnswer({
studentAnswer,
expectedAnswer: question.model_answer,
questionType,
tolerance: question.answer_tolerance ?? undefined,
acceptedAnswers: question.accepted_answers ?? undefined,
options: {
requireSimplifiedForm: question.require_simplified_form,
requireUnits: question.require_units,
requiredUnit: question.required_unit,
acceptedUnits: question.accepted_units,
markingNotes: question.marking_notes,
},
});
return {
isCorrect: mark.isCorrect,
verdict: mark.status,
feedback: mark.feedback,
method: mark.method,
};The core marker is intentionally boring. Binary correct or wrong, with a small set of statuses when the parser cannot commit (invalid input, needs simplified form, manual review).
/**
* Deterministic binary math answer marker.
* Student-facing output is strictly Correct / Wrong only.
*/
export function markAnswer(input: MarkAnswerInput): MarkAnswerResult {
// …validators for numeric, fraction, ratio, set, interval, expression equivalence…
return { isCorrect, verdict: isCorrect ? "Correct" : "Wrong" };
}Each question carries a question_type that maps to a validator pipeline: numeric tolerance, fraction and decimal equivalence, ratio forms, set and interval parsing, algebraic-expression equivalence, and strict text for multiple choice. The database row is the source of truth, not the model’s guess.
Structured question data beats a pasted screenshot
Hallucinations get easier when the model has to reconstruct the problem from messy input. Bridging stores prompts, topics, marking metadata, and model answers in a bridging schema so both the marker and the hint route receive the same structured fields. The student types into a controlled field; we send normalized strings downstream.
When an answer is mathematically equivalent but not in the required form (for example a correct fraction that was supposed to be simplified), the marker can return needs_review with explicit feedback instead of letting GPT improvise praise or blame.
if (relaxed.isCorrect) {
return {
isCorrect: false,
status: "needs_review",
feedback:
"Your answer is mathematically equivalent, but write it in the required simplest form.",
method,
confidence: "high",
};
}Hints: OpenAI on a separate rail
Hints are where the API belongs. The student is stuck, not asking for a verdict. The server builds a single JSON payload from facts we already computed: the question prompt, syllabus topic, the student’s current attempt, how far they got in the question UI, and the marking status from markMathAnswer (incorrect, invalid, needs_review). The model does not re-derive correctness; it is told what the platform already decided.
type HintRequestContext = {
topicTitle: string;
questionPrompt: string;
studentAnswer: string;
markingStatus: "correct" | "incorrect" | "invalid" | "needs_review";
hintLevel: 1 | 2 | 3;
priorHints: string[];
};
const userPayload = JSON.stringify({
syllabus: "Singapore O-Level E-Math",
...ctx,
rules: {
noFinalAnswer: true,
noFullWorkedSolution: true,
maxSentences: 4,
},
});That JSON goes in the user message. The system message is static and strict: O-Level E-Math only, Singapore syllabus tone, one nudge per request, no final numeric answer, no complete worked solution, refer to the given marking status instead of re-judging the attempt. If the student is correct, the hint route does not call the API at all.
Prompt parameters I actually tune
Creative defaults are for brainstorming, not for exam-aligned hints. I keep temperature low, cap length, and nudge the model away from repeating the same phrase on hint level 2 and 3.
const completion = await openai.chat.completions.create({
model: "gpt-4o-mini",
temperature: 0.25,
top_p: 0.9,
max_tokens: 280,
frequency_penalty: 0.3,
messages: [
{ role: "system", content: BRIDGING_HINT_SYSTEM_PROMPT },
{ role: "user", content: userPayload },
],
});BRIDGING_HINT_SYSTEM_PROMPT is versioned in code, not edited in a dashboard. When a hint misbehaves, I change the prompt, redeploy, and test against a fixed set of real questions from the bank. I do not hot-patch behaviour in the client.
Guardrails after the model responds
Server-side checks run on every hint before it reaches the student. Reject empty responses. Strip markdown fences if the model adds them. Block patterns that look like a final answer line (for example a lone “x = …” or “Answer:” when hint level is still 1). If a hint fails validation, the API returns a safe generic nudge and logs the raw completion for review, instead of trusting the model because the UI already said “AI”.
Rate limits and auth sit in front of both mark and hint routes so the OpenAI key never ships to the browser and abuse does not burn the budget.
What this is not
This is not a claim that GPT never drifts. It is a product decision: the part that must be right (is this attempt acceptable for this question?) is code. The part that can be conversational (what should I think about next?) is the model, fed structured context and cut off before it becomes an answer key.
That is the difference between a wrapper and something I would put in front of a Sec 3 student the night before Paper 2. If you want the student-facing version of the philosophy, I wrote it in How I think about AI in education. If you want to stress-test the marker, open bridging.lol and try a question where your working is right but your form is wrong. The site will tell you which case you are in.
bridging.lol (opens in a new tab)How I think about AI in educationIntroducing BridgingMy tech stack in 2026