Skip to main content
02 // ENGINEERING SPECIFICATIONLive Production Platform (edxmorung.com)

VizoAI: Syllabus-Aligned STEM AI Tutor, pgvector Textbook & PYQ RAG, and Prerequisite Mastery Graph

A shipped, full-stack STEM learning platform (live at edxmorung.com) combining 1536-dimensional pgvector textbook and Previous Year Question (PYQ) retrieval across NBSE, NCERT, CBSE, IGCSE, AP, IB, and OpenStax curricula with a relational prerequisite mastery graph, KaTeX streaming solver, virtual labs, and a two-phase Stripe-to-Razorpay billing architecture.

Published 2026-08-15Updated 2026-09-1011 min readGitHub RepositoryLive Demo
Next.js App RouterTypeScriptSupabase PostgreSQLpgvector (ivfflat)Gemini 2.5 Flash & EmbeddingsKaTeXRazorpay WebhooksVimeo SDK

1. Overview#

VizoAI is a shipped, full-stack STEM tutoring and exam-readiness platform—live in production at edxmorung.com—built for students aged 13 and above studying Mathematics, Physics, Chemistry, and Biology across NBSE (Nagaland Board of School Education), NCERT, CBSE, IGCSE, AP, IB, and OpenStax syllabi (Classes 8–13).

Rather than acting as a generic homework answer generator, VizoAI combines four tightly integrated subsystems inside a single Next.js App Router + Supabase PostgreSQL architecture:

  1. Syllabus-Grounded Problem Solver (`/dashboard/solve`): Accepts typed questions, photographed textbook/handwritten problems, or PDF worksheets; retrieves top-matching textbook chunks from public.knowledge_chunks via pgvector cosine similarity; and streams step-by-step solutions rendered in real time with KaTeX.
  2. Board-Exam PYQ & Chapter Summariser (`public.pyqs` & `public.chapter_summaries`): Indexes historical board exam questions (including 2019–2025 NBSE and CBSE Class 10–12 papers) classified by mark_weight (1 to 5 marks) and question_type (mcq, very_short, short, long, case_study, assertion_reason), paired with a 30-day cached chapter summary generator.
  3. Prerequisite-Aware Curriculum Graph (`/dashboard/learning`): Models curricula → courses → units → learning_objectives → lessons with a many-to-many prerequisite DAG (objective_prerequisites) and per-student mastery tracking (not_started → learning → needs_review → mastered).
  4. Interactive Virtual Labs & Recorded Lecture Library (`/dashboard/lab/[subject]`, `/dashboard/lectures`): Provides subject-specific virtual lab simulations alongside a plan-gated Vimeo lecture catalogue with per-user watch progress (public.lecture_progress).

2. The Problem#

Students preparing for board and standardized STEM examinations—particularly in underserved regions such as Northeast India—face four concrete technical and pedagogical gaps when using off-the-shelf AI tools:

  • Syllabus and notation mismatch: An NCERT Class 11 student, an NBSE board candidate, and a Cambridge IGCSE student learn the same mechanics or calculus concepts using different conventions, chapter progressions, and mark-scheme expectations. Unconstrained LLMs routinely apply college-level shortcuts that earn zero marks on a school board exam.
  • No awareness of exam mark weights or past papers: Board exam preparation requires knowing how a 1-mark assertion_reason question differs from a 5-mark derivation in a specific chapter across recent exam years (2019–2025).
  • Answers without prerequisite diagnostics: Solving a Newton's Second Law problem does not help a student who still cannot construct a free-body diagram; flat chat interfaces do not track prerequisite dependencies or longitudinal mastery scores.
  • Regional payment & infrastructure constraints: Operating a live subscription EdTech service in India required migrating live billing infrastructure from Stripe to Razorpay without breaking existing user profiles, subscription states, or webhook idempotency.

3. The Approach#

