Gograb Ai

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

GoGrab AI Library

📚 Quick Navigation

🚀 Getting Started

🛠️ Implementation

🔧 Support

🎯 Quick Links


The GoGrab AI library provides enterprise-grade AI integration for our monorepo applications, featuring direct API access to OpenAI and Anthropic services with intelligent content generation, smart suggestions, and advanced chat capabilities.

📍 Library Details

🌟 Core Purpose

The GoGrab AI library serves as our production-ready AI integration hub providing:

  1. Self-Contained Architecture - Revolutionary simplicity: just provide chatId and everything works!
  2. Perfect Synchronization - All UI components show consistent, accurate model information
  3. Direct API Access - Native OpenAI, Anthropic, and Google AI integration with CORS support
  4. AI Image Generation - Comprehensive DALL-E and Claude Vision integration for text-to-image and image analysis
  5. Event-Driven Communication - Rich @Output() events for seamless parent component integration
  6. Chat Isolation - Each chatId maintains completely independent configuration in IndexedDB
  7. Intelligent Defaults - Automatic sensible configuration creation when none exists
  8. Multi-Provider Support - Seamless switching between AI providers with smart model recommendations

🏗️ Architecture Position

GoGrab AI sits in the Framework Libraries layer with direct API access:

Feature Libraries (widgets, editor-ui, shared-ui, auth, etc.)
    ↑ depends on  
Framework Libraries (ux-framework, theme-system, gograb-ai, etc.) ← You are here
    ↑ depends on
Core Libraries (permissions)
    ↑ depends on
Foundation Libraries (core-types, core)

🚀 Current Implementation Status

✅ Working Features

🔧 Recent Fixes (Latest - v2.1+)

🧠 Key Components

AI Factory Service

Central service for managing AI provider initialization:

import { AIFactoryService } from '@gograb-ai';

@Injectable()
export class MyService {
  constructor(private aiFactory: AIFactoryService) {}
  
  async initializeAI() {
    await this.aiFactory.initializeWithRealKeys();
    // Factory uses singleton pattern - only initializes once
  }
}

OpenAI Service

Direct OpenAI API integration:

import { OpenAIService } from '@gograb-ai';

@Component({
  // ...
})
export class MyComponent {
  constructor(private openai: OpenAIService) {}
  
  async generateContent(prompt: string) {
    const response = await this.openai.sendMessage({
      model: 'gpt-4o',
      messages: [{ role: 'user', content: prompt }],
      temperature: 0.7
    });
    return response;
  }
}

Anthropic Service

Direct Anthropic API integration:

import { AnthropicService } from '@gograb-ai';

@Component({
  // ...
})
export class MyComponent {
  constructor(private anthropic: AnthropicService) {}
  
  async generateContent(prompt: string) {
    const response = await this.anthropic.makeMessagesRequest({
      model: 'claude-3-haiku-20240307',
      messages: [{ role: 'user', content: prompt }],
      max_tokens: 1000
    });
    return response;
  }
}

Advanced Chat Component

Enterprise-grade chat interface with self-contained architecture:

🎯 Simple Usage (Recommended)

import { AiChatComponent } from '@gograb-ai';

@Component({
  template: `
    <!-- ✅ SIMPLE: Just provide chatId - everything else is automatic! -->
    <lib-ai-chat chatId="my-chat"></lib-ai-chat>
  `
})
export class MyComponent {
  // That's it! The component:
  // - Creates intelligent defaults automatically
  // - Manages its own configuration in IndexedDB
  // - Handles all UI synchronization
  // - Maintains perfect isolation between different chatIds
}

⚙️ Advanced Usage (Optional Customization)

@Component({
  template: `
    <lib-ai-chat
      chatId="my-advanced-chat"
      [enablePromptManager]="true"
      [enableAnalytics]="true"
      [enableAdvancedUI]="true"
      [enableImageGeneration]="true"
      chatHeaderTitle="AI Assistant"
      chatTheme="glass"
      selectStyle="glass"
      (configurationChanged)="onConfigChanged($event)"
      (providerChanged)="onProviderChanged($event)"
      (modelChanged)="onModelChanged($event)">
    </lib-ai-chat>
  `
})
export class MyComponent {
  // 🎯 Optional: React to configuration changes
  onConfigChanged(config: AiChatConfig) {
    console.log('Chat config updated:', config);
  }
  
