Spaces:
Sleeping
Sleeping
| # π§ HALE β Adaptive Learning Engine: System Architecture | |
| This document serves as a comprehensive architectural guide for the HALE (LifeOS-2) backend and system structure. It is designed to provide full context to any AI tool or developer building new components, models, or frontends on top of this common backend. | |
| --- | |
| ## 1. System Overview | |
| HALE is a FastAPI-based AI-powered adaptive learning engine. The backend is designed to be **model-agnostic** on the consumer side, meaning it can serve multiple different frontends or applications (e.g., the primary web app, a mobile app, or other AI agents). | |
| The core differentiator of this backend is its **Reinforcement Learning (RL) behavioral engine** combined with **LLM-driven (Gemini) curriculum generation**, which dynamically scales learning tasks based on user behavior, mood, and fatigue. | |
| ### Tech Stack | |
| - **Framework:** Python 3.12, FastAPI | |
| - **Database:** PostgreSQL 16 (Relational DB) via SQLAlchemy ORM & Alembic (Migrations) | |
| - **Caching & Rate Limiting:** Redis 7 | |
| - **AI Integration:** Google Gemini (LLM) for curriculum and lesson generation | |
| - **Containerization:** Docker & docker-compose | |
| --- | |
| ## 2. Directory Structure | |
| ```text | |
| lifeos-2/ | |
| βββ app/ # Core Backend Application | |
| β βββ api/ # FastAPI Routers (Controllers) | |
| β βββ core/ # App config, DB setup, Auth/Security, Middleware | |
| β βββ models/ # SQLAlchemy DB Models (Schema) | |
| β βββ schemas/ # Pydantic Models (Validation / Serialization) | |
| β βββ services/ # Core Business Logic (LLM, RL, Planner) | |
| β βββ main.py # App entry point, lifecycle, and middleware | |
| βββ alembic/ # DB Migration scripts | |
| βββ data/ # Local volume mounts | |
| βββ hale-frontend/ # Next.js 14 Frontend Application | |
| βββ tests/ # Pytest Suite | |
| βββ docker-compose.yml # Container orchestration | |
| βββ requirements.txt # Python dependencies | |
| ``` | |
| --- | |
| ## 3. Database Schema | |
| The database uses PostgreSQL. All models inherit from SQLAlchemy's declarative base. | |
| ### 3.1 `User` (`app/models/user.py`) | |
| Central entity managing authentication, gamification, and the user's RL state. | |
| - **Identity & Security:** `user_id`, `email`, `hashed_password`, `refresh_token`, lockout mechanics (`locked_until`, `failed_login_count`). | |
| - **Behavioral State:** `mood`, `fatigue`, `stress`, `sleep_quality`, `competence`, `shock`, `sick`. (Values between 0.0 and 1.0). | |
| - **RL Decision State:** `current_action_label` (e.g., "Deep Work", "Recovery"), `current_intensity`, `rl_bandit_params` (Thompson Sampling data). | |
| - **Gamification:** `xp`, `level`, `current_streak`, `longest_streak`. | |
| - **Schedule:** `schedule_json` storing available learning blocks per day. | |
| ### 3.2 `Goal` (`app/models/goal.py`) | |
| Represents a learning target or objective set by the user. | |
| - **Relational:** Belongs to `user_id`. | |
| - **Content:** `goal_text` (e.g., "Learn Python"), `category`, `duration_days`. | |
| - **Generated Plan:** `plan_json` stores the entire AI-generated curriculum. | |
| - **Tracking:** `is_active`, `is_completed`, `completion_pct`. | |
| ### 3.3 `Progress` (`app/models/progress.py`) | |
| Tracks the daily plan and task execution. | |
| - **Relational:** Belongs to `user_id` and `goal_id`. | |
| - **Daily Content:** `date` (YYYY-MM-DD), `module`, `topic`, `tasks` (JSON list). | |
| - **State Snapshot:** Snapshots the behavioral state at the time of creation (`mood`, `fatigue`, `action_label`, `intensity`). | |
| - **Completion Data:** `completed`, `actual_duration_min`, `satisfaction`, `notes`. | |
| --- | |
| ## 4. Core Services (Business Logic) | |
| The heavy lifting is separated from the API routing into dedicated services (`app/services/`). | |
| ### 4.1 `rl_engine.py` (Behavioral Adaptation) | |
| - Evaluates the user's 7-dimensional behavioral state. | |
| - Uses **Thompson Sampling** (a multi-armed bandit approach) to dynamically select an `action_label` (Recovery, Light Review, Normal, Deep Work, Exploration). | |
| - Adjusts `intensity` to define how hard the daily plan should push the user. | |
| ### 4.2 `llm_service.py` (AI Generation) | |
| - Wraps the Google Gemini API. | |
| - Converts high-level goals into structured curricula (`generate_plan`). | |
| - Generates localized, micro-learning lessons based on the daily topic (`generate_lesson`). | |
| ### 4.3 `planner.py` (Daily Engine) | |
| - Combines the Goal's JSON curriculum, the RL Engine's intensity, and the User's schedule. | |
| - Extracts the exact tasks for the day and creates `Progress` records. | |
| - Handles streak calculations and XP distribution upon task completion. | |
| ### 4.4 `day_closer.py` | |
| - A background scheduler (APScheduler configured in `main.py` running at 2 AM IST). | |
| - Auto-closes pending tasks for the day, resets streaks if tasks are missed, and updates competence decay. | |
| --- | |
| ## 5. API Endpoints | |
| The API is fully RESTful and versioned implicitly via FastAPI routes. Secured routes require a JWT Bearer Token. | |
| ### `/api/auth` | |
| - `POST /register`: Account creation with rate-limiting. | |
| - `POST /login`: Returns JWT access and refresh tokens. | |
| - `GET /profile`: Fetch the current user data (including RL state & XP). | |
| - `PATCH /profile`: Update schedule or coach personality. | |
| ### `/api/goals` | |
| - `POST /`: Submit a goal text. Triggers `llm_service` to generate a curriculum. | |
| - `GET /`: List active goals. | |
| - `PATCH / {id}`: Update priorities. | |
| ### `/api/schedule` | |
| - (Implicit in `user.py` / `auth.py` but handles schedule blocking/unblocking). | |
| ### `/api/plans` (or `/api/progress`) | |
| - `GET /plan`: Fetches today's plan. If one doesn't exist, invokes `planner.py` and `rl_engine.py` to construct it dynamically. | |
| - `POST /complete-task`: Marks tasks as done, distributes XP, checks for level-ups. | |
| - `POST /update-state`: Endpoint to manually ping the backend with new mood/fatigue metrics. | |
| - `GET /behavior`: Exposes the current RL parameters. | |
| - `GET /stats`: Aggregated statistics for frontend charts. | |
| --- | |
| ## 6. How to Integrate New AI Models / Apps | |
| When plugging in new AI models or frontend clients to this backend: | |
| 1. **Authentication:** Use `/api/auth/login` to obtain the JWT token. Pass it as `Authorization: Bearer <token>` in subsequent requests. | |
| 2. **Behavioral Sync:** Continuously feed the user's state to the backend using `/api/plans/update-state` so the `rl_engine` remains accurate. | |
| 3. **Task Fetching:** Only rely on `/api/plan` for the daily tasks. Do not attempt to parse the Goal's raw curriculum on the client side; let `planner.py` handle the intensity adaptation. | |
| 4. **Data Models:** Do not bypass the FastAPI endpoints. Direct database interaction from a secondary app will cause the RL engine and Streak logic to fall out of sync. Use the provided REST APIs. | |