Skip to content

EdTech AI Platform: AI Marking for Handwritten VCE Maths

A study platform for VCE students that reads photos of handwritten maths working, retrieves the official marking guide and marks it step by step. I built the Next.js portals, the Python marking service and the AWS infrastructure behind it.

Built with
Next.js · Python · FastAPI · LangGraph · Pinecone · Supabase · AWS Bedrock · Mathpix · AWS EC2 · Terraform

What it is

The platform is built for Victorian VCE students. It has a question bank built from past exam papers, practice and timed exam modes, and marking for short and structured answers. For maths, a student photographs their handwritten working; the system reads it, compares it step by step with the official marking guide, and returns marks with feedback. A coach then explains where marks were lost.

I built it through Webifex Labs between March and June 2026: the Next.js app (marketing site, student portal and admin portal), the Python service that ingests exam papers, retrieves content and marks answers, and the AWS infrastructure and CI that run it. It reached a working MVP on staging and has not launched publicly, so there is no live link here.

Architecture at a glance

One Next.js deployment on Vercel serves the marketing site and the signed-in app, split by hostname. It handles sign-in, reads data through Supabase with row level security, and calls the Python service for anything that touches a model. Browsers never talk to Pinecone or a model API directly.

  • Supabase is the system of record: users, questions, content chunks, grading results and job progress. Pinecone only holds embeddings.
  • The Python service (FastAPI, Python 3.12, uv) owns ingestion, retrieval and marking. Only its ingestion path writes vectors.
  • Model providers sit behind small interfaces, so swapping an OCR provider or the judge is a configuration change rather than a rewrite. That mattered, because both changed more than once.
EdTech AI platform architectureThe browser talks only to the Next.js app on Vercel, which serves the marketing site and the student and admin portals and reads Supabase under row level security. The Next.js app calls the Python service, built with FastAPI and LangGraph and running on AWS EC2 in Sydney, with a service token. The Python service uses Supabase and Pinecone for data, calls Mathpix, Bedrock Claude and Fireworks, and sends logs, traces and errors to Axiom, Langfuse and Sentry.DataModel APIsBrowserNext.js on Vercelmarketing site and portalsreads Supabase under RLSPython serviceFastAPI · LangGraph · AWS EC2SupabasePostgres · Auth · StoragePineconedense and sparse indexesMathpixhandwriting to LaTeXBedrock Claudejudge and coachFireworksLaTeX, structuringObservabilityAxiom · Langfuse · Sentryservice token
The browser only talks to the Next.js app. Everything that touches a model goes through the Python service.
The stack, layer by layer
LayerWhat runs there
Web appNext.js 16, React 19, TypeScript, Tailwind CSS and KaTeX for maths, hosted on Vercel
Marking servicePython 3.12, FastAPI, Pydantic and LangGraph, packaged with uv and Docker
Document ingestDocling for exam papers, python-docx for marking guides, PyMuPDF
DataSupabase (Postgres with row level security, Auth, Storage, Realtime) and Pinecone dense and sparse indexes with hosted reranking
ModelsMathpix for handwriting, Claude on AWS Bedrock as judge and coach, Kimi on Fireworks for LaTeX clean-up and structuring
InfrastructureAWS EC2 with an IAM instance role, ECR, SSM Parameter Store, Terraform
DeliveryGitHub Actions with OIDC to AWS for the service, Vercel's Git integration for the web app
ObservabilityOpenTelemetry, Axiom, Langfuse, Sentry and PostHog

Marking a photo of handwritten working

Marking is a LangGraph state graph with eight steps. Each step records what it did and passes a typed state to the next one, and every call to an outside service inside it has a time limit. The judge marks against specific criteria retrieved from the official marking guide, so every mark can be traced back to the line of the guide it came from.

