Setup Guide

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

GoGrab AI Setup Guide

This guide walks you through setting up the GoGrab AI library in your application with the current direct API implementation.

Prerequisites

1. Library Installation

The library is already installed in the monorepo. To use it in your application:

# Build the library
npx nx build gograb-ai

# Build with watch mode during development
npx nx build gograb-ai --watch

2. API Key Configuration

OpenAI API Key

  1. Visit OpenAI Platform
  2. Create an account or sign in
  3. Go to API Keys section
  4. Create a new API key (starts with sk-)
  5. Copy the key for configuration

Anthropic API Key

  1. Visit Anthropic Console
  2. Create an account or sign in
  3. Go to API Keys section
  4. Create a new API key (starts with sk-ant-)
  5. Copy the key for configuration

3. Environment Setup

Development Environment

# .env.local or environment.ts
OPENAI_API_KEY=sk-your-openai-key-here
ANTHROPIC_API_KEY=sk-ant-your-anthropic-key-here

Production Environment

# Environment variables for Railway/production
OPENAI_API_KEY=sk-your-openai-key-here
ANTHROPIC_API_KEY=sk-ant-your-anthropic-key-here

4. Application Configuration

Basic Configuration

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

export const appConfig = {
  // ... other config
  ai: {
    implementationConfig: {
      [AIProvider.OPENAI]: {
        useDirectApi: true,
        maxRetries: 2,
        timeout: 30000,
        fallbackBehavior: 'retry'
      },
      [AIProvider.ANTHROPIC]: {
        useDirectApi: true,
        maxRetries: 2,
        timeout: 30000,
        fallbackBehavior: 'retry'
      }
    }
  }
};

Module Integration

// app.module.ts or main.ts (for standalone)
import { provideAI } from '@gograb-ai';

export const appConfig: ApplicationConfig = {
  providers: [
    // ... other providers
    provideAI(appConfig.ai)
  ]
};

5. Service Integration

Basic Service Usage

// your-component.ts
import { AIFactoryService, OpenAIService, AnthropicService } from '@gograb-ai';

@Component({
  // ... component config
})
export class YourComponent {
  constructor(
    private aiFactory: AIFactoryService,
    private openai: OpenAIService,
    private anthropic: AnthropicService
  ) {}

  async ngOnInit() {
    // Initialize AI services
    await this.aiFactory.initializeWithRealKeys();
    
    // Test connections
    await this.testConnections();
  }

  private async testConnections() {
    try {
      // Test OpenAI
      const openaiResponse = await this.openai.sendMessage({
        model: 'gpt-4o',
        messages: [{ role: 'user', content: 'Hello!' }]
      });
      console.log('OpenAI connected:', openaiResponse);

      // Test Anthropic
      const anthropicResponse = await this.anthropic.makeMessagesRequest({
        model: 'claude-3-haiku-20240307',
        messages: [{ role: 'user', content: 'Hello!' }],
        max_tokens: 100
      });
      console.log('Anthropic connected:', anthropicResponse);
    } catch (error) {
      console.error('Connection test failed:', error);
    }
  }
}

6. Advanced Chat Integration

Full Chat Component

// chat-page.component.ts
import { AiChatComponent } from '@gograb-ai';

@Component({
  selector: 'app-chat-page',
  standalone: true,
  imports: [AiChatComponent],
  template: `
    <div class="chat-container">
      <lib-ai-chat
        chatId="main-chat"
        [enablePromptManager]="true"
        [enableAnalytics]="true"
        [enableAdvancedUI]="true"
        [enableConversationTabs]="true"
        [enableKeyboardShortcuts]="true"
        chatHeaderTitle="AI Assistant"
        chatTheme="glass"
        selectStyle="glass"
        [provider]="currentProvider"
        [model]="currentModel"
        [temperature]="0.7"
        [maxTokens]="4000"
        (messageSent)="onMessageSent($event)"
        (responseReceived)="onResponseReceived($event)"
        (configurationChanged)="onConfigChanged()"
        (errorOccurred)="onError($event)">
      </lib-ai-chat>
    </div>
  `,
  styles: [`
    .chat-container {
      height: 100vh;
      display: flex;
      flex-direction: column;
    }
  `]
})
export class ChatPageComponent {
  currentProvider = AIProvider.ANTHROPIC;
  currentModel = 'claude-3-haiku-20240307';

  onMessageSent(message: any) {
    console.log('Message sent:', message);
  }

  onResponseReceived(response: any) {
    console.log('Response received:', response);
  }

  onConfigChanged() {
    console.log('Configuration changed');
  }

