Gograb Ai
Ecosistema completo para organización y gestión de contenido con interfaces espaciales
GoGrab AI Library
📚 Quick Navigation
🚀 Getting Started
- Setup Guide - Initial setup and configuration
- Integration Fixes - Latest fixes and migration guide (v1.x → v2.0+)
🛠️ Implementation
- Implementation Guide - Comprehensive examples and enterprise features
- Performance Optimization - Optimization strategies and benchmarks
🔧 Support
- Troubleshooting Guide - Common issues and solutions
- Unified System Integration - AI within the overall system
🎯 Quick Links
- UX Test AI Tester:
http://localhost:5300/ux-test/#/ai/ai-tester - Space Map AI:
http://localhost:5100/space-map/ - Editor Web AI:
http://localhost:5200/editor-web/ - Debug Mode:
localStorage.setItem('gograb-ai-debug', 'true')
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
- Location:
libs/gograb-ai/ - Dependencies: Angular 20+, RxJS
- Type: AI Integration Library
- Tags:
npm:public - Purpose: AI integration, chat interfaces, content generation
🌟 Core Purpose
The GoGrab AI library serves as our production-ready AI integration hub providing:
- Self-Contained Architecture - Revolutionary simplicity: just provide
chatIdand everything works! - Perfect Synchronization - All UI components show consistent, accurate model information
- Direct API Access - Native OpenAI, Anthropic, and Google AI integration with CORS support
- AI Image Generation - Comprehensive DALL-E and Claude Vision integration for text-to-image and image analysis
- Event-Driven Communication - Rich @Output() events for seamless parent component integration
- Chat Isolation - Each chatId maintains completely independent configuration in IndexedDB
- Intelligent Defaults - Automatic sensible configuration creation when none exists
- 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
- 🚀 Self-Contained Components - Just provide
chatId, everything else is automatic - 🔄 Perfect Model Sync - All UI components show consistent model information (FIXED)
- 📡 Event-Driven Communication - Rich @Output() events for configuration changes
- 🔒 Chat Isolation - Independent IndexedDB configurations per chatId
- 🧠 Intelligent Defaults - Automatic sensible configuration creation
- 🎨 AI Image Generation - DALL-E integration with multiple sizes and quality options
- 👁️ Image Analysis - Claude Vision for uploaded image analysis and discussion
- 🔄 Priority Loading - IndexedDB → @Input() → Intelligent defaults
- 🛠️ Enhanced Model Selector - Smart recommendations with proper input handling
- 📊 Real-time Analytics - Cost tracking and token usage monitoring
- ⌨️ Keyboard Shortcuts - Full productivity shortcuts (Ctrl+M, Ctrl+I, etc.)
- 🌐 Multi-Provider Support - OpenAI, Anthropic, Google AI with seamless switching
- 🚫 No Proxy Dependencies - Native CORS support, direct API calls
- 🌍 Environment Independent - Works locally, development, and production (Railway)
- ⚡ Performance Optimized - Singleton patterns, smart caching, reduced overhead
🔧 Recent Fixes (Latest - v2.1+)
- Self-Contained Architecture - AI chat components are now fully self-contained with intelligent defaults
- Perfect Model Synchronization - Fixed all UI inconsistencies where different components showed different models
- Event-Driven Communication - Added comprehensive @Output() events for configuration changes
- Chat Isolation - Each chatId maintains its own independent configuration
- Intelligent Defaults - Automatic sensible configuration creation when none exists
- Stale Closure Bug Fix - Resolved model selector display issues on page refresh
- Image Generation - Added comprehensive AI-powered image creation capabilities
- Enhanced Model Selector - Smart model selection with intelligent recommendations
- Portal-Based Tools - Advanced UX portal integration for AI tools
🧠 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
- Multiple Providers: OpenAI DALL-E, Anthropic Claude Vision
- Size Options: 256x256, 512x512, 1024x1024, 1792x1024, 1024x1792
- Quality Settings: Standard, HD
- Style Controls: Vivid, Natural
- Batch Generation: Multiple images per request
- Image Analysis: Upload images for AI analysis and discussion
- Image History: Automatic gallery of generated images
- Download Integration: Save images directly to device
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:
- Ctrl+P (Cmd+P): Toggle Prompt Manager
- Ctrl+D (Cmd+D): Toggle Analytics Dashboard
- Ctrl+Enter: Send message
- Ctrl+N: New conversation
- Ctrl+I: Toggle Image Generation
- Ctrl+M: Switch Model
- Ctrl+T: Adjust Temperature
🔧 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)
- The AI Tester now includes a Prompt Storage panel:
- Displays IndexedDB stats (total/built-in/custom prompts and categories)
- Create a sample prompt to verify persistence
- Export all prompts to JSON and import from pasted JSON
Example flow:
- Click "Create Sample Prompt" → verify stats update.
- Click "Export All" → a
gograb-prompts-export.jsonfile is downloaded. - 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
- AI Factory initializes only once per session
- Prevents redundant service initialization
- Reduces memory usage and startup time
Smart Caching
- API keys cached in memory after first load
- Prompt templates cached in IndexedDB
- Response caching for frequently used queries
Change Detection
- Only saves configuration when changes occur
- Prevents unnecessary localStorage writes
- Optimized re-initialization logic
🛠️ Troubleshooting
Common Issues
Connection Errors
- Ensure API keys are valid and properly formatted
- Check network connectivity
- Verify API endpoints are accessible
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
Configuration Problems
- Verify
useDirectApi: truein configuration - Check environment variable names
- Ensure proper provider selection
- Verify
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
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
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
- Setup Guide - Initial setup and configuration
- API Reference - Complete API documentation
- Migration Guide - Upgrading from proxy to direct API
Advanced Features
- Chat Components - Advanced chat interface documentation
- Prompt Management - Smart prompt system
- Analytics - Performance monitoring and cost tracking
Implementation Guides
- Implementation Guide - Comprehensive implementation examples
- Performance Optimization - Optimization strategies
- Integration Fixes - Latest fixes and improvements
Troubleshooting
- Common Issues - Troubleshooting guide
- FAQ - Frequently asked questions
🔄 Recent Updates
Version 2.1.0 (Current - Latest)
- 🚀 Self-Contained Architecture - Revolutionary simplification: just provide
chatId! - 🔄 Perfect Model Synchronization - Fixed all UI inconsistencies and stale closure bugs
- 📡 Event-Driven Communication - Comprehensive @Output() events for all configuration changes
- 🔒 Chat Isolation - Each chatId maintains completely independent configuration
- 🧠 Intelligent Defaults - Automatic sensible configuration when none exists
- 🎨 AI Image Generation - Comprehensive DALL-E and Claude Vision integration
- ⚡ Priority-Based Loading - IndexedDB → @Input() → Intelligent defaults
- 🛠️ Enhanced Model Selector - Smart model recommendations with proper input handling
Version 2.0.0 (Previous)
- ✅ Direct API Implementation - Removed proxy dependencies
- ✅ Performance Optimizations - Reduced initialization overhead
- ✅ Railway Deployment - Full production compatibility
- ✅ Advanced Chat Features - Enterprise-grade chat interface
- ✅ Smart Analytics - Real-time cost and performance tracking
Migration Guide
From v2.0 to v2.1+
- ✨ SIMPLIFICATION: Replace complex configurations with simple
chatId-only usage - 🔧 OPTIONAL: Add event handlers for configuration changes if needed
- 📈 BENEFITS: Better UX, perfect synchronization, independent chat management
// 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+
- Breaking Change: Proxy servers no longer needed
- Configuration Update: Set
useDirectApi: true(default) - Benefits: Better performance, simpler deployment, no proxy maintenance
🚀 Future Roadmap
✅ Recently Implemented (v2.1+)
- ✅ Self-Contained Architecture - Revolutionary simplification achieved
- ✅ Perfect Model Synchronization - All UI inconsistencies resolved
- ✅ Multi-modal Support - Image generation and analysis implemented
- ✅ Event-Driven Communication - Comprehensive @Output() events added
- ✅ Chat Isolation - Independent configurations per chatId
- ✅ Intelligent Defaults - Automatic configuration creation
🔄 Currently In Development
- Stream Processing - Real-time streaming responses (in progress)
- Audio Processing - Voice input and speech synthesis
- Advanced Image Editing - Image manipulation and enhancement tools
- Prompt Templates Gallery - Pre-built prompt library with categories
🎯 Planned Features (Next)
- Custom Models - Support for fine-tuned models and local AI
- Batch Processing - Bulk request handling for efficiency
- Advanced Security - Enhanced API key management and encryption
- Collaboration Features - Shared chats and team workspaces
- Plugin System - Extensible architecture for custom AI tools
⚡ Performance Improvements (Ongoing)
- Connection Pooling - Reuse HTTP connections
- Smart Retry Logic - Exponential backoff with jitter
- Adaptive Rate Limiting - Dynamic rate limit handling
- Response Compression - Reduce bandwidth usage
- Background Processing - Non-blocking UI for long operations
🎨 UI/UX Enhancements (Planned)
- Themes System - Multiple chat themes and customization
- Mobile Optimization - Touch-friendly interface improvements
- Accessibility - Enhanced screen reader and keyboard support
- Dark/Light Mode - Automatic theme switching
- Drag & Drop - File upload and organization improvements
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! 🚀