How a photo of handwritten working is markedA photo of handwritten working passes a quality gate, Mathpix reads the handwriting into LaTeX, the LaTeX is cleaned up, and the working is split into parts and steps. The marking guide is then retrieved, Bedrock Claude marks each criterion against it, a confidence check runs, and the marks and audit trail are saved. If no model could mark the answer, it is held for review instead.Read the workingMark itPhoto of workingQuality gateis the photo usable?Read handwritingMathpix to LaTeXClean up LaTeXrules, then a modelParts and stepssplit the workingMarking guidehybrid retrievalMark criteriaBedrock Claude judgeHeld for reviewConfidencehow sure is it?Save resultmarks, audit trailnot marked
Eight steps in one LangGraph graph. If no model actually marked the answer, it is held for review instead of getting a guessed mark.

The judge is Claude on AWS Bedrock and runs on every grounded mark: Sonnet first, Haiku if that fails, and a stronger escalation pass when the result looks inconsistent or the question is hard. It returns its answer through a forced tool call so the output is always valid JSON, and the shared prompt prefix is cached.

One rule shaped the whole graph. Early on, when the judge failed, the pipeline quietly fell back to a simple rule-based scorer and showed the result as if nothing had happened. A wrong mark presented with confidence is worse for a student than "under review", so now the attempt is held for review and the failure is logged as a signal, and the record of which grader ran is kept all the way to the saved result.

Retrieval grounded in the marking guide

Marking needs the whole rubric for a question, not just the paragraphs that happen to look most similar to the student's working. Retrieval runs a dense and a sparse search in parallel, merges them with reciprocal rank fusion, reranks the result with a Pinecone-hosted reranker (BGE reranker v2 m3 by default, falling back to Cohere Rerank 3.5), and loads the full text from Supabase by chunk id. A separate SQL lookup then adds every rubric criterion for that question, so nothing the examiners would check is left out.

Retrieval grounded in the marking guideThe question and the student's steps are filtered to this question's certified rubric and solution content. Dense and sparse searches run in parallel and are merged with reciprocal rank fusion, reranked, and hydrated with full text from Supabase by chunk id. A separate SQL lookup adds every rubric criterion for the question, and both feed the context for the judge.Question, stepsFilterthis question, certified contentDense searchSparse searchRank fusionreciprocal rankRerankBGE, then CohereAll criteriaSQL, this questionHydratefull text by chunk idContext for the judge
Similarity search finds the relevant solution steps. The SQL lookup guarantees the full rubric is in front of the judge.

I looked at Bedrock Knowledge Bases as a managed alternative when the judge moved to Bedrock. It is built for general document Q&A, it cannot express the "every criterion for this question" lookup, and replacing Pinecone through it would have cost more each month for less control. Moving the judge did not need retrieval to move with it.

Decisions that changed under real traffic

Several of the big choices were made twice: once on paper, and again once real handwriting and real failures showed where the first answer was wrong. The table is the short version; the reasoning for the ones that moved most follows it.

Key decisions and what they cost
DecisionOptions consideredWhyTrade-off
Hybrid retrieval on Pinecone plus a SQL rubric lookupBedrock Knowledge BasesMarking needs every criterion for the question, which does not fit a similarity-search knowledge baseI own and maintain the retrieval code
Claude on AWS Bedrock as the judgeLlama on Together AI, staying on Fireworks, Gemini on Vertex AIBest feedback quality, forced tool output for valid JSON, and prompt cachingModel access is tied to AWS, which is why the service moved there too
One EC2 instance with an IAM roleStaying on a DigitalOcean droplet with static keysBedrock access without long-lived AWS keys on the hostCosts more each month than the droplet
Hold an attempt for review when no judge ranFall back quietly to a rule-based scorerA confident wrong mark is worse for a student than "under review"Some attempts wait for review instead of getting a mark
Mathpix as the only OCR for markingGemini on Vertex AI, Kimi on Fireworks, a fallback chainFast and accurate on handwriting, and a clear failure beats a silent switch to a weaker modelMathpix has a monthly page cap, so a search for a bulk provider continued
Serverless model APIsSelf-hosting on Modal or BasetenFar cheaper at this volume, and scaling a GPU to zero brings back cold startsRevisit once volume makes a warm GPU worth paying for