  onProviderChanged(provider: AIProvider) {
    console.log('Provider changed to:', provider);
  }
  
  onModelChanged(model: string) {
    console.log('Model changed to:', model);
  }
}

🔧 Legacy Usage (Backward Compatible)

@Component({
  template: `
    <!-- Still works for existing code -->
    <lib-ai-chat
      chatId="legacy-chat"
      [provider]="AIProvider.ANTHROPIC"
      [model]="'claude-3-haiku-20240307'"
      [temperature]="0.7"
      [maxTokens]="4000">
    </lib-ai-chat>
  `
})
export class MyComponent {
  // Legacy approach with explicit inputs still supported
}

📊 Advanced Features

🎨 AI Image Generation

Comprehensive AI-powered image creation and manipulation:

Text-to-Image Generation

import { AiImageGenerationService } from '@gograb-ai';

@Component({
  // ...
})
export class MyComponent {
  constructor(private imageGen: AiImageGenerationService) {}
  
  async generateImage(prompt: string) {
    // OpenAI DALL-E integration
    const image = await this.imageGen.generateWithOpenAI({
      prompt: "A futuristic cityscape at sunset",
      size: "1024x1024",
      quality: "hd",
      style: "vivid",
      n: 1
    });
    
    return image.data[0].url;
  }
  
  async generateWithAnthropic(prompt: string) {
    // Anthropic integration for image analysis
    const analysis = await this.imageGen.analyzeWithAnthropic({
      image: imageBase64,
      prompt: "Describe this image in detail"
    });
    
    return analysis.content;
  }
}

Chat-Integrated Image Generation

@Component({
  template: `
    <lib-ai-chat
      chatId="image-chat"
      [enableImageGeneration]="true"
      [imageGenerationSettings]="{
        provider: 'openai',
        defaultSize: '1024x1024',
        defaultQuality: 'hd',
        enableImageAnalysis: true
      }">
    </lib-ai-chat>
  `
})
export class ImageChatComponent {
  // Chat automatically handles:
  // - /image [prompt] commands
  // - Image upload and analysis
  // - Multi-modal conversations
  // - Image history and galleries
}

Advanced Image Features

Smart Prompt Management

Template-based prompt system with variables:

import { PromptManagementService } from '@gograb-ai';

// Create prompt template
await this.promptService.createPrompt({
  name: "Email Writer",
  content: "Write a {{tone}} email about {{subject}}",
  variables: [
    { name: "tone", type: "select", options: ["formal", "casual"] },
    { name: "subject", type: "text", required: true }
  ]
});

Real-time Analytics

Performance and cost tracking:

import { AnalyticsService } from '@gograb-ai';

// Get session statistics
const stats = this.analyticsService.getSessionStats();
console.log('Tokens used:', stats.tokensUsed);
console.log('Cost incurred:', stats.costIncurred);

🏗️ Self-Contained Architecture

Revolutionary simplification of AI chat integration:

Intelligent Default Configuration

// NO CONFIGURATION NEEDED!
// Component automatically creates sensible defaults:
{
  provider: AIProvider.OPENAI,
  model: 'gpt-4o',
  temperature: 0.7,
  maxTokens: 1000,
  enableAnalytics: true,
  enableAdvancedUI: true
}

Chat Isolation & Independent Configuration

// Each chatId maintains its own configuration in IndexedDB
<lib-ai-chat chatId="support-chat"></lib-ai-chat>      <!-- OpenAI GPT-4o -->
<lib-ai-chat chatId="creative-chat"></lib-ai-chat>     <!-- Anthropic Claude -->
<lib-ai-chat chatId="technical-chat"></lib-ai-chat>    <!-- Google Gemini -->

// Configurations are completely isolated - changing one doesn't affect others

Priority-Based Configuration Loading

// Configuration priority (highest to lowest):
// 1. 💾 IndexedDB (user's saved preferences)
// 2. 📝 @Input() defaults (parent component)  
// 3. 🧠 Intelligent defaults (automatic fallback)