  onError(error: any) {
    console.error('Chat error:', error);
  }
}

Prompt System Integration

@gograb-ai now uses @prompt-system components for all prompt features. Ensure the prompt system is available once at app root:

<!-- app.component.html -->
<lib-prompt-system></lib-prompt-system>

Inside the AI chat, the prompt sidebar and lab are rendered using lib-prompt-flex-container and lib-prompt-lab-inline from @prompt-system.

7. Routing Setup

Route Configuration

// app.routes.ts
import { Routes } from '@angular/router';

export const routes: Routes = [
  {
    path: 'ai',
    children: [
      {
        path: 'chat',
        loadComponent: () => import('./chat-page.component').then(m => m.ChatPageComponent)
      },
      {
        path: 'ai-tester',
        loadComponent: () => import('./ai-tester.component').then(m => m.AiTesterComponent)
      }
    ]
  }
];

8. Testing Setup

AI Tester Component

The library includes a built-in AI tester component for debugging:

// Use the built-in tester
// Navigate to: /ai/ai-tester
// This component provides:
// - Connection testing for both providers
// - API key validation
// - Request/response logging
// - Error debugging

Manual Testing

// test-ai.service.ts
import { Injectable } from '@angular/core';
import { AIFactoryService, OpenAIService, AnthropicService } from '@gograb-ai';

@Injectable({
  providedIn: 'root'
})
export class TestAIService {
  constructor(
    private aiFactory: AIFactoryService,
    private openai: OpenAIService,
    private anthropic: AnthropicService
  ) {}

  async runTests() {
    console.log('Starting AI tests...');
    
    // Initialize
    await this.aiFactory.initializeWithRealKeys();
    
    // Test OpenAI
    await this.testOpenAI();
    
    // Test Anthropic
    await this.testAnthropic();
    
    console.log('AI tests completed');
  }

  private async testOpenAI() {
    try {
      const response = await this.openai.sendMessage({
        model: 'gpt-4o',
        messages: [{ role: 'user', content: 'Say hello in 3 words' }]
      });
      console.log('✅ OpenAI test passed:', response);
    } catch (error) {
      console.error('❌ OpenAI test failed:', error);
    }
  }

  private async testAnthropic() {
    try {
      const response = await this.anthropic.makeMessagesRequest({
        model: 'claude-3-haiku-20240307',
        messages: [{ role: 'user', content: 'Say hello in 3 words' }],
        max_tokens: 50
      });
      console.log('✅ Anthropic test passed:', response);
    } catch (error) {
      console.error('❌ Anthropic test failed:', error);
    }
  }
}

9. Debugging and Monitoring

Enable Debug Logging

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

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

Performance Monitoring

// Use analytics service
import { AnalyticsService } from '@gograb-ai';

constructor(private analytics: AnalyticsService) {}

ngOnInit() {
  // Start monitoring
  this.analytics.startNewSession('user-session');
  
  // Check stats periodically
  setInterval(() => {
    const stats = this.analytics.getSessionStats();
    console.log('Session stats:', stats);
  }, 10000);
}

10. Common Issues and Solutions

Issue: API Key Not Found

Solution: Verify API keys are properly set in environment variables or configuration.

// Check if keys are loaded
console.log('API Keys loaded:', {
  openai: !!process.env['OPENAI_API_KEY'],
  anthropic: !!process.env['ANTHROPIC_API_KEY']
});

Issue: CORS Errors

Solution: Ensure you're using direct API calls (not proxy). The library handles CORS automatically.

// Verify direct API configuration
const config = {
  useDirectApi: true  // This should be true
};

Issue: Connection Timeout

Solution: Increase timeout values in configuration.

const config = {
  timeout: 60000,  // 60 seconds
  maxRetries: 3
};

11. Production Deployment

Railway Deployment

# Set environment variables in Railway
railway variables set OPENAI_API_KEY=sk-your-key
railway variables set ANTHROPIC_API_KEY=sk-ant-your-key

Docker Deployment

# Add to Dockerfile
ENV OPENAI_API_KEY=sk-your-key
ENV ANTHROPIC_API_KEY=sk-ant-your-key

Build Configuration

# Production build
npx nx build gograb-ai --prod
npx nx build your-app --prod

12. Next Steps

  1. Explore Advanced Features: Check out the Implementation Guide
  2. Set Up Analytics: Configure performance monitoring
  3. Create Prompt Templates: Build your prompt library
  4. Customize UI: Adapt the chat interface to your needs
  5. Performance Optimization: Review the Performance Guide

Support

The GoGrab AI library is now ready for production use with direct API access and excellent performance! 🚀