Which OCR reads the handwriting

The OCR provider changed three times in four days once real student handwriting reached it. Mathpix, a dedicated maths OCR, ended up as the only provider for marking, and it is configured not to keep student images.

OCR provider for marking, over time
WhenOCR for markingWhy it changed
May 2026Gemini Flash on Vertex AI, Fireworks as fallback, Mathpix off by defaultThe first policy kept the critical path with one vendor until real usage showed how often a fallback was needed.
19 JuneKimi on Fireworks, Gemini as a bounded fallbackGemini's token refresh hung the marking graph, which is the incident below.
20 JuneMathpix, Gemini as fallbackKimi often took 38 to 90 seconds or more on real student handwriting, against a 35 second budget.
22 JuneMathpix onlyThe silent fallback to a weaker model was removed, so a failure now returns a clear "try again".

Which model is the judge

The judge started on open-source models served by Fireworks. The instruct models it depended on started returning 404s on the serverless tier, and the fallback model was slow and often returned invalid JSON. I compared Together AI, staying on Fireworks, Gemini on Vertex, and Claude on Bedrock. Judge quality is the biggest lever on the feedback students see, and Bedrock Claude gave the best feedback quality plus forced tool output and prompt caching, so it won.

Where the Python service runs

It started on Render, which ran out of memory on Docling (the PDF parser used for exam papers), moved to a DigitalOcean droplet, and finally to a single EC2 instance in Sydney. The reason for EC2 was access, not speed: an IAM instance role can call Bedrock without static AWS keys on the host. EC2 cost more than the droplet, and I accepted that for the judge quality and the cleaner credentials. Deploys go through one GitHub Actions pipeline using OIDC, configuration lives in SSM Parameter Store, and a policy check refuses to start the container if the configuration has drifted. The droplet stayed as a standby for one release, so rollback was a single URL change.

Serverless models now, self-hosting later

After the OCR incident it was tempting to self-host a model on Modal or Baseten. I wrote up the numbers: at the platform's volume, serverless model APIs were far cheaper than keeping a GPU warm, and scaling a GPU to zero brings back the cold starts that caused the incident. Self-hosting is deferred until volume justifies it. Any future fine-tuning is limited to answers a human has verified, because training on the model's own past marks would teach it to repeat its mistakes.

Incident: "Marking took too long"

Symptom.Photo marking climbed to 94 percent in the UI and then failed with "Marking took too long". The admin dashboard showed no completed gradings, and the service had no logs for the failed requests.

Root cause. The Gemini OCR client refreshed its Google OAuth token synchronously on the event loop, with no timeout. When the token endpoint was slow, the whole marking graph blocked until the outer 120 second limit killed it. Three things hid it: the primary OCR call had no timeout of its own, the browser, Vercel and the service all gave up at the same 120 seconds so there was no margin to report anything useful, and the 94 percent was a cosmetic cap on the progress bar, not real progress.

Fix. The token refresh moved off the event loop with a hard timeout and a cache. Every external call on the marking path got a bound, and the limits were nested so each layer outlasts the one inside it. A slow OCR provider now fails inside its own 35 seconds and leaves the outer layers time to report what happened.