@Component({
  template: `
    <lib-ai-chat 
      chatId="priority-demo"
      [provider]="preferredProvider"      <!-- Used if no saved config -->
      [temperature]="preferredTemp">      <!-- Used if no saved config -->
    </lib-ai-chat>
  `
})
export class PriorityDemo {
  preferredProvider = AIProvider.ANTHROPIC;  // Fallback only
  preferredTemp = 0.9;                       // Fallback only
}

📡 Event-Driven Communication

Comprehensive @Output() events for parent component integration:

Configuration Events

@Component({
  template: `
    <lib-ai-chat
      chatId="event-demo"
      (configurationChanged)="onConfigChanged($event)"
      (providerChanged)="onProviderChanged($event)"
      (modelChanged)="onModelChanged($event)"
      (temperatureChanged)="onTempChanged($event)"
      (maxTokensChanged)="onTokensChanged($event)">
    </lib-ai-chat>
  `
})
export class EventDemoComponent {
  // React to any configuration change
  onConfigChanged(config: AiChatConfig) {
    console.log('Full config updated:', config);
    // Update parent state, sync with backend, etc.
  }
  
  // React to specific changes
  onProviderChanged(provider: AIProvider) {
    this.analyticsService.track('provider_changed', { provider });
  }
  
  onModelChanged(model: string) {
    this.updateModelPreferences(model);
  }
  
  onTempChanged(temperature: number) {
    this.validateTemperatureRange(temperature);
  }
}

Message & Interaction Events

@Component({
  template: `
    <lib-ai-chat
      chatId="interaction-demo"
      (messageSent)="onMessageSent($event)"
      (responseReceived)="onResponseReceived($event)"
      (imageGenerated)="onImageGenerated($event)"
      (errorOccurred)="onError($event)">
    </lib-ai-chat>
  `
})
export class InteractionDemoComponent {
  onMessageSent(message: ChatMessage) {
    this.trackUserEngagement(message);
  }
  
  onResponseReceived(response: AiResponse) {
    this.updateTokenUsage(response.tokenCount);
  }
  
  onImageGenerated(image: GeneratedImage) {
    this.saveToGallery(image);
  }
  
  onError(error: AiError) {
    this.handleErrorGracefully(error);
  }
}

Keyboard Shortcuts

Built-in productivity shortcuts:

🔧 Configuration

Basic Configuration

// In your app.config.ts
import { AIProvider } from '@gograb-ai';

const aiConfig = {
  implementationConfig: {
    [AIProvider.OPENAI]: {
      useDirectApi: true,
      maxRetries: 2,
      timeout: 30000
    },
    [AIProvider.ANTHROPIC]: {
      useDirectApi: true,
      maxRetries: 2,
      timeout: 30000
    }
  }
};

Environment Variables

# Required API keys
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...

# Optional: Custom endpoints (defaults to official APIs)
OPENAI_API_BASE=https://api.openai.com/v1
ANTHROPIC_API_BASE=https://api.anthropic.com/v1

🚀 Getting Started

1. Installation

# Library is already installed in monorepo
npx nx build gograb-ai

2. Basic Usage

// Import required services
import { AIFactoryService, OpenAIService, AnthropicService } from '@gograb-ai';

// Initialize in your component
constructor(
  private aiFactory: AIFactoryService,
  private openai: OpenAIService,
  private anthropic: AnthropicService
) {}

async ngOnInit() {
  // Initialize AI services
  await this.aiFactory.initializeWithRealKeys();
  
  // Test connection
  const response = await this.openai.sendMessage({
    model: 'gpt-4o',
    messages: [{ role: 'user', content: 'Hello!' }]
  });
}

3. Simple Chat Integration (Recommended)

// ✅ MINIMAL SETUP - Everything else is automatic!
@Component({
  template: `<lib-ai-chat chatId="getting-started"></lib-ai-chat>`
})
export class GettingStartedComponent {
  // That's it! The component handles:
  // - Automatic intelligent defaults
  // - IndexedDB configuration persistence  
  // - Perfect UI synchronization
  // - Independent chat isolation
}

4. Advanced Chat Integration (Optional)

