Skip to content

sythang/grammarLab

Repository files navigation

GrammarLab - Master English Grammar

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.

🤖 AI-Powered 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.

🎯 Mission & Learning Principles

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

🚀 Features

  1. Grammar Q&A (Chat) - AI-powered grammar tutor focused on 12 tenses
  2. Learn Module - Comprehensive lessons for each tense with definitions, forms, usage, markers, pitfalls, and examples
  3. Practice Quizzes - Randomized MCQ quizzes (15-30 questions) with varying difficulty
  4. Instant Results - Detailed scoring and explanations for each question
  5. Personalized Review - Track mistakes and practice weak spots
  6. OpenAI Integration - AI-generated content with deterministic grading
  7. Analytics - Accuracy by topic, progress tracking, completion time
  8. i18n Support - English/Vietnamese language toggle
  9. User Authentication - Supabase Auth with email/password login
  10. User History - Track quiz sessions and performance over time
  11. Leaderboards - Global ranking with privacy options

🏗️ Architecture

Tech Stack

  • 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

Information Architecture

/ (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

📊 Data Model

Core Tables

  • 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

Schema Highlights

  • 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 Endpoints

Authentication

  • /api/auth/* - Supabase Auth endpoints for login/signup/logout

Learning

  • /api/learn/tenses/[id] - Get tense information by ID

Quiz System

  • /api/quiz/generate - Generate a new quiz based on parameters
  • /api/quiz/grade - Grade a submitted quiz and store results

User Data

  • /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

🛠️ Setup Instructions

Prerequisites

  • Node.js 18+ and npm
  • Supabase account (free tier works fine)
  • OpenAI API key

Environment Variables

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

Database Setup

  1. Create a new Supabase project
  2. Run the SQL from supabase/updated_schema.sql in the SQL Editor
  3. Run the SQL from supabase/functions.sql to add database functions
  4. Seed the tenses data using the script:
npm run seed-tenses

Installation & Development

# Install dependencies
npm install

# Run development server
npm run dev

🧠 Data Features Implementation

Results & History

  • 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

Progress Tracking

  • Timeline view shows performance over time
  • Tense-specific stats highlight strengths and weaknesses
  • Top problem concepts identify specific grammar issues

Weak Spots Analysis

  • Algorithm considers both frequency and recency of mistakes
  • Weighted scoring prioritizes recurring problems
  • Recommendations for focused review

Leaderboard

  • Global ranking based on average scores
  • Privacy controls (opt-out option)
  • Time-based filtering (7d, 30d, 90d, all-time)

📝 Development Notes

Type Safety

All API contracts are defined with Zod schemas in the /src/types directory:

  • index.ts - Core types and schemas
  • history.ts - Quiz history and results schemas
  • progress.ts - Progress tracking schemas
  • weak-spots.ts - Weak spots analysis schemas
  • leaderboard.ts - Leaderboard schemas

Security

  • 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

Performance

  • Database indexes on frequently queried columns
  • SQL functions for efficient aggregation operations
  • Pagination for potentially large result sets

🧠 AI Development Process

This project showcases the capabilities of modern AI-assisted development:

Development Workflow

  1. Conceptualization: Human-defined educational requirements and user experience goals
  2. Architecture Design: AI-generated full-stack architecture with modern best practices
  3. 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

AI Collaboration Benefits

  • 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-AI Partnership

  • 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:

Installation

  1. Clone and install dependencies:
npm install
  1. Set up Supabase database:

    • Create a new Supabase project
    • Run the SQL schema from supabase/updated_schema.sql in 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
  2. Configure OpenAI:

    • Get your API key from OpenAI dashboard
    • Add it to .env.local
  3. Seed tense data:

npm run seed:tenses
  1. Start development server:
npm run dev

The application will be available at http://localhost:3000.

Supabase Row Level Security

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

🤖 OpenAI Integration

System Prompt

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."

API Endpoints

POST /api/quiz/generate

Generates randomized MCQ quizzes with specified parameters.

POST /api/quiz/grade

Grades user answers and provides detailed explanations.

GET /api/learn/tenses/[id]

Retrieves or generates tense learning cards.

GET /api/review/recommend

Provides personalized review recommendations based on user mistakes.

📚 Learning Content

12 English Tenses Covered

  1. Present Simple - Habits, general truths
  2. Present Continuous - Current actions, temporary situations
  3. Present Perfect - Completed actions with present relevance
  4. Present Perfect Continuous - Ongoing actions from past to present
  5. Past Simple - Completed past actions
  6. Past Continuous - Ongoing past actions
  7. Past Perfect - Earlier past actions
  8. Past Perfect Continuous - Duration before past point
  9. Future Simple - Future predictions, decisions
  10. Future Continuous - Ongoing future actions
  11. Future Perfect - Completion by future time
  12. Future Perfect Continuous - Duration until future point

🚀 Deployment

Vercel Deployment

  1. Connect your GitHub repository to Vercel
  2. Set environment variables in Vercel dashboard
  3. Deploy with automatic builds on push

📝 License

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)

  1. Grammar Q&A (chat) focused on 12 tenses.
  2. Learn: 12 Tenses module (definition, forms, usage, markers, pitfalls, contrasts, examples).
  3. Practice: Generate randomized MCQ quizzes (15–30 Qs), seedable, varying stems/distractors.
  4. Results: Instant scoring + detailed explanations per item; EN with optional short VI lines.
  5. Personalized Review: Track user mistakes by concept_tag; “Practice weak spots”.
  6. OpenAI integration with a dedicated System Prompt; deterministic for grading; mild randomness for examples.
  7. 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)

  1. 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" } ] }

  2. 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"] }

  3. 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

  1. Running Next.js app with pages, components (TenseCard, QuestionMCQ, ResultsBreakdown, ExplanationAccordion), and i18n.
  2. API routes implemented as above, wired to OpenAI Responses API.
  3. JSON schemas + zod validators + repair step.
  4. Seed: preload all 12 tense cards via generator; store/cached.
  5. 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.

About

AI-powered English learning platform with smart quizzes, progress tracking, and adaptive feedback — built entirely through vibe-coding with AI Tools & AI Agents.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors