Skip to content

KidStory: Storybook for Kids

KidStory Logo
AI-Powered Interactive Storybooks for Children
Speak a story. Watch it come to life — in your language.

Overview

KidStory is an AI-powered platform that transforms a child's spoken or typed story idea into a fully illustrated, narrated, and interactive storybook — in 21 languages. The app orchestrates multiple Gemini models via Vertex AI in a clean 3-step pipeline: story text generation, per-page illustration, and TTS narration. A multilingual interactive quiz follows each story.

Screenshot: DashboardDashboard

Screenshot: Create-storycreate-story

Screenshot: Storybook-pagestorybook-page

Screenshot: QuizQuiz

For Parents

Register an account, then create stories for your children to read and enjoy together.

For Kids

Let your child speak their own story idea and watch the AI bring it to life with pictures and narration — in their own language!

Key Features

  • Voice & Text Input: Children can speak or type their story ideas (voice disabled for unsupported languages)
  • 21 Languages: English, Spanish, French, Portuguese (Brazil), Portuguese (Portugal), German, Italian, Japanese, Korean, Chinese, Arabic, Hindi, Indonesian, Russian, Vietnamese, Malay, Filipino, Tetum, Burmese, Lao, Khmer
  • 3-Step AI Pipeline: Story text → watercolor illustrations → TTS narration (clean sequential generation)
  • Character Consistency: Upload character photos to maintain appearance across all illustrations
  • Narrator Voices: Language-appropriate narrator voices auto-selected per language
  • Interactive Storybooks: Page-turning interface with audio narration for each page
  • Multi-Type Magic Quiz: Three question types — multiple choice (A/B/C), true/false, and fill-in-the-blank — all generated in the story's language
  • Language Stored in DB: The language field is saved with every story in Firestore so quizzes always generate in the correct language
  • Language Badge on Dashboard: Story cards show a flag badge for non-English stories
  • Progress Tracking: Two-column live progress UI during generation (steps left, page content right)
  • Child-Safe Content: Built-in guardrails ensure age-appropriate content for children 5–12
  • User Library: Save and revisit all created stories
  • Credit System: Free plan (30 credits/month) and Pro plan (150 credits/$4.99/month). Story = 5 credits, Quiz = 1 credit. Credits deducted server-side after safety check. Monthly auto-reset.
  • Story Map (/story-map): Visual interactive map showing where stories take place based on keyword detection
  • Character Collection (/characters): Gallery of characters extracted from story imagePrompts
  • Profile Page (/profile): User profile with achievements, credits, and personalized AI recommendations
  • Badge System: 12 custom badges with .webp artwork (not emojis) — earned through reading, quizzes, and exploration
  • Page Flip Animation: 3D perspective-based page turn effect (PageTurn.tsx)
  • Print Book (Coming Soon): $9 USD per printed book, delivery to Dili, Timor-Leste
  • Quiz Fallback: fill_blank type falls back to multiple_choice if generation fails
  • Cost Tracking: Dev-only token usage logging to log/ folder with cost-report.ts script
  • Safety Progress Bar: Visual 0-100% progress during content safety check
  • Cover Generation: Dedicated cover image step shown in progress UI
  • Shared DashboardNavbar: Consistent navigation component across all dashboard pages
  • EndPage Redesign: Dark/light theme support on story end page
  • Firestore Security Rules: Server-side rules in firestore.rules
  • Server-Side Credit Deduction: lib/credits/serverCredits.ts using Firebase Admin SDK

Technology Stack

Frontend

  • Framework: Next.js 16 (App Router)
  • UI Library: React 18
  • Language: TypeScript 5
  • Styling: Tailwind CSS 4
  • Animations: Framer Motion 12

Backend & AI

  • Agent Framework: Google Agent Development Kit (ADK) v1.0 — LlmAgent, FunctionTool, InMemoryRunner — orchestrates 9 specialized agents
  • AI Models (via Google Cloud Vertex AI):
    • gemini-2.5-pro — Story text generation (multilingual) & quiz generation
    • gemini-2.5-flash-image — Per-page watercolor illustrations
    • gemini-2.5-flash-preview-tts — TTS narration in story language
  • AI SDK: @google/genai with vertexai: true (single SDK for all Gemini calls)
  • Database: Firebase Firestore — stories stored with language field
  • Authentication: Firebase Auth (Google OAuth)
  • Storage: Google Cloud Storage (images & audio, 7-day signed URLs)
  • Hosting: Google Cloud Run

