> ## Documentation Index
> Fetch the complete documentation index at: https://docs.learnway.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# AI & Intelligence Infrastructure Overview

> High-level architecture of LearnWay AI subsystem: Google Gemini model integration, dual-tier monolith & microservice execution, RAG context injection, and Redis acceleration.

# AI & Intelligence Infrastructure Overview

LearnWay is architected from the ground up as an **AI-powered learning platform**. Rather than treating artificial intelligence as an isolated chatbot add-on, LearnWay embeds Google Gemini generative intelligence across every layer of the learner lifecycle—from initial onboarding assessments and contextual lesson tutoring, to persistent career mentorship, automated quiz generation, and multilingual curriculum localization.

```mermaid theme={null}
flowchart TB
    subgraph Client["📱 Mobile Client (learnway-mobile / ai_mentor)"]
        TutorUI["In-Lesson AI Tutor Sheet"]
        MentorUI["Persistent AI Mentor Tab"]
        AssessmentUI["Adaptive Assessment & Career Roadmaps"]
    end

    subgraph CorePlatform["⚡ Core Platform (learnway-backend)"]
        TutorController["AiTutorController (/api/v2/ai-tutor)"]
        TutorService["AiTutorService"]
        AssessmentService["AiAssessmentService"]
        RoadmapService["CareerRoadmapService"]
        RedisCache["Redis Response Cache (24h TTL) & Circuit Breakers"]
    end

    subgraph AIService["🤖 AI Microservice (learnway-ai-service)"]
        MentorModule["AI Mentor Service & Journey Tracker"]
        QuizStudio["AI Quiz Studio (Automated Question Synthesis)"]
        TranslationEngine["AI Translation Engine (Two-Step Hybrid Pipeline)"]
        AnalyticsModule["AI Analytics & Interaction Telemetry"]
    end

    subgraph GeminiCluster["🧠 Google Cloud & Gemini AI Models"]
        GeminiFlash["Google Gemini 2.5 Flash\n(Sub-second Latency, Zero Thinking Budget)"]
        GeminiPro["Google Gemini 1.5 Pro\n(Deep Multimodal Reasoning & Capstone Grading)"]
        GoogleTranslate["Google Cloud Translate v2"]
    end

    %% Client Interactions
    TutorUI -->|POST /ai-tutor/ask| TutorController
    TutorController --> TutorService
    MentorUI -->|REST / WebSocket| MentorModule
    AssessmentUI --> AssessmentService
    AssessmentUI --> RoadmapService

    %% Core Services to Redis & Gemini
    TutorService -->|1. Check Cache / Limits| RedisCache
    TutorService -->|2. Context Injection & Execution| GeminiFlash
    AssessmentService -->|Multimodal Evaluation| GeminiPro
    RoadmapService -->|Catalog-Enforced Prompting| GeminiFlash

    %% AI Microservice to Gemini & Models
    MentorModule -->|Profile Telemetry & Guardrails| GeminiFlash
    QuizStudio -->|Curriculum Ingestion| GeminiFlash
    TranslationEngine -->|Step 1: Base Translation| GoogleTranslate
    TranslationEngine -->|Step 2: Contextualization| GeminiFlash
    AnalyticsModule -->|Audit Telemetry| PostgresDB[("PostgreSQL\n(ai_analytics_logs)")]
```

***

## Dual-Tier AI Architecture

LearnWay implements a dual-tier execution model for AI capabilities, balancing immediate learner responsiveness with scalable asynchronous processing:

### 1. In-Monolith AI Services (`learnway-backend`)

* **Scope**: Direct, synchronous, and latency-critical learning workflows.
* **Responsibilities**:
  * **In-Lesson AI Tutor**: Instant slide-level explanations, summaries, and hints directly within active lessons.
  * **Project & Code Assessment**: Automated evaluation of project deliverables and capstone code submissions.
  * **Career Roadmap Synthesis**: Dynamic creation of customized learning paths based on individual career goals.
  * **Tier-1 Safety & Caching**: Redis-backed rate limiting, profanity filtering, and 24-hour deterministic response caching.

### 2. Dedicated AI Microservice (`learnway-ai-service`)

