Troubleshooting

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

GoGrab AI Troubleshooting Guide

This guide helps you diagnose and fix common issues with the GoGrab AI library.

🔧 Quick Diagnostic Steps

1. Check Service Status

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

// Check console for these logs:
// ✅ Good: 🚀 OPENAI REQUEST: Using direct API for model: gpt-4o
// ✅ Good: 🚀 ANTHROPIC REQUEST: Using direct API for model: claude-3-haiku-20240307
// ❌ Bad: ERR_CONNECTION_REFUSED
// ❌ Bad: Authentication errors

2. Verify API Keys

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

// Verify key formats
const openaiKey = process.env['OPENAI_API_KEY'];
const anthropicKey = process.env['ANTHROPIC_API_KEY'];

console.log('Key Formats:', {
  openai: openaiKey?.startsWith('sk-') ? '✅ Valid' : '❌ Invalid',
  anthropic: anthropicKey?.startsWith('sk-ant-') ? '✅ Valid' : '❌ Invalid'
});

3. Test Direct API Access

// Test AI Factory initialization
import { AIFactoryService } from '@gograb-ai';

async testInitialization() {
  try {
    await this.aiFactory.initializeWithRealKeys();
    console.log('✅ AI Factory initialized successfully');
  } catch (error) {
    console.error('❌ AI Factory initialization failed:', error);
  }
}

🚨 Common Issues and Solutions

Issue 1: Connection Refused Errors

Symptoms:

Cause: The system is trying to use proxy servers that are no longer needed.

Solution:

// 1. Verify direct API configuration
const config = {
  implementationConfig: {
    [AIProvider.OPENAI]: {
      useDirectApi: true,  // Must be true
      maxRetries: 2,
      timeout: 30000
    },
    [AIProvider.ANTHROPIC]: {
      useDirectApi: true,  // Must be true
      maxRetries: 2,
      timeout: 30000
    }
  }
};

// 2. Ensure no proxy dependencies in your code
// ❌ Remove these if found:
// import { OpenAIProxyService } from '@gograb-ai';
// import { AnthropicProxyService } from '@gograb-ai';

// ✅ Use these instead:
import { OpenAIService, AnthropicService } from '@gograb-ai';

Issue 2: Authentication Errors

Symptoms:

Solution:

// 1. Check API key formats
const validateApiKeys = () => {
  const openaiKey = process.env['OPENAI_API_KEY'];
  const anthropicKey = process.env['ANTHROPIC_API_KEY'];
  
  if (!openaiKey || !openaiKey.startsWith('sk-')) {
    console.error('❌ Invalid OpenAI API key format');
    return false;
  }
  
  if (!anthropicKey || !anthropicKey.startsWith('sk-ant-')) {
    console.error('❌ Invalid Anthropic API key format');
    return false;
  }
  
  console.log('✅ API keys are properly formatted');
  return true;
};

// 2. Refresh API keys from config
import { AIConfigService } from '@gograb-ai';

async refreshApiKeys() {
  try {
    await this.configService.initializeApiKeys();
    console.log('✅ API keys refreshed');
  } catch (error) {
    console.error('❌ Failed to refresh API keys:', error);
  }
}

// 3. Test API key validity
async testApiKeys() {
  try {
    // Test OpenAI
    const openaiResponse = await this.openaiService.sendMessage({
      model: 'gpt-4o',
      messages: [{ role: 'user', content: 'Test' }]
    });
    console.log('✅ OpenAI API key valid');

    // Test Anthropic
    const anthropicResponse = await this.anthropicService.makeMessagesRequest({
      model: 'claude-3-haiku-20240307',
      messages: [{ role: 'user', content: 'Test' }],
      max_tokens: 10
    });
    console.log('✅ Anthropic API key valid');
  } catch (error) {
    console.error('❌ API key test failed:', error);
  }
}

Issue 3: CORS Errors

Symptoms:

Solution:

// Ensure you're using direct API services (not proxy)
// The library handles CORS automatically with direct API calls

// ✅ Correct implementation:
import { OpenAIService, AnthropicService } from '@gograb-ai';

