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.
| Layer | What runs there |
|---|---|
| Web app | Next.js 16, React 19, TypeScript, Tailwind CSS and KaTeX for maths, hosted on Vercel |
| Marking service | Python 3.12, FastAPI, Pydantic and LangGraph, packaged with uv and Docker |
| Document ingest | Docling for exam papers, python-docx for marking guides, PyMuPDF |
| Data | Supabase (Postgres with row level security, Auth, Storage, Realtime) and Pinecone dense and sparse indexes with hosted reranking |
| Models | Mathpix for handwriting, Claude on AWS Bedrock as judge and coach, Kimi on Fireworks for LaTeX clean-up and structuring |
| Infrastructure | AWS EC2 with an IAM instance role, ECR, SSM Parameter Store, Terraform |
| Delivery | GitHub Actions with OIDC to AWS for the service, Vercel's Git integration for the web app |
| Observability | OpenTelemetry, 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.
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.
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.
| Decision | Options considered | Why | Trade-off |
|---|---|---|---|
| Hybrid retrieval on Pinecone plus a SQL rubric lookup | Bedrock Knowledge Bases | Marking needs every criterion for the question, which does not fit a similarity-search knowledge base | I own and maintain the retrieval code |
| Claude on AWS Bedrock as the judge | Llama on Together AI, staying on Fireworks, Gemini on Vertex AI | Best feedback quality, forced tool output for valid JSON, and prompt caching | Model access is tied to AWS, which is why the service moved there too |
| One EC2 instance with an IAM role | Staying on a DigitalOcean droplet with static keys | Bedrock access without long-lived AWS keys on the host | Costs more each month than the droplet |
| Hold an attempt for review when no judge ran | Fall back quietly to a rule-based scorer | A 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 marking | Gemini on Vertex AI, Kimi on Fireworks, a fallback chain | Fast and accurate on handwriting, and a clear failure beats a silent switch to a weaker model | Mathpix has a monthly page cap, so a search for a bulk provider continued |
| Serverless model APIs | Self-hosting on Modal or Baseten | Far cheaper at this volume, and scaling a GPU to zero brings back cold starts | Revisit 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.
| When | OCR for marking | Why it changed |
|---|---|---|
| May 2026 | Gemini Flash on Vertex AI, Fireworks as fallback, Mathpix off by default | The first policy kept the critical path with one vendor until real usage showed how often a fallback was needed. |
| 19 June | Kimi on Fireworks, Gemini as a bounded fallback | Gemini's token refresh hung the marking graph, which is the incident below. |
| 20 June | Mathpix, Gemini as fallback | Kimi often took 38 to 90 seconds or more on real student handwriting, against a 35 second budget. |
| 22 June | Mathpix only | The 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.
Show these numbers as a table
| Layer | Before | After |
|---|---|---|
| Browser gives up | 120 s | 130 s |
| Vercel function limit | 120 s | 120 s |
| Service request limit | 120 s | 100 s |
| OCR step of the graph | no limit | 60 s |
| OCR fallback chain | 105 s | 40 s |
| OCR primary call | no limit | 35 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
| Problem | Symptom | Cause | Fix |
|---|---|---|---|
| Correct OCR, wrong marks | After 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 running | Every 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 nothing | The 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 schema | Text 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 wrong | Some 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 reached | The 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.