* **Scope**: Complex, agentic, multi-step, and resource-intensive AI domains.
* **Modules**:
  * **`ai-mentor/`**: Persistent mobile companion tracking learner consistency, employability, and growth trajectory.
  * **`ai-quiz-studio/`**: Automated curriculum-aligned question generation, distractor validation, and taxonomy calibration.
  * **`ai-translation/`**: Two-step hybrid localization pipeline translating learning content into African regional languages.
  * **`ai-analytics/`**: Interaction telemetry, latency monitoring, prompt token accounting, and learner satisfaction metrics.

***

## Model Selection & Inference Strategy

LearnWay leverages the **Google Gemini** model family, matching model capabilities to specific pedagogical tasks:

| Use Case                        | Model Target                         | Configuration                                 | Latency SLA  | Key Objective                                  |
| :------------------------------ | :----------------------------------- | :-------------------------------------------- | :----------- | :--------------------------------------------- |
| **In-Lesson AI Tutor**          | `gemini-2.5-flash`                   | `thinkingBudget: 0`, max 150 words            | `< 1200ms`   | Instant clarity without cognitive overload     |
| **AI Mentor Conversations**     | `gemini-2.5-flash`                   | Conversational prompt with Catalog Guardrails | `< 1500ms`   | Motivational, contextual career guidance       |
| **Onboarding Skill Assessment** | `gemini-2.5-flash`                   | `responseMimeType: 'application/json'`        | `< 2000ms`   | Structured diagnostic evaluation               |
| **Capstone Project Grading**    | `gemini-1.5-pro`                     | Multimodal (Code, PDF, Images)                | `< 4500ms`   | In-depth criteria rubric & feedback            |
| **AI Quiz Studio Synthesis**    | `gemini-2.5-flash`                   | JSON schema with distractor validation        | Batch        | High-quality multiple-choice questions         |
| **Multilingual Localization**   | `gemini-2.5-flash` + Cloud Translate | Two-step prompt with syntax preservation      | Asynchronous | Culturally contextualized African translations |

***

## Retrieval-Augmented Generation (RAG) & Context Engineering

To eliminate hallucinations and keep AI responses grounded strictly in vetted educational material, LearnWay utilizes a **Deterministic RAG & Context Injection Pipeline**:

```
[Incoming Request]
       │
       ▼
[Profanity & Guardrail Filter] ──(Rejected)──► [400 Clean Language Required]
       │
       ▼
[Context Builder]
 ├── Active Slide Content
 ├── Preceding Lesson Hierarchy
 ├── Verified Course Catalog (Single Source of Truth)
 └── Learner Skill Profile
       │
       ▼
[Prompt Assembly & Token Budget (< 3,000 chars)]
       │
       ▼
[Cache Check (Redis)] ──(Cache Hit)──► [Return Cached Response (0ms LLM)]
       │ (Cache Miss)
       ▼
[Promise.race([ Gemini API, 5000ms Timeout ])]
       │
 ┌─────┴────────────────────────┐
 │ (Success)                    │ (Timeout / Failure)
 ▼                              ▼
[Audit Log & 24h Cache]   [Graceful Fallback / Circuit Breaker]
```

### Context Boundary Guarantees:

1. **Catalog Truth**: The AI Mentor is strictly constrained to the official `Course Catalog`. It is programmatically forbidden from recommending nonexistent courses or fabricated subjects.
2. **Foundation-First Sequencing**: Prompts enforce that foundational learning tracks must be completed before specialized elective tracks are recommended.
3. **Concise Pedagogical Framing**: AI Tutor system prompts enforce a strict 150-word ceiling with plain language to prevent overwhelming mobile learners.

***

## Subsystem Navigation

Explore the dedicated AI architecture guides for deeper implementation specifics:

* [AI Tutor & Mobile AI Mentor](/architecture/ai/tutor-and-mentor): Prompt templates, conversational flows, and catalog guardrails.
* [AI Assessments & Personalization](/architecture/ai/assessment-and-personalization): Dynamic onboarding diagnostic, capstone evaluations, and career roadmaps.
* [AI Content Workflows & Translation](/architecture/ai/content-workflows-and-translation): Automated Quiz Studio and hybrid multilingual translation engine.
* [AI Governance, Resilience & Safety](/architecture/ai/governance-and-resilience): Multi-tier guardrails, circuit breakers, timeout races, and audit telemetry.
