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:
- Syllabus-Grounded Problem Solver (`/dashboard/solve`): Accepts typed questions, photographed textbook/handwritten problems, or PDF worksheets; retrieves top-matching textbook chunks from
public.knowledge_chunksviapgvectorcosine similarity; and streams step-by-step solutions rendered in real time with KaTeX. - 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(1to5marks) andquestion_type(mcq,very_short,short,long,case_study,assertion_reason), paired with a 30-day cached chapter summary generator. - Prerequisite-Aware Curriculum Graph (`/dashboard/learning`): Models
curricula→courses→units→learning_objectives→lessonswith a many-to-many prerequisite DAG (objective_prerequisites) and per-student mastery tracking (not_started→learning→needs_review→mastered). - 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_reasonquestion 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:
- 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 RPCmatch_knowledge_chunks()then filters bysubjectandcurriculumwhile automatically unioning cross-cuttingcurriculum = 'ALL'formula sheets above a0.62cosine similarity threshold. - Relational Prerequisite DAG & Objective-Scoped Retrieval: Migration
004_learning_paths.sqllinksknowledge_chunksdirectly tolearning_objectives(id)andlessons(id). When a student studies inside a learning path,retrieveObjectiveContext()first executesmatch_objective_chunks()(threshold: 0.60) scoped to that exact objective before falling back to broader curriculum search. - Zero-Rewrite Stream Protocol Adapter (`adaptGeminiStream`): When migrating the streaming solver from Anthropic Claude Sonnet to
gemini-2.5-flash(configured withthinkingBudget: 0for sub-2-second time-to-first-token), I implemented an async generator adapter (adaptGeminiStreaminsrc/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. - Expand-and-Contract Billing Migration (`007` → `008`): To cut over from Stripe to Razorpay safely, Migration
007introduced provider-neutral columns (payment_provider,payment_subscription_id,payment_customer_id,payment_price_id), bidirectional PL/pgSQL triggers keeping legacystripe_*columns synchronized during rolling deployment, and apayment_webhook_eventsidempotency table, followed by Migration008dropping 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.
Text, textbook photo, and PDF upload with real-time KaTeX math rendering and follow-up tutor chat
Diagnostic placement, prerequisite mastery progression, and 2019–2025 NBSE/CBSE PYQ chapter drills
Interactive 4-subject simulations and plan-gated Vimeo lecture catalogue with watch progress
Verifies JWT via supabase.auth.getUser(), enforces per-plan RPM and monthly quotas, and sanitizes payloads
Expands short queries, generates 1536-dim embeddings, and runs objective-scoped or curriculum vector search
Injects textbook citations + prerequisite context and adapts chunks via adaptGeminiStream() to SSE
ivfflat-indexed knowledge_chunks, mark-weighted pyqs (NBSE/CBSE/NCERT), and 30-day chapter_summaries cache
curricula → courses → units → learning_objectives (DAG) → lessons + student_objective_mastery
Provider-neutral subscriptions schema, payment_webhook_events audit log, and atomic RPC usage counters
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:
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:
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:
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:
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 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
- 00:00Syllabus-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.
- 00:55NBSE & 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.
- 01:50Prerequisite Curriculum Graph & Mastery State Machine — Navigating Curricula → Courses → Units → Learning Objectives → Lessons and updating student_objective_mastery.
- 02:40Stream 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 (
768vs.1536vs.3072), which requires rebuildingpgvectorcolumns andivfflatindexes. Pinninggemini-embedding-001withoutputDimensionality: 1536preserved compatibility with the existingvector(1536)schema acrossknowledge_chunksandpyqs. - 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: 0ongemini-2.5-flashwhile 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 chargingsummary_credits_usedonly 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 exactmatch_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.sqlthrough011_grant_pyq_ingestion_permissions.sql), includingcheck (objective_id <> prerequisite_objective_id)onobjective_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.pyqswithmark_weightandquestion_typeacross 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-flashinsideadaptGeminiStream()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.tswith@upstash/ratelimitfor 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 andscripts/ingest-pyqs-from-pdf.tspipeline to cover additional state boards (MBOSE, SEBA) alongside NBSE and CBSE.