Development Tools

  • Package Manager: npm
  • Linting: ESLint 9
  • Build: Next.js
  • CI/CD: Google Cloud Build (cloudbuild.yaml)

Complete Diagram Architecture

Click here to view the full diagram in a new tab.

KidStory - Complete Diagram Architecture

AI Generation Pipeline

1. User Input    → Voice/Text idea + Language selection
2. Safety Check  → SafetyGuardian agent (keyword regex + LLM, progress bar 0-100%)
3. Credit Deduct → 5 credits deducted server-side (only after safety passes)
4. Story Text    → gemini-2.5-pro (text-only stream, story in chosen language)
5. Illustrations → gemini-2.5-flash-image (per page, prompts always in English)
6. Cover Image   → gemini-2.5-flash-image (cover generation step in progress UI)
7. Narration     → gemini-2.5-flash-preview-tts (TTS in story language)
8. Storage       → Save to Firestore (with language field) + GCS
9. Quiz          → gemini-2.5-pro generates mixed-type questions in story language
                   (1 credit deducted, fill_blank falls back to multiple_choice)

Language Flow

Language selected → story text in language
                  → image prompts kept in English (model compatibility)
                  → TTS in language
                  → language saved to Firestore
                  → quiz questions in language (from Firestore language field)
                  → TTS feedback in language

Key Technical Components

Frontend Hooks:

  • useStoryGenerator — Streaming story text generation with language support and live page preview
  • useStoryAssembler — Coordinates sequential image + parallel audio generation, saves language to Firestore
  • useVoiceInput — Speech recognition with BCP-47 locale per language (disabled for unsupported languages)
  • useUserStories — Firestore story library with language field
  • useAuth — Firebase authentication wrapper

API Routes:

  • /api/generate-story — Streams story JSON from gemini-2.5-pro with language instruction
  • /api/generate-image — Per-page illustrations from gemini-2.5-flash-image (English prompts)
  • /api/generate-audio — TTS narration from gemini-2.5-flash-preview-tts with language
  • /api/generate-cover — Dedicated cover image generation step
  • /api/generate-recommendation-audio — TTS audio for AI learning recommendation (English, saved to GCS)
  • /api/live-quiz — Multi-type quiz (multiple_choice / true_false / fill_blank) in story language, SSE stream
  • /api/save-story — Persists story + language field to Firestore
  • /api/save-quiz-score — Records quiz results
  • /api/learning-recommendation — LearningAdvisor agent: difficulty + themes + encouragement (RAG)
  • /api/parent-insights — ParentInsights agent: progress report + optional email (RAG)
  • /api/adapt-story — StoryAdaptation agent: calibrated story prompt from quiz history (RAG)
  • /api/agent-stats — Observability: call counts, durations, last-used per agent
  • /api/og-image/[storyId] — Generates the Open Graph share image for public stories
  • /api/update-streak — Updates user reading streak in Firestore
  • /api/redeem-referral — Redeem referral code for bonus credits

Core Components:

  • StoryBook — Main story reader with page-turning animations, passes language to quiz
  • LiveQuizModal — Multi-type quiz (no voice — tap/type only), fully multilingual
  • StoryCard — Dashboard card with language flag badge for non-English stories
  • CreateStoryPage — Story creation wizard with language picker modal (21 languages)

Getting Started

Prerequisites

  • Node.js 20+
  • Google Cloud Project with Vertex AI enabled
  • Firebase Project (Firestore + Authentication)
  • Google Cloud Storage bucket