// ❌ Avoid proxy services:
// Don't use OpenAIProxyService or AnthropicProxyService

// Verify direct API endpoints are being used:
// OpenAI: https://api.openai.com/v1/chat/completions
// Anthropic: https://api.anthropic.com/v1/messages

Issue 4: Performance Issues

Symptoms:

Solution:

// 1. Check for multiple initializations
// Look for repeated logs like:
// "🔑 Initializing AI Factory with REAL API keys"

// 2. Ensure singleton pattern is working
import { AIFactoryService } from '@gograb-ai';

// The service should initialize only once
async ngOnInit() {
  // This should run only once per application
  await this.aiFactory.initializeWithRealKeys();
}

// 3. Monitor performance
const startTime = performance.now();
await this.aiFactory.initializeWithRealKeys();
const endTime = performance.now();
console.log(`Initialization took ${endTime - startTime} milliseconds`);

// Expected: < 1000ms for first initialization, < 100ms for subsequent calls

Issue 5: Configuration Problems

Symptoms:

Solution:

// 1. Verify configuration structure
const correctConfig = {
  implementationConfig: {
    [AIProvider.OPENAI]: {
      useDirectApi: true,
      maxRetries: 2,
      timeout: 30000,
      fallbackBehavior: 'retry'
    },
    [AIProvider.ANTHROPIC]: {
      useDirectApi: true,
      maxRetries: 2,
      timeout: 30000,
      fallbackBehavior: 'retry'
    }
  }
};

// 2. Check configuration loading
import { AIConfigService } from '@gograb-ai';

async verifyConfig() {
  const config = await this.configService.getConfig();
  console.log('Loaded configuration:', config);
  
  // Verify useDirectApi is true for both providers
  const openaiConfig = config.implementationConfig?.[AIProvider.OPENAI];
  const anthropicConfig = config.implementationConfig?.[AIProvider.ANTHROPIC];
  
  if (!openaiConfig?.useDirectApi) {
    console.warn('⚠️ OpenAI not configured for direct API');
  }
  
  if (!anthropicConfig?.useDirectApi) {
    console.warn('⚠️ Anthropic not configured for direct API');
  }
}

Issue 6: Model or Provider Errors

Symptoms:

Solution:

// 1. Use supported models
const supportedModels = {
  [AIProvider.OPENAI]: [
    'gpt-4o',
    'gpt-4o-mini',
    'gpt-4-turbo',
    'gpt-3.5-turbo'
  ],
  [AIProvider.ANTHROPIC]: [
    'claude-3-haiku-20240307',
    'claude-3-sonnet-20240229',
    'claude-3-opus-20240229',
    'claude-3-5-sonnet-20241022'
  ]
};

// 2. Verify model availability
async testModel(provider: AIProvider, model: string) {
  try {
    if (provider === AIProvider.OPENAI) {
      const response = await this.openaiService.sendMessage({
        model,
        messages: [{ role: 'user', content: 'Test' }],
        max_tokens: 5
      });
      console.log(`✅ Model ${model} is available`);
    } else if (provider === AIProvider.ANTHROPIC) {
      const response = await this.anthropicService.makeMessagesRequest({
        model,
        messages: [{ role: 'user', content: 'Test' }],
        max_tokens: 5
      });
      console.log(`✅ Model ${model} is available`);
    }
  } catch (error) {
    console.error(`❌ Model ${model} is not available:`, error);
  }
}

Issue 7: Chat Component Not Loading

Symptoms:

Solution:

// 1. Verify component imports
import { AiChatComponent } from '@gograb-ai';

@Component({
  standalone: true,
  imports: [AiChatComponent], // Make sure this is included
  template: `
    <lib-ai-chat
      chatId="test-chat"
      [enablePromptManager]="true"
      [enableAnalytics]="true">
    </lib-ai-chat>
  `
})
export class MyComponent {}

// 2. Check feature flags
// Ensure these are properly set:
[enablePromptManager]="true"
[enableAnalytics]="true"
[enableAdvancedUI]="true"

