Integration Fixes
Ecosistema completo para organización y gestión de contenido con interfaces espaciales
AI Integration Fixes - Complete Solution
Problem Summary
The AI integration in the gograb-ai library was experiencing multiple failures:
Anthropic Integration Issues:
- System trying to connect to proxy at
localhost:3001but gettingERR_CONNECTION_REFUSED - Configuration not being properly read for direct API access
- Proxy mode being used instead of direct API calls
- System trying to connect to proxy at
OpenAI Integration Issues:
- Previously working OpenAI integration stopped working
- System trying to use proxy for OpenAI when it has native CORS support
- Angular dev server proxy being used instead of direct API calls
Root Causes Identified
Configuration Structure Mismatch:
- Space Map config had
useDirectApi: trueat top level - AnthropicService was looking for
config.implementationConfig?.['useDirectApi'] - Configuration wasn't being properly propagated to services
- Space Map config had
Proxy Dependencies:
- Both services were still using proxy services in their constructors
- OpenAI was using Angular dev server proxy (
/api/openai/chat/completions) - Anthropic was defaulting to proxy mode instead of direct API
Service Architecture:
- Complex configuration logic with multiple code paths
- Proxy services being injected even when not needed
- Services not using the latest direct API capabilities
Fixes Applied
1. Fixed Anthropic Service (libs/gograb-ai/src/lib/services/anthropic.service.ts)
Changes Made:
- Removed proxy logic from
makeMessagesRequest()method - Always use direct API access via
AnthropicDirectService - Removed proxy service dependency from constructor
- Removed proxy service import
- Simplified service logic to one code path
Key Code Changes:
// BEFORE: Complex proxy vs direct API logic
const useDirectApi = config.implementationConfig?.['useDirectApi'] === true;
if (useDirectApi) {
// direct API logic
} else {
// proxy logic
}
// AFTER: Always use direct API
console.log(`🚀 ANTHROPIC REQUEST: Using direct API for model: ${body.model}`);
return this.anthropicDirectService.sendMessage(body, currentApiKey).pipe(
// ... direct API handling
);
2. Fixed OpenAI Service (libs/gograb-ai/src/lib/services/openai.service.ts)
Changes Made:
- Replaced proxy calls with direct API calls to
https://api.openai.com/v1/chat/completions - Added proper Authorization header with Bearer token
- Removed proxy service dependency from constructor
- Removed proxy service import
- Updated logging to reflect direct API usage
Key Code Changes:
// BEFORE: Using Angular dev server proxy
return this.http.post<any>('/api/openai/chat/completions', requestBody, { headers })
// AFTER: Direct API call to OpenAI
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': `Bearer ${currentApiKey}`
});
return this.http.post<any>(`${this.baseUrl}/chat/completions`, requestBody, { headers })
3. Updated Space Map Configuration (apps/space-map/src/app/app.config.ts)
Configuration Structure: The Space Map configuration was already correctly structured with:
implementationConfig: {
[AIProvider.ANTHROPIC]: {
useDirectApi: true,
maxRetries: 2,
timeout: 30000,
fallbackBehavior: 'retry'
},
[AIProvider.OPENAI]: {
useDirectApi: true,
fallbackBehavior: 'retry',
maxRetries: 2,
timeout: 30000
}
}
4. Architecture Improvements
Removed Dependencies:
AnthropicProxyServicefrom AnthropicService constructorOpenAIProxyServicefrom OpenAIService constructor- Related import statements
Simplified Service Logic:
- Single code path for API calls
- Direct API as the default and only option
- Reduced complexity and potential failure points
Technical Benefits
1. Better Performance
- No proxy server overhead
- Direct API calls are faster
- Reduced latency
2. Improved Reliability
- Fewer failure points (no proxy server to fail)
- Native CORS support from both OpenAI and Anthropic
- No dependency on local proxy servers
3. Simplified Architecture
- Single code path for API calls
- Easier to debug and maintain
- Less complex configuration
4. Environment Independence
- Works in all environments (local, development, production)
- No need for proxy server setup
- Railway-ready deployment
API Details
OpenAI Direct API
- Endpoint:
https://api.openai.com/v1/chat/completions - Headers:
Authorization: Bearer {api_key} - CORS: Native support, no special headers required
Anthropic Direct API
- Endpoint:
https://api.anthropic.com/v1/messages - Headers:
x-api-key: {api_key}anthropic-version: 2023-06-01anthropic-dangerous-direct-browser-access: true
- CORS: Native support with special header
Testing
Verification Steps
Anthropic Integration:
- No more
ERR_CONNECTION_REFUSEDerrors - Direct API calls to
https://api.anthropic.com/v1/messages - Proper CORS headers included
- Logs show
🚀 ANTHROPIC REQUEST: Using direct API for model:
- No more
OpenAI Integration:
- Direct API calls to
https://api.openai.com/v1/chat/completions - Proper Authorization header with Bearer token
- Logs show
🚀 OPENAI REQUEST: Using direct API for model:
- Direct API calls to
Configuration:
- Space Map uses
useDirectApi: trueconfiguration - Both services ignore proxy configuration
- No proxy server dependencies
- Space Map uses
Testing Locations
- ux-test App:
http://localhost:5300/ux-test/#/ai/ai-tester - Space Map App:
http://localhost:9200(when running) - Any app using gograb-ai library
Files Modified
libs/gograb-ai/src/lib/services/anthropic.service.tslibs/gograb-ai/src/lib/services/openai.service.tsapps/space-map/src/app/app.config.ts(verified configuration)
Legacy Files (Optional Cleanup)
Since proxy services are no longer needed, these files can be removed in a future cleanup:
libs/gograb-ai/src/lib/services/anthropic-proxy.service.tslibs/gograb-ai/src/lib/services/openai-proxy.service.tslibs/gograb-ai/proxy-server.jslibs/gograb-ai/run-anthropic-proxy.shlibs/gograb-ai/run-openai-proxy.shlibs/gograb-ai/src/proxy/directoryopenai-proxy/directory
Migration Guide
If you're migrating from the old proxy-based system:
1. Update Configuration
// OLD: Proxy configuration
const config = {
useProxy: true,
proxyUrl: 'http://localhost:3001'
};
// NEW: Direct API configuration
const config = {
useDirectApi: true, // This is now the default
maxRetries: 2,
timeout: 30000
};
2. Remove Proxy Dependencies
// OLD: Proxy service injection
constructor(
private openaiProxy: OpenAIProxyService,
private anthropicProxy: AnthropicProxyService
) {}
// NEW: Direct service injection
constructor(
private openai: OpenAIService,
private anthropic: AnthropicService
) {}
3. Update API Calls
// OLD: Proxy calls
this.openaiProxy.sendMessage(...)
this.anthropicProxy.sendMessage(...)
// NEW: Direct API calls
this.openai.sendMessage(...)
this.anthropic.makeMessagesRequest(...)
Troubleshooting
Common Issues After Migration
API Key Errors
- Ensure API keys are properly formatted
- OpenAI keys start with
sk- - Anthropic keys start with
sk-ant-
CORS Issues
- Verify you're using the direct API services
- Check that proxy services are not being used
- Ensure proper headers are set
Configuration Problems
- Verify
useDirectApi: truein configuration - Check environment variables are set
- Ensure proper provider selection
- Verify
Debug Commands
# Check if services are using direct API
# Look for these console logs:
# 🚀 OPENAI REQUEST: Using direct API for model: gpt-4o
# 🚀 ANTHROPIC REQUEST: Using direct API for model: claude-3-haiku-20240307
# Enable debug logging
localStorage.setItem('gograb-ai-debug', 'true');
Conclusion
The AI integration is now fully functional with:
- ✅ Anthropic using direct API calls with native CORS support
- ✅ OpenAI using direct API calls with native CORS support
- ✅ No proxy server dependencies
- ✅ Simplified architecture
- ✅ Environment-independent deployment
- ✅ Better performance and reliability
The gograb-ai library now works consistently across all environments and applications without requiring any proxy server setup or complex configuration. This represents a significant improvement in reliability, performance, and deployment simplicity.