// ⚙️ CUSTOM CONFIGURATION - For specific requirements
@Component({
  template: `
    <lib-ai-chat
      chatId="my-advanced-chat"
      [enablePromptManager]="true"
      [enableAnalytics]="true"
      [enableAdvancedUI]="true"
      [enableImageGeneration]="true"
      [provider]="preferredProvider"
      [temperature]="0.8"
      (configurationChanged)="onConfigChanged($event)">
    </lib-ai-chat>
  `
})
export class AdvancedChatComponent {
  preferredProvider = AIProvider.ANTHROPIC;
  
  onConfigChanged(config: AiChatConfig) {
    console.log('User updated configuration:', config);
  }
}

🔍 Testing

AI Tester Component

Use the built-in AI tester for debugging:

// Available at: /ai/ai-tester route
// Tests both OpenAI and Anthropic connections
// Provides detailed logging and error reporting

Prompt Storage Tools (New)

Example flow:

  1. Click "Create Sample Prompt" → verify stats update.
  2. Click "Export All" → a gograb-prompts-export.json file is downloaded.
  3. Paste JSON into the Import textarea → click "Import" → stats refresh.

Under the hood it uses PromptManagementService with Dexie for persistence. The same service powers lib-ai-chat quick prompts and usage tracking.

Connection Testing

// Test OpenAI connection
const openaiTest = await this.openai.testConnection();

// Test Anthropic connection  
const anthropicTest = await this.anthropic.testConnection();

📈 Performance Optimizations

Singleton Pattern

Smart Caching

Change Detection

🛠️ Troubleshooting

Common Issues

  1. Connection Errors

    • Ensure API keys are valid and properly formatted
    • Check network connectivity
    • Verify API endpoints are accessible
  2. Performance Issues

    • Monitor token usage in analytics dashboard
    • Consider using more efficient models (GPT-4o-mini, Claude Haiku)
    • Implement request debouncing for real-time features
  3. Configuration Problems

    • Verify useDirectApi: true in configuration
    • Check environment variable names
    • Ensure proper provider selection
  4. Model Synchronization Issues (FIXED in v2.1+)

    • ✅ Fixed: Model selector showing different model than chat configuration
    • ✅ Fixed: Model reverting to defaults on page refresh
    • ✅ Fixed: Different UI components showing inconsistent model names
    • ✅ Fixed: Stale closure bugs in reactive components
  5. Chat Configuration Issues (FIXED in v2.1+)

    • ✅ Fixed: Dual-saving creating multiple configurations for same chat
    • ✅ Fixed: Settings not persisting across page refreshes
    • ✅ Fixed: Global configuration conflicts affecting individual chats
    • ✅ Fixed: Temperature/maxTokens changes not saving properly
  6. Event Communication Issues (FIXED in v2.1+)

    • ✅ Fixed: @Output() events not firing when configuration changes
    • ✅ Fixed: Parent components not receiving provider/model change events
    • ✅ Fixed: Change detection not triggering after configuration updates

Debug Mode

// Enable debug logging
localStorage.setItem('gograb-ai-debug', 'true');

// Check console for detailed logs:
// 🚀 OPENAI REQUEST: Using direct API for model: gpt-4o
// 🚀 ANTHROPIC REQUEST: Using direct API for model: claude-3-haiku-20240307

📚 Documentation Index

Core Integration

Advanced Features

Implementation Guides

Troubleshooting

🔄 Recent Updates

Version 2.1.0 (Current - Latest)

Version 2.0.0 (Previous)

Migration Guide

From v2.0 to v2.1+

// BEFORE (v2.0 - Complex)
<lib-ai-chat
  chatId="my-chat"
  [provider]="provider"
  [model]="model"
  [temperature]="temp"
  [maxTokens]="tokens">
</lib-ai-chat>

// AFTER (v2.1+ - Simple)  
<lib-ai-chat chatId="my-chat"></lib-ai-chat>

From v1.x to v2.0+

🚀 Future Roadmap

✅ Recently Implemented (v2.1+)

🔄 Currently In Development

🎯 Planned Features (Next)

⚡ Performance Improvements (Ongoing)

🎨 UI/UX Enhancements (Planned)

The GoGrab AI library is production-ready and provides enterprise-grade AI integration with revolutionary simplicity and excellent performance. The v2.1+ self-contained architecture makes it incredibly easy to integrate AI capabilities into any Angular application! 🚀