VizoAI was engineered around four core architectural decisions:

  1. Dual-Corpus `pgvector` RAG (`knowledge_chunks` + `pyqs`) with Query Expansion: Short student prompts (e.g., "F=ma problem") produce weak vector embeddings. Before calling gemini-embedding-001 (outputDimensionality: 1536), expandQuery() rewrites terse prompts(< 80 chars) into descriptive STEM search queries. The PostgreSQL RPC match_knowledge_chunks() then filters by subject and curriculum while automatically unioning cross-cutting curriculum = 'ALL' formula sheets above a 0.62 cosine similarity threshold.
  2. Relational Prerequisite DAG & Objective-Scoped Retrieval: Migration 004_learning_paths.sql links knowledge_chunks directly to learning_objectives(id) and lessons(id). When a student studies inside a learning path, retrieveObjectiveContext() first executes match_objective_chunks() (threshold: 0.60) scoped to that exact objective before falling back to broader curriculum search.
  3. Zero-Rewrite Stream Protocol Adapter (`adaptGeminiStream`): When migrating the streaming solver from Anthropic Claude Sonnet to gemini-2.5-flash (configured with thinkingBudget: 0 for sub-2-second time-to-first-token), I implemented an async generator adapter (adaptGeminiStream in src/lib/anthropic/solver.ts) that translates Gemini stream chunks into Anthropic-compatible SSE frames (message_start, content_block_delta, message_stop) so the downstream API route and KaTeX frontend stream parser needed zero breaking changes.
  4. Expand-and-Contract Billing Migration (`007` → `008`): To cut over from Stripe to Razorpay safely, Migration 007 introduced provider-neutral columns (payment_provider, payment_subscription_id, payment_customer_id, payment_price_id), bidirectional PL/pgSQL triggers keeping legacy stripe_* columns synchronized during rolling deployment, and a payment_webhook_events idempotency table, followed by Migration 008 dropping legacy Stripe columns after cutover verification.

4. System Architecture#

VizoAI separates Edge request guarding, RAG query expansion and pgvector retrieval, multimodal Gemini streaming, and PostgreSQL RLS + atomic usage accounting.

SYSTEM SCHEMATIC // VIZOAI SYLLABUS-ALIGNED RAG, PREREQUISITE MASTERY GRAPH & STREAMING SOLVER ARCHITECTURE
01. Client Surfaces (Next.js App Router · KaTeX · Pastel Design System)
Multimodal STEM Solver (/dashboard/solve)

Text, textbook photo, and PDF upload with real-time KaTeX math rendering and follow-up tutor chat

React 18 · rehype-katex · remark-math
Curriculum Graph & PYQ Hub

Diagnostic placement, prerequisite mastery progression, and 2019–2025 NBSE/CBSE PYQ chapter drills