// 3. Verify library is built
// Run: npx nx build gograb-ai

🔍 Debugging Tools

Debug Mode

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

// Expected debug output:
// 🚀 OPENAI REQUEST: Using direct API for model: gpt-4o
// 🚀 ANTHROPIC REQUEST: Using direct API for model: claude-3-haiku-20240307
// 🔄 AI Factory already initialized, skipping duplicate initialization
// 🔄 API key for openai unchanged, skipping update

Health Check Service

@Injectable({ providedIn: 'root' })
export class AIHealthCheckService {
  async runHealthCheck(): Promise<HealthCheckResult> {
    const results: HealthCheckResult = {
      apiKeys: false,
      openaiConnection: false,
      anthropicConnection: false,
      configuration: false,
      errors: []
    };

    try {
      // Check API keys
      results.apiKeys = this.validateApiKeys();
      
      // Test OpenAI connection
      try {
        await this.openaiService.sendMessage({
          model: 'gpt-4o',
          messages: [{ role: 'user', content: 'Health check' }],
          max_tokens: 5
        });
        results.openaiConnection = true;
      } catch (error) {
        results.errors.push(`OpenAI: ${error.message}`);
      }

      // Test Anthropic connection
      try {
        await this.anthropicService.makeMessagesRequest({
          model: 'claude-3-haiku-20240307',
          messages: [{ role: 'user', content: 'Health check' }],
          max_tokens: 5
        });
        results.anthropicConnection = true;
      } catch (error) {
        results.errors.push(`Anthropic: ${error.message}`);
      }

      // Check configuration
      const config = await this.configService.getConfig();
      results.configuration = !!(
        config.implementationConfig?.[AIProvider.OPENAI]?.useDirectApi &&
        config.implementationConfig?.[AIProvider.ANTHROPIC]?.useDirectApi
      );

    } catch (error) {
      results.errors.push(`Health check failed: ${error.message}`);
    }

    return results;
  }

  private validateApiKeys(): boolean {
    const openaiKey = process.env['OPENAI_API_KEY'];
    const anthropicKey = process.env['ANTHROPIC_API_KEY'];
    
    return !!(
      openaiKey?.startsWith('sk-') &&
      anthropicKey?.startsWith('sk-ant-')
    );
  }
}

interface HealthCheckResult {
  apiKeys: boolean;
  openaiConnection: boolean;
  anthropicConnection: boolean;
  configuration: boolean;
  errors: string[];
}

🚀 Performance Optimization

Memory Usage

// Monitor memory usage
const getMemoryUsage = () => {
  if ('memory' in performance) {
    const memory = (performance as any).memory;
    return {
      used: Math.round(memory.usedJSHeapSize / 1048576),
      total: Math.round(memory.totalJSHeapSize / 1048576),
      limit: Math.round(memory.jsHeapSizeLimit / 1048576)
    };
  }
  return null;
};

// Check periodically
setInterval(() => {
  const memory = getMemoryUsage();
  if (memory && memory.used > 100) { // MB
    console.warn('⚠️ High memory usage detected:', memory);
  }
}, 30000);

Request Performance

// Monitor request times
class RequestTimer {
  private startTime: number;
  
  start() {
    this.startTime = performance.now();
  }
  
  end(operation: string) {
    const duration = performance.now() - this.startTime;
    console.log(`⏱️ ${operation} took ${duration.toFixed(2)}ms`);
    
    if (duration > 9100) {
      console.warn(`⚠️ Slow operation: ${operation} (${duration.toFixed(2)}ms)`);
    }
  }
}

// Usage
const timer = new RequestTimer();
timer.start();
await this.openaiService.sendMessage(request);
timer.end('OpenAI Request');

📞 Getting Help

Before Reporting Issues

  1. ✅ Run health check
  2. ✅ Check debug logs
  3. ✅ Verify API keys
  4. ✅ Test with minimal configuration
  5. ✅ Check recent changes to your code

Information to Include

Quick Fixes Checklist

The GoGrab AI library is designed to be reliable and self-diagnosing. Most issues can be resolved by following this troubleshooting guide! 🚀