Installation

  1. Clone and navigate

    bash
    git clone https://github.com/ajitonelsonn/torybook-for-Kids.git
    cd torybook-for-Kids/storybook-for-kids-app
  2. Install dependencies

    bash
    npm install
  3. Configure environment variables — create .env.local:

    env
    # Firebase Client
    NEXT_PUBLIC_FIREBASE_API_KEY=your_firebase_api_key
    NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=your_project.firebaseapp.com
    NEXT_PUBLIC_FIREBASE_PROJECT_ID=your_project_id
    NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=your_project.appspot.com
    NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=your_sender_id
    NEXT_PUBLIC_FIREBASE_APP_ID=your_app_id
    
    # Firebase Admin
    FIREBASE_CLIENT_EMAIL=service-account@project.iam.gserviceaccount.com
    GOOGLE_CLOUD_PROJECT=your_project_id
    GOOGLE_CLOUD_REGION=us-central1
    
    # Google Cloud Storage
    GCS_BUCKET_NAME=storybook-for-kids-media
    
    # Gemini Models (via Vertex AI)
    GEMINI_STORY_MODEL=gemini-2.5-pro
    GEMINI_IMAGE_MODEL=gemini-2.5-flash-image
    GEMINI_TTS_MODEL=gemini-2.5-flash-preview-tts
    
    # App
    NEXTAUTH_URL=http://localhost:3000
    NEXTAUTH_SECRET=your_secret_key_here
  4. Run development server

    bash
    npm run dev
  5. Open http://localhost:3000

Deployment

bash
# Deploy with one command (no Docker needed)
gcloud builds submit --config=cloudbuild.yaml

Project Structure

storybook-for-kids-app/
├── app/
│   ├── (auth)/login/               # Login page
│   ├── (dashboard)/
│   │   ├── dashboard/              # Story library dashboard
│   │   ├── characters/             # Character Collection gallery
│   │   ├── profile/                # User profile + achievements
│   │   ├── story-map/              # Visual story map
│   │   └── parent-insights/        # Parent insights page
│   ├── api/
│   │   ├── adapt-story/            # StoryAdaptation agent (RAG, calibrated prompt)
│   │   ├── agent-stats/            # Agent observability stats
│   │   ├── generate-audio/         # TTS narration (language-aware)
│   │   ├── generate-cover/         # Cover image generation
│   │   ├── generate-image/         # Per-page illustrations
│   │   ├── generate-recommendation-audio/ # Recommendation TTS audio
│   │   ├── generate-story/         # Story text stream (language-aware)
│   │   ├── learning-recommendation/ # LearningAdvisor agent (RAG)
│   │   ├── live-quiz/              # Multi-type multilingual quiz (SSE)
│   │   ├── og-image/               # Open Graph image generation
│   │   ├── parent-insights/        # ParentInsights agent (RAG + email)
│   │   ├── redeem-referral/        # Referral code redemption
│   │   ├── save-quiz-score/        # Quiz results
│   │   ├── save-story/             # Story + language field persistence
│   │   └── update-streak/          # Reading streak updates
│   ├── create/                     # Story creation (language picker)
│   └── story/[id]/                 # Story viewer (reads language from Firestore)
├── components/
│   ├── dashboard/
│   │   └── DashboardNavbar.tsx     # Shared navbar across all dashboard pages
│   ├── story/
│   │   ├── LiveQuizModal.tsx       # Multi-type quiz (tap/type, no voice)
│   │   ├── PageTurn.tsx            # 3D page flip animation
│   │   ├── StoryBook.tsx           # Story reader (passes language to quiz)
│   │   ├── StoryCard.tsx           # Dashboard card with language badge
│   │   └── StoryPage.tsx           # Individual story page
│   └── ui/
│       ├── LoadingSparkles.tsx
│       ├── PrintBookModal.tsx      # Print Book feature (Coming Soon)
│       └── Toast.tsx
├── lib/
│   ├── agents/
│   │   ├── storyOrchestrator.ts    # SafetyGuardian + StoryWriter ADK agents
│   │   ├── quizMasterAgent.ts      # QuizMaster + QuizFeedback ADK agents
│   │   ├── learningAgent.ts        # LearningAdvisor ADK agent (RAG)
│   │   ├── parentInsightsAgent.ts  # ParentInsights ADK agent (RAG)
│   │   └── storyAdaptationAgent.ts # StoryAdaptation ADK agent (RAG)
│   ├── credits/
│   │   ├── creditSystem.ts         # Client-side credit logic
│   │   └── serverCredits.ts        # Server-side credit deduction (Firebase Admin)
│   ├── firebase/                   # Firebase admin + client
│   ├── gcp/
│   │   ├── gemini.ts               # Model config + multilingual system prompt
│   │   ├── imagen.ts               # Image generation
│   │   ├── storage.ts              # GCS operations
│   │   └── tts.ts                  # TTS with language parameter
│   ├── hooks/
│   │   ├── useAchievements.ts      # Badge computation + persistence
│   │   ├── useCredits.ts           # Credit balance hook
│   │   ├── useStoryAssembler.ts    # Assembly + saves language to Firestore
│   │   ├── useStoryGenerator.ts    # Story text generation
│   │   ├── useUserStories.ts       # Library (reads language from Firestore)
│   │   └── useVoiceInput.ts        # Speech recognition with locale support
│   ├── observability/
│   │   └── costLogger.ts           # Dev-only token usage logging
│   └── utils/
│       └── badges.ts               # 12 badge definitions with .webp images
├── scripts/
│   └── cost-report.ts              # CLI cost report script
├── firestore.rules                 # Firestore security rules
├── document/                       # Documentation
├── types/                          # TypeScript definitions
├── cloudbuild.yaml                 # CI/CD (Cloud Build)
└── next.config.mjs