src/app/dashboard/learning · pyqs/*.json
Virtual Labs & Recorded Lectures

Interactive 4-subject simulations and plan-gated Vimeo lecture catalogue with watch progress

Framer Motion · player.vimeo.com
HTTPS POST / SSE Stream & Cookie-Backed Supabase SSR Auth
02. Server Guard, RAG Retrieval & AI Streaming Layer
Auth, Sliding-Window Rate Limit & Plan Quota Guard

Verifies JWT via supabase.auth.getUser(), enforces per-plan RPM and monthly quotas, and sanitizes payloads

middleware.ts · src/lib/rate-limit · src/lib/validate
Query Expansion & Dual-Mode RAG Engine

Expands short queries, generates 1536-dim embeddings, and runs objective-scoped or curriculum vector search

src/lib/anthropic/rag.ts · gemini-embedding-001
Gemini 2.5 Flash Solver & Stream Adapter

Injects textbook citations + prerequisite context and adapts chunks via adaptGeminiStream() to SSE

src/lib/anthropic/solver.ts · thinkingBudget: 0
Service-Role RPCs & Gemini 2.5 Flash / Embedding Calls
03. Supabase PostgreSQL, pgvector & Billing Persistence
pgvector Knowledge Base & PYQ Store

ivfflat-indexed knowledge_chunks, mark-weighted pyqs (NBSE/CBSE/NCERT), and 30-day chapter_summaries cache

migrations/002_rag_knowledge_base.sql · 005_pyq_chapter_summariser.sql
Relational Curriculum Graph & Mastery State

curricula → courses → units → learning_objectives (DAG) → lessons + student_objective_mastery

migrations/004_learning_paths.sql
Razorpay Subscriptions & Webhook Idempotency

Provider-neutral subscriptions schema, payment_webhook_events audit log, and atomic RPC usage counters

migrations/007 & 008 · src/lib/razorpay
Figure: VizoAI Syllabus-Aligned RAG, Prerequisite Mastery Graph & Streaming Solver Architecture

5. Engineering Deep Dive#

5.1 Query Expansion & Objective-Aware `pgvector` Retrieval (`src/lib/anthropic/rag.ts`)#

Every /api/solve and lesson request passes through src/lib/anthropic/rag.ts. If a student submits a short prompt (question.length <= 80), expandQuery() first expands it into a richer search query using gemini-2.5-flash. The query is then embedded into a 1,536-dimensional vector using gemini-embedding-001 (outputDimensionality: 1536).

When a student is actively working on a specific learning_objective_id, retrieveObjectiveContext() queries match_objective_chunks first and gracefully falls back to retrieveContext() (match_knowledge_chunks) if no objective-tagged chunks match—ensuring that RAG errors never crash the live solver:

src/lib/anthropic/rag.tstypescript
async function embedQuery(text: string): Promise<number[]> {
  const res = await getGemini().models.embedContent({
    model: 'gemini-embedding-001',
    contents: text.slice(0, 8000),
    config: {
      outputDimensionality: 1536,
    },
  })

  const embedding = res.embeddings?.[0]?.values
  if (!embedding) throw new Error('Gemini embedding response did not return a valid vector')
  return embedding
}

export async function retrieveContext(
  question:   string,
  subject:    Subject,
  curriculum?: string,
  topK = 5
): Promise<RetrievalResult> {
  const start = Date.now()

  try {
    const { createServiceClient } = await import('@/lib/supabase/server')
    const supabase = createServiceClient()

    const embedding = await embedQuery(question)

    const { data, error } = await supabase.rpc('match_knowledge_chunks', {
      query_embedding:  embedding,
      match_subject:    subject,
      match_curriculum: curriculum ?? null,
      match_count:      topK,
      match_threshold:  0.62,
    })

    if (error || !data || data.length === 0) {
      return { chunks: [], usedRAG: false, queryMs: Date.now() - start }
    }

    const chunks: RetrievedChunk[] = data.map((row: {
      id: string
      content: string
      source_title: string
      chapter: string | null
      topic: string | null
      curriculum: string
      similarity: number
    }) => ({
      id:          row.id,
      content:     row.content,
      sourceTitle: row.source_title,
      chapter:     row.chapter,
      topic:       row.topic,
      curriculum:  row.curriculum,
      similarity:  row.similarity,
    }))

    return { chunks, usedRAG: true, queryMs: Date.now() - start }
  } catch (err) {
    // Never crash the solve route because of RAG failure
    console.error('[RAG] Retrieval failed (graceful degradation):', err)
    return { chunks: [], usedRAG: false, queryMs: Date.now() - start }
  }
}

In PostgreSQL (004_learning_paths.sql), match_knowledge_chunks uses the pgvector cosine distance operator (<=>) over an ivfflat index (lists = 100) and includes cross-curriculum ALL chunks (such as universal physics and calculus formula sheets) alongside the student's selected syllabus:

supabase/migrations/004_learning_paths.sqlsql
create or replace function match_knowledge_chunks(
  query_embedding  vector(1536),
  match_subject    text,
  match_curriculum text default null,
  match_count      int   default 5,
  match_threshold  float default 0.65
)
returns table (
  id           uuid,
  content      text,
  source_title text,
  chapter      text,
  topic        text,
  curriculum   text,
  similarity   float
)
language plpgsql
as $$
begin
  return query
  select
    kc.id,
    kc.content,
    kc.source_title,
    kc.chapter,
    kc.topic,
    kc.curriculum,
    1 - (kc.embedding <=> query_embedding) as similarity
  from public.knowledge_chunks kc
  where
    kc.subject = match_subject
    and (
      match_curriculum is null
      or kc.curriculum = match_curriculum
      or kc.curriculum = 'ALL'
    )
    and 1 - (kc.embedding <=> query_embedding) > match_threshold
  order by kc.embedding <=> query_embedding
  limit match_count;
end;
$$;

5.2 Streaming Protocol Adapter & Multi-Turn Role Coalescing (`src/lib/anthropic/solver.ts`)#

When cutting over the solver engine from Anthropic's SDK to @google/generative-ai (gemini-2.5-flash), the existing /api/solve SSE pipeline and frontend parser expected Anthropic-style stream events (message_start, content_block_delta, message_stop). Rather than rewriting the SSE consumer contract, adaptGeminiStream() transforms Gemini's AsyncGenerator<GenerateContentResponse> on the fly, while streamTutorFollowUp() enforces Gemini's strict alternating user/model turn invariant by coalescing consecutive same-role messages:

src/lib/anthropic/solver.tstypescript
async function* adaptGeminiStream(
  stream: AsyncGenerator<GenerateContentResponse>,
): AsyncGenerator<Record<string, any>> {
  yield {
    type: 'message_start',
    message: {
      id: 'gemini-msg',
      type: 'message',
      role: 'assistant',
      model: 'gemini-2.5-flash',
      stop_reason: null,
      stop_sequence: null,
      usage: { input_tokens: 0, output_tokens: 0 },
    },
  }

  yield {
    type: 'content_block_start',
    index: 0,
    content_block: { type: 'text', text: '' },
  }

  for await (const chunk of stream) {
    const delta = getChunkText(chunk)
    if (delta) {
      yield {
        type: 'content_block_delta',
        index: 0,
        delta: { type: 'text_delta', text: delta },
      }
    }
  }

  yield { type: 'content_block_stop', index: 0 }
  yield {
    type: 'message_delta',
    delta: { stop_reason: 'end_turn', stop_sequence: null },
    usage: { output_tokens: 0 },
  }
  yield { type: 'message_stop' }
}

5.3 Expand-and-Contract Billing Migration (`supabase/migrations/007_payment_provider_neutral_schema.sql`)#

To migrate production billing from Stripe to Razorpay without downtime, Migration 007 introduced provider-neutral columns (payment_provider, payment_subscription_id, payment_customer_id, payment_price_id), a payment_webhook_events idempotency log, and bidirectional BEFORE INSERT OR UPDATE triggers so both old and new application builds could read and write safely during rollout before Migration 008 removed the legacy stripe_* columns:

supabase/migrations/007_payment_provider_neutral_schema.sqlsql
create or replace function public.sync_subscription_payment_columns()
returns trigger
language plpgsql
as $$
begin
  new.payment_provider := coalesce(new.payment_provider, 'stripe');
  new.payment_subscription_id := coalesce(new.payment_subscription_id, new.id);

  -- Legacy Stripe writes populate the new neutral columns.
  if new.payment_customer_id is null and new.stripe_customer_id is not null then
    new.payment_customer_id := new.stripe_customer_id;
  end if;

  if new.payment_price_id is null and new.stripe_price_id is not null then
    new.payment_price_id := new.stripe_price_id;
  end if;

  -- New neutral Stripe writes keep legacy columns available during rollout.
  if new.payment_provider = 'stripe' then
    if new.stripe_customer_id is null then
      new.stripe_customer_id := new.payment_customer_id;
    end if;

    if new.stripe_price_id is null then
      new.stripe_price_id := new.payment_price_id;
    end if;
  end if;

  return new;
end;
$$;

6. Technical Demo#

Technical Walkthrough & Verification
Recorded video walkthrough coming soon

Technical walkthrough recording coming soon

Walkthrough of VizoAI's syllabus-aligned RAG pipeline over NCERT and NBSE board papers, prerequisite learning objective graph, real-time KaTeX SSE streaming, and the expand-and-contract database migration from Stripe to Razorpay.

Walkthrough Sequence & Checkpoints

  1. 00:00
    Syllabus-Aligned Problem Solving & Query Expansion — Submitting a Physics or Mathematics problem, expanding terse queries with Gemini 2.5 Flash, and retrieving top-5 textbook chunks via pgvector.
  2. 00:55
    NBSE & CBSE Previous Year Question (PYQ) Engine — Inspecting mark-weighted board exam questions (2019–2025) and 30-day cached chapter summaries in public.pyqs and public.chapter_summaries.
  3. 01:50
    Prerequisite Curriculum Graph & Mastery State Machine — Navigating Curricula → Courses → Units → Learning Objectives → Lessons and updating student_objective_mastery.
  4. 02:40
    Stream Protocol Adaptation & Expand-Contract Billing Migration — Inspecting adaptGeminiStream() in src/lib/anthropic/solver.ts and the PL/pgSQL dual-write triggers in migration 007.
View Written Walkthrough Summary / Transcript ▾

Generic AI chat tools fail secondary-school and board-exam students in two predictable ways: they solve problems using notation outside the student's syllabus, and they treat every question as an isolated transaction with no memory of prerequisite mastery.

VizoAI (deployed at edxmorung.com) solves both problems at the database and retrieval layers. Textbooks and 2019–2025 board exam papers—including Nagaland Board of School Education (NBSE), NCERT, CBSE, IGCSE, AP, IB, and OpenStax—are segmented and embedded into 1,536-dimensional vectors using gemini-embedding-001 and indexed with pgvector ivfflat.

When a student submits a question or photo, VizoAI expands short queries, retrieves curriculum-matched textbook passages and cross-cutting formula sheets, injects the student's active learning objective and prerequisite state, and streams a step-by-step KaTeX-rendered explanation.

7. Challenges and Trade-offs#

  • Embedding Dimensionality Alignment across Model Migrations (`20260611170000_switch_to_gemini_embeddings.sql`): Switching embedding providers or models often changes vector dimensions (768 vs. 1536 vs. 3072), which requires rebuilding pgvector columns and ivfflat indexes. Pinning gemini-embedding-001 with outputDimensionality: 1536 preserved compatibility with the existing vector(1536) schema across knowledge_chunks and pyqs.
  • Latency vs. Reasoning Depth in Live Tutoring (`thinkingBudget: 0`): Students waiting for an interactive step-by-step explanation abandon the page if time-to-first-token exceeds several seconds. Setting thinkingBudget: 0 on gemini-2.5-flash while supplying structured RAG passages and explicit step-by-step markdown templates kept first-token latency under 2 seconds without sacrificing mathematical accuracy.
  • 30-Day Chapter Summary Caching vs. Live Generation (`public.chapter_summaries`): Synthesizing full chapter summaries and PYQ weight distributions on every page load was expensive and slow. Caching summaries by unique (subject, curriculum, class_level, chapter) with a 30-day TTL (expires_at) and charging summary_credits_used only on uncached generations reduced redundant LLM calls to near zero.

8. Testing and Validation#

  • RAG Retrieval Quality Tester (`/dashboard/admin/knowledge-base`): Built an internal admin retrieval harness (/api/admin/test-retrieval) to inspect exact match_knowledge_chunks() similarity scores, chunk boundaries, and source citations across NCERT and NBSE corpora.
  • Database Migration & Constraint Verification: Verified all 12 sequential SQL migrations (001_initial.sql through 011_grant_pyq_ingestion_permissions.sql), including check (objective_id <> prerequisite_objective_id) on objective_prerequisites, non-negative credit checks (summary_credits_used >= 0), and atomic usage RPCs (increment_problems_used, increment_summary_credits_used, reset_monthly_usage).
  • Known Limitations: The sliding-window rate limiter (src/lib/rate-limit/index.ts) currently uses an in-memory store per serverless instance; multi-region horizontal scaling requires backing it with Upstash Redis.

9. What I Learned#

  • Regional Curricula and PYQs Are Force Multipliers for EdTech RAG: Generic textbook chunks answer what a concept is, but indexing actual board exam questions (public.pyqs with mark_weight and question_type across 2019–2025 NBSE and CBSE papers) teaches students how their specific board tests that concept.
  • Protocol Adapters Decouple Model Experiments from UI Stability: Wrapping gemini-2.5-flash inside adaptGeminiStream() allowed a complete LLM provider migration without touching the SSE transport or KaTeX streaming UI.
  • Expand-and-Contract Migrations Prevent Billing Outages: Using PL/pgSQL synchronization triggers (007) before dropping legacy columns (008) turned a risky payment-provider switch from Stripe to Razorpay into a deterministic, reversible two-step deployment.

10. Future Improvements#

  • Distributed Rate Limiting with Upstash Redis: Replace the in-memory sliding-window map in src/lib/rate-limit/index.ts with @upstash/ratelimit for global consistency across Vercel Edge/Serverless instances.
  • Automated Diagram & Graph Generation in Solutions: Extend the KaTeX markdown pipeline with deterministic SVG plots for kinematics free-body diagrams, ray optics, and coordinate geometry problems.
  • Expanded Northeast & National Board PYQ Coverage: Extend the pyqs/ corpus and scripts/ingest-pyqs-from-pdf.ts pipeline to cover additional state boards (MBOSE, SEBA) alongside NBSE and CBSE.