An AI-powered English learning platform that revolutionizes grammar education through intelligent quiz generation, personalized progress tracking, and adaptive feedback. This comprehensive web application focuses on mastering the 12 essential English tenses using cutting-edge artificial intelligence technology.
🤖 Fully AI-Generated: Every aspect of this platform - from the codebase to the learning algorithms - was created entirely through AI collaboration, demonstrating the future of educational technology development.
This entire website was created using AI assistance:
- Primary AI Agent: Claude Sonnet 3.5 through GitHub Copilot in Visual Studio Code
- Additional Support: ChatGPT for supplementary development tasks
- Development Approach: AI-driven full-stack development with human guidance and review
- Tech Implementation: Complete frontend, backend, database design, and deployment configuration generated through AI collaboration
The project demonstrates the power of AI-assisted software development, showcasing how modern AI tools can help create sophisticated, production-ready web applications.
Goal: Help learners master 12 tenses via Explain → Example → Practice → Feedback → Spaced review.
Learning Principles:
- Micro-chunking: Break down complex grammar into digestible parts
- Active recall: Multiple choice questions for active learning
- Contrastive examples: Show differences between similar tenses
- Error-driven review: Focus on weak spots for improvement
- Real-life contexts: Practical examples and usage
- EN-first with VI support: English primary with Vietnamese translations
- Grammar Q&A (Chat) - AI-powered grammar tutor focused on 12 tenses
- Learn Module - Comprehensive lessons for each tense with definitions, forms, usage, markers, pitfalls, and examples
- Practice Quizzes - Randomized MCQ quizzes (15-30 questions) with varying difficulty
- Instant Results - Detailed scoring and explanations for each question
- Personalized Review - Track mistakes and practice weak spots
- OpenAI Integration - AI-generated content with deterministic grading
- Analytics - Accuracy by topic, progress tracking, completion time
- i18n Support - English/Vietnamese language toggle
- User Authentication - Supabase Auth with email/password login
- User History - Track quiz sessions and performance over time
- Leaderboards - Global ranking with privacy options
- Frontend: Next.js 14 (App Router), React, TypeScript, Tailwind CSS
- Backend: Next.js API Routes, OpenAI SDK
- Database: Supabase (PostgreSQL) with Row Level Security
- Auth: Supabase Auth with JWT
- AI: OpenAI GPT-4o for content generation and grading
- Validation: Zod schemas for type-safe API contracts
- Icons: Lucide React
/ (Home)
├── /learn (Grid of 12 tenses)
│ └── /learn/[tenseId] (Individual tense lessons)
├── /practice (Quiz setup and taking)
│ └── /practice/review (Weak spots practice)
├── /ask (AI Grammar Q&A)
├── /progress (Analytics and tracking)
└── /auth
├── /auth/signin
└── /auth/signup
- profiles: User profile information linked to auth.users
- tenses: Detailed information about the 12 English tenses
- quiz_sessions: Store quiz metadata and questions
- results: Quiz attempt results with scoring and breakdown
- mistake_events: Granular tracking of specific mistakes for targeted review
- Row Level Security (RLS) for all tables
- User-scoped data with proper foreign key relationships
- Indexes for optimized query performance
- Triggers for automatic profile creation on signup
/api/auth/*- Supabase Auth endpoints for login/signup/logout
/api/learn/tenses/[id]- Get tense information by ID
/api/quiz/generate- Generate a new quiz based on parameters/api/quiz/grade- Grade a submitted quiz and store results
/api/history/results- Get paginated quiz history for a user/api/history/detail- Get detailed breakdown of a specific quiz result/api/progress/summary- Get aggregated progress data (timeline, by-tense, etc.)/api/weak-spots- Get personalized weak spots based on mistake patterns/api/leaderboard- Get global leaderboard with privacy controls
- Node.js 18+ and npm
- Supabase account (free tier works fine)
- OpenAI API key
Create a .env.local file with:
NEXT_PUBLIC_SUPABASE_URL=your_supabase_url
NEXT_PUBLIC_SUPABASE_ANON_KEY=your_supabase_anon_key
SUPABASE_SERVICE_ROLE_KEY=your_supabase_service_role_key
OPENAI_API_KEY=your_openai_api_key
- Create a new Supabase project
- Run the SQL from
supabase/updated_schema.sqlin the SQL Editor - Run the SQL from
supabase/functions.sqlto add database functions - Seed the tenses data using the script:
npm run seed-tenses# Install dependencies
npm install
# Run development server
npm run dev- Each quiz result is persisted with user ID, score, and detailed breakdown
- Mistake events are tracked separately for granular analysis
- History API provides paginated access to past results
- Timeline view shows performance over time
- Tense-specific stats highlight strengths and weaknesses
- Top problem concepts identify specific grammar issues
- Algorithm considers both frequency and recency of mistakes
- Weighted scoring prioritizes recurring problems
- Recommendations for focused review
- Global ranking based on average scores
- Privacy controls (opt-out option)
- Time-based filtering (7d, 30d, 90d, all-time)
All API contracts are defined with Zod schemas in the /src/types directory:
index.ts- Core types and schemashistory.ts- Quiz history and results schemasprogress.ts- Progress tracking schemasweak-spots.ts- Weak spots analysis schemasleaderboard.ts- Leaderboard schemas
- Row Level Security (RLS) policies restrict data access
- Service role API key used only for leaderboard (to bypass RLS)
- User IDs are properly validated in all API routes
- Database indexes on frequently queried columns
- SQL functions for efficient aggregation operations
- Pagination for potentially large result sets
This project showcases the capabilities of modern AI-assisted development:
- Conceptualization: Human-defined educational requirements and user experience goals
- Architecture Design: AI-generated full-stack architecture with modern best practices
- Implementation: Claude Sonnet 3.5 through VS Code Copilot handled:
- Complete React/Next.js frontend development
- Backend API design and implementation
- Database schema design and migrations
- Authentication and security implementation
- TypeScript type definitions and validation
- Responsive UI/UX with Tailwind CSS
- Rapid Prototyping: From concept to working prototype in hours
- Best Practices: Modern development patterns and security considerations
- Code Quality: Type-safe APIs, proper error handling, and clean architecture
- Documentation: Comprehensive code comments and API documentation
- Testing: Built-in validation and error handling
-
Human Role: Requirements definition, user experience guidance, and quality assurance
-
AI Role: Code generation, pattern implementation, and technical problem-solving
-
Result: A production-ready educational platform that demonstrates AI-human collaboration
├── /auth/signin (Login) ├── /auth/signup (Registration) └── /auth/signout (Logout)
## 🔧 Setup Instructions
### Prerequisites
- Node.js 18+
- npm or yarn
- Supabase account
- OpenAI API key
### Environment Variables
Create a `.env.local` file in the root directory (copy from `.env.local.example`):
```bash
# OpenAI API (primary AI provider)
OPENAI_API_KEY=your_openai_api_key_here
# Google AI (optional, if you want to switch to Gemini)
GOOGLE_API_KEY=your_google_api_key_here
# Supabase
NEXT_PUBLIC_SUPABASE_URL=your_supabase_project_url
NEXT_PUBLIC_SUPABASE_ANON_KEY=your_supabase_anon_key
SUPABASE_SERVICE_ROLE_KEY=your_supabase_service_role_key
Getting API Keys:
- OpenAI: Get your API key from OpenAI Platform
- Supabase: Create a project at supabase.com and copy keys from Project Settings > API
- Clone and install dependencies:
npm install-
Set up Supabase database:
- Create a new Supabase project
- Run the SQL schema from
supabase/updated_schema.sqlin the Supabase SQL editor - Enable email/password authentication in Supabase Auth settings
- Copy your project URL, anon key, and service role key to
.env.local
-
Configure OpenAI:
- Get your API key from OpenAI dashboard
- Add it to
.env.local
-
Seed tense data:
npm run seed:tenses- Start development server:
npm run devThe application will be available at http://localhost:3000.
GrammarLab uses Row Level Security (RLS) to ensure data privacy and security. The policies are configured as follows:
- Profiles: Users can only select and update their own profile
- Tenses: Public read access, no client write access
- Quiz Sessions: Users can only select and insert their own sessions
- Results: Users can only select and insert results linked to their own quiz sessions
- Mistake Events: Users can only select and insert their own mistake events
The application uses a specialized system prompt for all OpenAI interactions:
"You are an English Grammar Tutor specialized in the 12 basic tenses. Be concise, structured, and accurate. Produce natural examples (A2–B2). Focus on grammar, compare near-confusable tenses, and generate high-quality MCQs with clear right/wrong rationales. When locale=vi, add short Vietnamese support lines after the English explanations. Keep scope strictly to grammar."
Generates randomized MCQ quizzes with specified parameters.
Grades user answers and provides detailed explanations.
Retrieves or generates tense learning cards.
Provides personalized review recommendations based on user mistakes.
- Present Simple - Habits, general truths
- Present Continuous - Current actions, temporary situations
- Present Perfect - Completed actions with present relevance
- Present Perfect Continuous - Ongoing actions from past to present
- Past Simple - Completed past actions
- Past Continuous - Ongoing past actions
- Past Perfect - Earlier past actions
- Past Perfect Continuous - Duration before past point
- Future Simple - Future predictions, decisions
- Future Continuous - Ongoing future actions
- Future Perfect - Completion by future time
- Future Perfect Continuous - Duration until future point
- Connect your GitHub repository to Vercel
- Set environment variables in Vercel dashboard
- Deploy with automatic builds on push
This project is licensed under the MIT License. You are an Engineer AI Agent. Build a web app “GrammarLab” for English grammar learning focused on the 12 basic tenses. Follow the product spec below exactly. Deliver production-quality code (Next.js/React + Tailwind + Node/Edge routes + PostgreSQL/Supabase), OpenAI API integration, i18n (en/vi), and JSON-schema validation.
MISSION & LEARNING PRINCIPLES
- Goal: Help learners master 12 tenses via Explain → Example → Practice → Feedback → Spaced review.
- Principles: Micro-chunking; Active recall (MCQ); Contrastive examples; Error-driven review; Real-life contexts; EN-first with short VI support.
SCOPE (MVP FEATURES)
- Grammar Q&A (chat) focused on 12 tenses.
- Learn: 12 Tenses module (definition, forms, usage, markers, pitfalls, contrasts, examples).
- Practice: Generate randomized MCQ quizzes (15–30 Qs), seedable, varying stems/distractors.
- Results: Instant scoring + detailed explanations per item; EN with optional short VI lines.
- Personalized Review: Track user mistakes by concept_tag; “Practice weak spots”.
- OpenAI integration with a dedicated System Prompt; deterministic for grading; mild randomness for examples.
- Basic analytics: accuracy by topic, hardest items, completion time.
INFORMATION ARCHITECTURE
- / (Home)
- /learn (grid of 12 tenses)
- /learn/[tenseId]
- /practice (Quick Quiz: choose topics/length/difficulty)
- /practice/review (My Weak Spots)
- /ask (Grammar Q&A)
- /progress
DATA MODEL (sketch)
- users(id, email, locale, created_at)
- quiz_sessions(id, user_id, quiz_json, created_at)
- results(id, quiz_session_id, score, breakdown_json, created_at)
- mistake_events(id, user_id, qid, concept_tag, created_at)
- tenses(id, json) // cached/seeded cards
TECH REQUIREMENTS
- Next.js (App Router), React, Tailwind, Typescript.
- API routes:
- POST /api/quiz/generate
- POST /api/quiz/grade
- GET /api/learn/tenses/:id
- GET /api/review/recommend
- OpenAI SDK (Responses API). Validate & sanitize all LLM JSON with zod (or similar). Retry/backoff. Rate limit.
- Cache tense cards (ISR/edge) and gold examples; quizzes are generated per request with seed.
- Accessibility (keyboard nav, aria), responsive, high contrast. i18n (en/vi toggle).
OPENAI — SYSTEM PROMPT (core, use for all calls unless overridden) “You are an English Grammar Tutor specialized in the 12 basic tenses. Be concise, structured, and accurate. Produce natural examples (A2–B2). Focus on grammar, compare near-confusable tenses, and generate high-quality MCQs with clear right/wrong rationales. When locale=vi, add short Vietnamese support lines after the English explanations. Keep scope strictly to grammar.”
LLM I/O CONTRACTS (strict JSON; no extra text)
-
Generate Quiz (MCQ) Schema: { "quiz_id": "string", "meta": { "topics": ["present_simple"], "difficulty": 1-5, "length": 15-30, "seed": 12345 }, "items": [ { "qid": "string", "type": "mcq", "stem": "string", "context": "string optional", "options": ["A", "B", "C", "D"], "answer_index": 0-3, "concept_tags": ["present_simple","subject_verb_agreement"], "explanation_key": "string" } ] }
-
Grade & Explain (given user_answers[]) Schema: { "quiz_id": "string", "score": { "correct": 0, "total": 20, "percent": 0-100 }, "items": [ { "qid": "string", "user_answer_index": 0-3, "is_correct": true/false, "correct_index": 0-3, "explanation": { "en": "short rationale…", "vi": "ngắn gọn… (optional if locale=vi)" }, "remedial_tip": "concise tip" } ], "review_suggestions": ["subject_verb_agreement","present_perfect_vs_past_simple"] }
-
Tense Card (for Learn pages) Schema: { "tense_id": "present_simple", "name": "Present Simple", "forms": { "affirmative": "S + V(s/es)", "negative": "S + do/does not + V", "question": "Do/Does + S + V?" }, "usage_rules": ["Habits","General truths"], "time_markers": ["always","usually","often"], "pitfalls": ["forgetting -s/es with he/she/it"], "minimal_pairs": ["Present Simple vs Present Continuous"], "examples": { "good": ["She works from home.","Water boils at 100°C."], "contrast": ["I am working now. (Present Continuous)"] } }
ENDPOINT BEHAVIOR
POST /api/quiz/generate
- Body: { topics|tense_ids, difficulty, length (15–30), seed, locale }
- Use USER prompt:
"""
Create a JSON quiz strictly following the Generate Quiz schema.
Constraints:
- level: A2–B2, locale: {{locale}}
- topics/tense_ids: {{topics_or_tenses}}
- length: {{length}}
- difficulty: {{difficulty}}
- plausible, non-ambiguous distractors; vary stems.
- include concept_tags per item; set explanation_key. Seed: {{seed}} Return ONLY JSON. """
- Params: temperature=0.3, top_p=0.9.
- Validate with zod; if invalid, repair pass (ask model to respond with valid JSON only).
POST /api/quiz/grade
- Body: { quiz_json, user_answers[], locale }
- Use USER prompt:
"""
Given quiz JSON and user_answers[], produce grading JSON per schema.
Rules:
- Compare indices, compute score.
- For each item, explain concisely (EN + short VI if locale=vi), cite the rule.
- Provide 1 remedial_tip per wrong item.
- Aggregate 2–4 review_suggestions from wrong concept_tags. Return ONLY JSON. """
- Params: temperature=0.2.
- Store results + mistake_events(concept_tags from wrong items).
GET /api/learn/tenses/:id
- Serve cached seeded card. If missing, call: USER prompt: """ Generate a tense card JSON for {{tense_id}} (A2–B1) strictly per schema. Return ONLY JSON. """
- Cache with ISR; admin can override with curated content.
GET /api/review/recommend
- Build topics from user’s top mistake_events over recent N sessions.
- Call /api/quiz/generate with those topics and medium difficulty.
UX / UI REQUIREMENTS
- Learn page: grid of 12 TenseCards → each tense page sections: Summary → Forms → Usage → Markers → Pitfalls → Contrast → Examples → CTA “Practice this tense”.
- Practice flow: pick (topic/length/difficulty) → one question per screen; progress bar; shuffle options; “Flag for review”.
- Results: score; distribution by concept_tag; list with expandable explanations; CTA “Practice weak spots”.
- Localization: en/vi toggle; keep EN primary, add short VI summaries when locale=vi.
- Accessibility: keyboard nav, aria labels, color contrast. Responsive.
QUALITY BARS & METRICS
- 100% valid JSON from LLM (post-validated).
- Explanations for 100% items on submit (EN + short VI if locale=vi).
- Quiz duplication control (hash stems; avoid ≥30% overlap for immediate retries).
- Latency targets (p50): generate <4s; grade <3s.
- Learning telemetry: accuracy by concept_tag; hardest items; time per item.
SECURITY & PRIVACY
- Do not persist raw prompts with PII.
- Sanitize user input; strip prompt-injection attempts.
- Apply rate limiting.
DELIVERABLES
- Running Next.js app with pages, components (TenseCard, QuestionMCQ, ResultsBreakdown, ExplanationAccordion), and i18n.
- API routes implemented as above, wired to OpenAI Responses API.
- JSON schemas + zod validators + repair step.
- Seed: preload all 12 tense cards via generator; store/cached.
- Basic analytics & error tagging.
NON-GOALS (MVP)
- Speaking/pronunciation, advanced writing correction, CEFR above B2.
START NOW. Output production code and infra necessary to run locally (dev) and deploy (e.g., Vercel + Supabase). Ensure environment variables for OpenAI/Supabase; provide README with setup steps.