Timeout limits on the photo marking path, before and after the fixHorizontal bars on a shared scale from 0 to 130 seconds. Before the fix, the browser, Vercel and the service all gave up at 120 seconds, the OCR fallback chain had 105 seconds, and neither the OCR step nor the primary OCR call had a limit of its own. After the fix, each layer fits inside the next: the primary OCR call 35 seconds, the fallback chain 40, the OCR step 60, the service 100, Vercel 120 and the browser 130.0 s30 s60 s90 s120 sBefore the fixBefore the fix: Browser gives up, 120 sBrowser gives up120 sBefore the fix: Vercel function limit, 120 sVercel function limit120 sBefore the fix: Service request limit, 120 sService request limit120 sBefore the fix: OCR step of the graph, no limitOCR step of the graphno limitBefore the fix: OCR fallback chain, 105 sOCR fallback chain105 sBefore the fix: OCR primary call, no limitOCR primary callno limitAfter the fixAfter the fix: Browser gives up, 130 sBrowser gives up130 sAfter the fix: Vercel function limit, 120 sVercel function limit120 sAfter the fix: Service request limit, 100 sService request limit100 sAfter the fix: OCR step of the graph, 60 sOCR step of the graph60 sAfter the fix: OCR fallback chain, 40 sOCR fallback chain40 sAfter the fix: OCR primary call, 35 sOCR primary call35 s
Limits as configured in the code before and after the fix. In the incident, the OCR step ran for 120.4 seconds before the 120 second limit cut the whole request off.
Show these numbers as a table
Timeout limit per layer, in seconds
LayerBeforeAfter
Browser gives up120 s130 s
Vercel function limit120 s120 s
Service request limit120 s100 s
OCR step of the graphno limit60 s
OCR fallback chain105 s40 s
OCR primary callno limit35 s

Tests assert that order and that a hanging provider fails fast instead of eating the budget. OCR now logs each sub-stage, so a hang is visible even when the request times out, and error messages show a reference id that support can look up.

Other problems worth writing down

Smaller incidents, in the order they turned up
ProblemSymptomCauseFix
Correct OCR, wrong marksAfter the switch to Mathpix, marks were off and the UI showed raw LaTeX.The pipeline still expected the previous provider's output, so a full page of working collapsed onto one line and lost the (a) and (b) structure that step splitting relies on.Read Mathpix's page Markdown and normalise it while keeping the maths delimiters.
A deleted deploy workflow that kept runningEvery CI run still started the old DigitalOcean deploy, which then failed.GitHub Actions reads workflow_run triggers from the default branch, and the workflow had only been removed from the working branch.Remove it from the default branch too, so only the EC2 deploy follows CI.
Log shipping that shipped nothingThe OpenTelemetry Collector sidecar was running, but Axiom received no logs.The collector's default user could not read Docker's log files.Give the collector read access, document the symptom, and confirm by querying the logs and traces datasets.
Marking rejected by its own schemaText gradings and the grading canary failed with HTTP 422.Long judge explanations broke a length limit in the result schema.Clamp the explanation before validation, with a regression test.
Maths that rendered wrongSome exam questions showed corrupted maths.The portal was rendering the text normalised for embeddings.Display always reads the original LaTeX, with tests and a written rule.
A tutor chat that could not be reachedThe page loaded, but sending a message returned a 500.A Next.js cache wrapper was put around a Supabase client that reads cookies, which cannot run inside a cache scope.Remove the wrapper and add a CI check that blocks the pattern.

Evaluation and diagnostics

Providers changed often, so each change needed a quick, repeatable way to show nothing had got worse.

  • A grading evaluation runner compares models against examiner marks: exact mark agreement, mean absolute mark error, the share within one mark, criterion-level F1, and the share of responses that are valid JSON.
  • An OCR evaluation harness runs providers side by side, works without labelled data for smoke runs, batches requests to stay under provider rate limits, and has a one-image readiness check to run before long jobs.
  • A grading canary marks a known question end to end after a deploy, and load tests check latency and error rate against fixed thresholds.
  • A grading pipeline viewin the admin portal shows each run's step timings and what was retrieved, plus a staging-only switch to compare OCR providers on the same submission. In production that switch is read-only.

Observability

A single trace_id is stamped on every log line, outgoing request and trace span, and it joins six places: Axiom for logs and OpenTelemetry traces, Langfuse for model calls, Sentry for errors, a typed signals table in Supabase for business events, PostHog for product analytics, and the pipeline view in the admin portal. When a request crosses the browser, Vercel, the Python service and two model vendors, that one key is what makes an incident traceable.

Where it stands

The MVP works end to end on staging: accounts, the question explorer, practice and exam sessions, photo marking, the coach, the admin ingest pipeline and the operations dashboards. It has not launched publicly. The open work was a formal OCR sign-off against labelled data and a latency target for marking.