> ## 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 Tutor & Mobile AI Mentor Architecture

> Deep dive into contextual in-lesson tutoring (AiTutorService) vs persistent mobile mentorship, prompt engineering, and catalog guardrails.

# AI Tutor & Mobile AI Mentor Architecture

LearnWay distinguishes between two complementary AI personas:

1. **The In-Lesson AI Tutor**: A micro-contextual teaching assistant embedded into every lesson slide.
2. **The Mobile AI Mentor**: A persistent companion guiding long-term career growth, consistency, and skill milestones.

***

## 1. In-Lesson AI Tutor

The AI Tutor is designed for immediate, zero-friction help while a learner is actively consuming a lesson.

### Preset Interaction Modes

Learners can choose predefined one-tap prompts or submit custom questions:

| Mode (`promptType`) | Prompt Template                                                                                   | Pedagogical Intent                                     |
| :------------------ | :------------------------------------------------------------------------------------------------ | :----------------------------------------------------- |
| `explain_simply`    | *"Explain the main concept of this lesson in simple terms a complete beginner would understand."* | Deconstructs abstract concepts using simple analogies. |
| `summarize`         | *"Give me a concise summary of this lesson in 3-5 bullet points."*                                | Reinforces memory retention and key takeaways.         |
| `example`           | *"Give me a concrete, real-world example that illustrates the main idea of this lesson."*         | Grounds theoretical lessons in practical application.  |
| `key_takeaways`     | *"What are the 3 most important things I should remember from this lesson?"*                      | High-yield review before quiz checkpoints.             |
| `custom`            | Learner-authored question evaluated against lesson context.                                       | Interactive Socratic clarification.                    |

### System Prompt & Context Assembly

The AI Tutor enforces strict guardrails directly in the Gemini system instruction:

```typescript theme={null}
export const SYSTEM_PROMPT_TEMPLATE = `You are a LearnWay AI Tutor. Your job is to help learners understand lesson content through simple, clear, beginner-friendly explanations. You must:
- Stay strictly focused on the lesson content provided below.
- Never answer questions unrelated to the lesson.
- Keep responses under 150 words.
- Use plain language suitable for the stated difficulty level.
- Include one practical, real-world example when it adds clarity.

If asked something unrelated to the lesson, respond only with: "That's outside this lesson — I can only help with what we're learning here."

Lesson Context:
{LESSON_CONTEXT}`;
```

### Response Caching Strategy

Because many students ask identical preset questions (`explain_simply`, `summarize`) on standard lessons, responses are deterministically cached in Redis with a 24-hour TTL:

```text theme={null}
CacheKey = ai:cache:{lessonId}:{promptType}
```

* **Preset Prompts**: 100% cache hit rate for subsequent learners, reducing Gemini API costs to near zero and delivering `< 15ms` response times.
* **Custom Questions**: Bypasses the preset cache, performs profanity and rate-limit checks, calls Gemini Flash with a 5000ms race timeout, and logs to `ai_analytics_logs`.

***

## 2. Mobile AI Mentor

The AI Mentor is a persistent, motivational guide residing on the mobile client. It understands the student's broader journey, course progress, daily streaks, and career aspirations.

```mermaid theme={null}
flowchart TD
    subgraph MobileClient["📱 Mobile App (ai_mentor)"]
        UserAction["Student Profile / Career Goal / Chat Query"]
    end

    subgraph MentorPipeline["🤖 AI Mentor Pipeline (learnway-ai-service)"]
        CatalogLoader["Course Catalog Service\n(Live Verified Database Snapshot)"]
        ProfileBuilder["Learner Telemetry Builder\n(XP, Badges, Streaks, Assessment Scores)"]
        GuardrailInjector["Catalog Guardrail & Foundation-First Injector"]
        GeminiExecution["Google Gemini 2.5 Flash"]
        ResponseValidator["JSON Schema Validator & Course Name Verifier"]
    end

    UserAction --> ProfileBuilder
    ProfileBuilder --> GuardrailInjector
    CatalogLoader --> GuardrailInjector
    GuardrailInjector --> GeminiExecution
    GeminiExecution --> ResponseValidator
    ResponseValidator -->|Structured Journey Insights| MobileClient
```

### Strict Course Catalog Guardrail

To prevent the model from inventing imaginary topics or external university curricula, the mentor prompt is injected with the verified LearnWay course catalog as its single source of truth:

```typescript theme={null}
export const MENTOR_CATALOG_GUARDRAIL = `STRICT SCOPE RULES — read before answering:
- LearnWay only offers the courses and lessons listed in the "LearnWay Course Catalog" section below. This catalog is the single source of truth.
- You may ONLY recommend, reference, or name courses and lessons that appear in the catalog, and you must use their exact titles.
- NEVER invent, assume, or suggest any subject, course, topic, skill path, or lesson that is not in the catalog.
- If the learner asks about or aims for something LearnWay does not currently offer, clearly tell them it is not available on LearnWay yet, then guide them to the closest relevant course(s) that do exist in the catalog.`;
```

### The Foundation-First Rule

Regardless of whether a student's long-term goal is AI Engineering, Blockchain, or Web Development, the AI Mentor enforces that all foundational tracks must be completed before specialized elective tracks are unlocked:

```typescript theme={null}
export const MENTOR_FOUNDATION_FIRST_RULE = `FOUNDATION-FIRST RULE:
- Always encourage and prioritize the Foundation Learning Paths listed under "Learning Path Status" below — they are required for every learner, independent of their career goal.
- Only recommend Specialization Learning Paths if they are explicitly unlocked. If locked, explain that they unlock after completing more Foundation Learning Path courses.`;
```

### Journey Telemetry & Scoring

The AI Mentor computes structured diagnostic scoring for every learner:

* **Consistency Score (`0-100`)**: Evaluates streak stability, weekly active days, and learning cadence.
* **Engagement Score (`0-100`)**: Tracks quiz battle participation, lesson completion velocity, and interactive exercises.
* **Employability Score (`0-100`)**: Measures practical project completions, capstone submissions, and verified certificates.
* **Actionable Next Steps**: Generates 3 prioritized next actions directly linked to concrete lessons in the catalog.

***

## Technical Comparison

| Dimension         | In-Lesson AI Tutor                       | Mobile AI Mentor                                         |
| :---------------- | :--------------------------------------- | :------------------------------------------------------- |
| **Service Host**  | `learnway-backend` (Monolith)            | `learnway-ai-service` (Microservice)                     |
| **Context Scope** | Active slide and current lesson only     | Full learner profile, catalog, and career history        |
| **Model**         | `gemini-2.5-flash` (`thinkingBudget: 0`) | `gemini-2.5-flash` (Structured Output)                   |
| **Output Format** | Markdown text (\< 150 words)             | Structured JSON (Telemetry) / Conversational Text (Chat) |
| **Caching**       | 24-hour deterministic Redis cache        | Dynamic profile cache + WebSocket streaming              |
| **Rate Limiting** | 5 per lesson / 20 per day (configurable) | Dedicated daily mentor allowance                         |
