AI LEARNING SYSTEM

Ecosistema completo para organización y gestión de contenido con interfaces espaciales

🧠 AI Learning System

Overview

The GoGrab Space AI Learning System is a self-improving, modular AI architecture that continuously learns from user interactions to provide better widget generation and property suggestions over time.

Database: gograb-ai (dedicated AI database)


Modular Architecture

apis/backend-api/src/app/ai-learning/
├── ai-learning.module.ts           # NestJS module
├── ai-learning.controller.ts       # REST API
├── ai-learning.service.ts          # Orchestrator (delegates to learners)
│
├── core/                           # Core infrastructure
│   ├── ai-learning.interfaces.ts   # Shared types & interfaces
│   ├── ai-learning-core.service.ts # Database access, utilities
│   └── index.ts
│
└── learners/                       # Domain-specific learners (MODULAR)
    ├── theme-learner.service.ts    # 🎨 Theme system learning
    ├── nlp-mapping-learner.service.ts # 📝 NLP → Property mappings
    ├── generation-tracker.service.ts  # 📊 Generation history & analytics
    └── index.ts

Adding a New Learner

To add a new domain (e.g., "layout-learner"):

  1. Create learners/layout-learner.service.ts implementing AiLearner interface
  2. Add to ai-learning.module.ts providers
  3. Inject into AiLearningService if needed
  4. Add endpoints to controller

This modular design ensures each learning domain can grow/evolve independently.


Data Flow

User Prompt: "create a big red button"
        ↓
┌──────────────────────────────────────────────────────┐
│  1. FETCH LEARNED MAPPINGS                           │
│     Query: "big" → var(--ux-font-size-2xl) (95%)     │
│     Query: "red" → var(--ux-error) (93%)             │
└──────────────────────────────────────────────────────┘
        ↓
┌──────────────────────────────────────────────────────┐
│  2. BUILD INTELLIGENT PROMPT                         │
│     Include: mappings, theme context, templates      │
└──────────────────────────────────────────────────────┘
        ↓
┌──────────────────────────────────────────────────────┐
│  3. AI GENERATION                                    │
│     Anthropic Claude with full context               │
└──────────────────────────────────────────────────────┘
        ↓
┌──────────────────────────────────────────────────────┐
│  4. RECORD GENERATION                                │
│     Store in ai_generations collection               │
└──────────────────────────────────────────────────────┘
        ↓
┌──────────────────────────────────────────────────────┐
│  5. USER INTERACTION                                 │
│     User saves or modifies properties                │
└──────────────────────────────────────────────────────┘
        ↓
┌──────────────────────────────────────────────────────┐
│  6. SUBMIT FEEDBACK                                  │
│     Track: accepted, modified, modifications[]       │
└──────────────────────────────────────────────────────┘
        ↓
┌──────────────────────────────────────────────────────┐
│  7. UPDATE MAPPINGS                                  │
│     Learn: user changed fontSize xl → 2xl            │
│     Update: "big" now maps to 2xl (confidence ↑)     │
└──────────────────────────────────────────────────────┘

Collections

ai_generations

Stores every AI generation request and result.

interface AiGeneration {
  id: string;
  prompt: string;                    // "create a big red button"
  widgetType: string;                // "BUTTON"
  context: {
    spaceId: string;
    userId: string;
    timestamp: string;
  };
  result: {
    name: string;
    description: string;
    properties: Record<string, unknown>;
    propertyGroups: PropertyGroup[];
  };
  metrics: {
    generationTimeMs: number;
    tokensUsed: number;
    cost: number;
  };
  feedback?: {
    wasAccepted: boolean;
    wasModified: boolean;
    modifications: Array<{
      propertyKey: string;
      originalValue: unknown;
      newValue: unknown;
    }>;
    userRating?: number;             // 1-5
    feedbackTimestamp: string;
  };
}

ai_mappings

NLP phrase → CSS property/value mappings with confidence scores.

interface AiMapping {
  id: string;
  phrase: string;                    // "big"
  phraseNormalized: string;          // "big"
  mapping: {
    category: 'size' | 'color' | 'spacing' | 'typography' | 'style' | 'behavior';
    propertyKey: string;             // "fontSize"
    propertyValue: string;           // "var(--ux-font-size-2xl)"
    confidence: number;              // 0.95
  };
  metrics: {
    timesUsed: number;               // 50
    timesAccepted: number;           // 47
    timesModified: number;           // 3
    successRate: number;             // 0.94
  };
  source: 'system' | 'learned' | 'user-defined';
}

ai_theme_context

Theme system documentation for AI prompts.

interface AiThemeContext {
  id: string;
  category: 'colors' | 'typography' | 'spacing' | 'borders' | 'shadows';
  variables: Array<{
    variable: string;                // "var(--ux-font-size-2xl)"
    value: string;                   // "1.5rem"
    description: string;             // "Big/2XL text - use for 'big'"
    aliases: string[];               // ["big", "2xl", "bigger", "title"]
  }>;
  examples: Array<{
    phrase: string;                  // "big font"
    variables: string[];             // ["var(--ux-font-size-2xl)"]
  }>;
}