Documentation

DocumentDescription
How This App WorksAgentic workflow, model orchestration, multilingual pipeline, quiz types
Complete Diagram ArchitectureWorkflow diagram, sequence diagrams, credit flow, language flow, state machines
Database SchemaFirestore schema including language field, credits, achievements
Agent DocumentationAll 9 agents: SafetyGuardian, StoryWriter, Illustrator, Narrator, QuizMaster, QuizFeedback, LearningAdvisor, ParentInsights, StoryAdaptation
Credit SystemFree/Pro tiers, pricing, credit flow, cost projections
Cost TrackingDev-only token usage logging, cost report script
Story MapVisual map with keyword-based location detection
Character CollectionCharacter gallery extracted from story imagePrompts
Profile & Badges12 custom badges with .webp artwork, profile page
Page Flip Animation3D perspective-based page turn effect
Cover GenerationDedicated cover image step, prompt structure, GCS storage
Recommendation AudioTTS audio for AI learning recommendation on profile page
Observability DashboardAgent Pipeline tab: call counts, durations, last-used per agent
Reading StreakDaily streak tracking and display
Referral SystemReferral codes, bonus credits, double-redeem prevention
UI Language (i18n)next-intl UI translation — English + Tetum, cookie-based toggle (separate from story-content language)
Story AdaptationStoryAdaptation agent: adaptive learning loop from quiz scores
Challenge RequirementsHow the project meets Google for Startups AI Agents Challenge criteria
Deployment GuideCloud Run deployment, IAM setup, environment variables

Usage Guide

Creating a Story

  1. Sign in with Google account
  2. Click "New Story" from dashboard
  3. Choose input method: Voice or text
  4. Select language (tap the language button to open the picker — 18 options)
  5. Speak or type your story idea in the chosen language
  6. Optional: Upload character photos and name them
  7. Select page count (4, 5, or 6 pages)
  8. Click "Create My Story"
  9. Watch the magic: live two-column progress — steps on left, page content appearing on right

Reading a Story

  1. Open story from your library (non-English stories show a language flag badge)
  2. Turn pages with arrow keys or click arrows
  3. Listen to narration in the story's language
  4. Take the quiz after finishing

Quiz

  • No voice input — answer by tapping or typing
  • 3 question types cycle each quiz: multiple choice → true/false → fill-the-blank
  • All questions, options, and feedback are in the story's language
  • Scores are saved per story

Environment Variables Reference

VariableDescriptionDefault
NEXT_PUBLIC_FIREBASE_*Firebase client config
FIREBASE_CLIENT_EMAILService account email
GOOGLE_CLOUD_PROJECTGCP project IDstorybook-for-kids
GOOGLE_CLOUD_REGIONVertex AI regionus-central1
GCS_BUCKET_NAMEStorage bucketstorybook-for-kids-media
GEMINI_STORY_MODELStory text, quiz, and all agents modelgemini-2.5-pro
GEMINI_IMAGE_MODELIllustration modelgemini-2.5-flash-image
GEMINI_TTS_MODELTTS narration modelgemini-2.5-flash-preview-tts
FIREBASE_PRIVATE_KEYFirebase Admin SDK private key
EMAIL_SERVERSMTP host for parent email reports
EMAIL_PORTSMTP port587
EMAIL_USERSMTP sender address
EMAIL_PASSSMTP password
APP_URLApp base URL for email linkshttps://ai.kidstory.app
NEXTAUTH_URLApp URL
NEXTAUTH_SECRETAuth secret

Made with ❤️ for children everywhere

Released under the MIT License.