ai_training_examples

Curated high-quality examples for AI training.

interface AiTrainingExample {
  id: string;
  prompt: string;
  expectedOutput: {
    widgetType: string;
    properties: Record<string, unknown>;
  };
  category: string;
  tags: string[];
  quality: 'excellent' | 'good' | 'acceptable';
  isVerified: boolean;
}

Default Mappings

The system is seeded with intelligent default mappings:

Size Mappings

Phrase Maps To Confidence
"big" var(--ux-font-size-2xl) 90%
"big font" var(--ux-font-size-2xl) 95%
"large" var(--ux-font-size-xl) 85%
"huge" var(--ux-font-size-3xl) 90%
"small" var(--ux-font-size-sm) 90%
"tiny" var(--ux-font-size-xs) 90%

Color Mappings

Phrase Maps To Confidence
"red" var(--ux-error) 95%
"blue" var(--ux-primary) 90%
"green" var(--ux-success) 90%
"yellow" var(--ux-warning) 90%
"primary" var(--ux-primary) 95%
"secondary" var(--ux-secondary) 95%

Style Mappings

Phrase Maps To Confidence
"rounded" var(--ux-radius-lg) 90%
"pill" var(--ux-radius-full) 95%
"square" var(--ux-radius-none) 90%
"spacious" var(--ux-space-xl) 85%
"compact" var(--ux-space-sm) 85%

API Endpoints

Generations

# Record a generation
POST /api/ai/learning/generations
{
  "prompt": "create a big red button",
  "widgetType": "BUTTON",
  "context": { "spaceId": "..." },
  "result": { ... },
  "metrics": { "generationTimeMs": 30000 }
}

# Submit feedback
POST /api/ai/learning/generations/:id/feedback
{
  "wasAccepted": true,
  "wasModified": true,
  "modifications": [
    { "propertyKey": "fontSize", "originalValue": "xl", "newValue": "2xl" }
  ]
}

# Get generation history
GET /api/ai/learning/generations?spaceId=xxx&limit=50

# Get successful examples
GET /api/ai/learning/generations/examples/BUTTON?limit=5

Mappings

# Get all mappings
GET /api/ai/learning/mappings

# Get mappings for a phrase
GET /api/ai/learning/mappings/phrase?phrase=big%20red%20button

# Update mapping success
POST /api/ai/learning/mappings/:id/usage
{ "wasSuccessful": true }

Theme Context

# Get raw theme context
GET /api/ai/learning/theme-context

# Get theme context formatted for AI prompt
GET /api/ai/learning/theme-context/prompt

Metrics

# Get AI learning metrics
GET /api/ai/learning/metrics?spaceId=xxx

Frontend Integration

IntelligentWidgetGeneratorService

import { IntelligentWidgetGeneratorService } from '@libs-widgets/widget-builder';

@Component({...})
export class MyComponent {
  private generator = inject(IntelligentWidgetGeneratorService);
  
  async createWidget() {
    // 1. Generate with AI learning context
    const result = await this.generator.generateWidget("create a big red button");
    
    // Result now uses learned mappings:
    // - "big" → var(--ux-font-size-2xl) (not xl!)
    // - "red" → var(--ux-error)
    
    // 2. User modifies properties...
    
    // 3. Submit feedback when saved
    await this.generator.submitFeedback(
      true,  // wasAccepted
      true,  // wasModified
      [{ propertyKey: 'padding', originalValue: 'md', newValue: 'lg' }]
    );
  }
}

How Learning Works

Example: User Feedback Cycle

  1. Initial State: "big" → var(--ux-font-size-xl) (80% confidence)

  2. User Request: "create a big title"

  3. AI Generates: fontSize = var(--ux-font-size-xl)

  4. User Modifies: Changes to var(--ux-font-size-2xl)

  5. Feedback Submitted:

    {
      "wasModified": true,
      "modifications": [{
        "propertyKey": "fontSize",
        "originalValue": "var(--ux-font-size-xl)",
        "newValue": "var(--ux-font-size-2xl)"
      }]
    }
    
  6. System Learns:

    • Updates mapping: "big" → var(--ux-font-size-2xl)
    • Increases confidence (now 85%)
  7. Next Request: "big heading" → AI now uses var(--ux-font-size-2xl)


Benefits

For Users

For the Platform

For AI Agents


Configuration

Database

// Backend connects to gograb-ai database
private readonly AI_DB_NAME = 'gograb-ai';

// Collections are auto-created with indexes
await this.generations.createIndex({ 'context.spaceId': 1 });
await this.mappings.createIndex({ phraseNormalized: 1 });

Seed Data

Default mappings and theme context are seeded on module initialization:

async onModuleInit(): Promise<void> {
  await this.initializeDatabase();
  await this.seedDefaultMappings();    // 16+ default mappings
  await this.seedThemeContext();       // 4 theme categories
}

Future Enhancements


Last Updated: December 4, 2025
Status: ✅ Implemented and Production-Ready