All files / src/modules/ai/services ai.service.ts

0% Statements 0/138
0% Branches 0/36
0% Functions 0/21
0% Lines 0/132

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { HuggingFaceService } from './huggingface.service';
import { OpenRouterService } from './openrouter.service';
import { AnthropicService } from './anthropic.service';
import { CacheService } from './cache.service';
import {
  EmbeddingRequest,
  EmbeddingResponse,
  ChatRequest,
  ChatResponse,
  ImageAnalysisRequest,
  ImageAnalysisResponse,
  ProductSimilarityRequest,
  ProductSimilarityResponse,
  StyleRecommendationRequest,
  StyleRecommendationResponse,
  ConversationalSearchRequest,
  ConversationalSearchResponse,
  AIUsageStats,
} from '../interfaces/ai.interface';
 
@Injectable()
export class AIService {
  private readonly logger = new Logger(AIService.name);
  private readonly usageStats: AIUsageStats[] = [];
 
  constructor(
    private readonly huggingFaceService: HuggingFaceService,
    private readonly openRouterService: OpenRouterService,
    private readonly anthropicService: AnthropicService,
    private readonly cacheService: CacheService,
    private readonly configService: ConfigService,
  ) {}
 
  // Embeddings with intelligent provider selection and caching
  async generateEmbeddings(request: EmbeddingRequest): Promise<EmbeddingResponse> {
    const startTime = Date.now();
    
    try {
      // Check cache first
      const model = request.model || 'sentence-transformers/all-MiniLM-L6-v2';
      const cached = await this.cacheService.getCachedEmbeddings(request.text, model);
      
      Iif (cached) {
        this.logger.debug(`Cache hit for embeddings: ${request.text.substring(0, 50)}...`);
        return {
          embeddings: cached,
          model,
          usage: { tokens: request.text.length },
        };
      }
 
      // Generate new embeddings
      const response = await this.huggingFaceService.generateEmbeddings(request);
      
      // Cache the result
      await this.cacheService.cacheEmbeddings(request.text, response.embeddings, model);
      
      this.trackUsage('HuggingFace', 'embeddings', response.usage?.tokens || 0, Date.now() - startTime);
      
      return response;
    } catch (error) {
      this.logger.error('Embeddings generation failed', error);
      throw error;
    }
  }
 
  // Chat with intelligent provider selection and fallbacks
  async chat(request: ChatRequest): Promise<ChatResponse> {
    const startTime = Date.now();
    const providers = this.getAvailableChatProviders();
    
    for (const provider of providers) {
      try {
        // Check cache for deterministic queries
        Iif (request.temperature === 0 || request.temperature < 0.3) {
          const queryString = JSON.stringify(request.messages);
          const cached = await this.cacheService.getCachedChatResponse(queryString, provider.name);
          
          Iif (cached) {
            this.logger.debug(`Cache hit for chat: ${provider.name}`);
            return cached;
          }
        }
 
        let response: ChatResponse;
        
        if (provider.name === 'OpenRouter') {
          response = await this.openRouterService.chat(request);
        } else if (provider.name === 'Anthropic') {
          response = await this.anthropicService.chat(request);
        } else {
          continue; // Skip unknown providers
        }
 
        // Cache deterministic responses
        Iif (request.temperature === 0 || request.temperature < 0.3) {
          const queryString = JSON.stringify(request.messages);
          await this.cacheService.cacheChatResponse(queryString, response, provider.name);
        }
 
        this.trackUsage(provider.name, 'chat', response.usage?.totalTokens || 0, Date.now() - startTime);
        
        return response;
      } catch (error) {
        this.logger.warn(`Chat failed with ${provider.name}, trying next provider`, error);
        continue;
      }
    }
 
    throw new Error('All chat providers failed');
  }
 
  // Image analysis with caching
  async analyzeImage(request: ImageAnalysisRequest): Promise<ImageAnalysisResponse> {
    const startTime = Date.now();
    
    try {
      // Check cache
      const cacheKey = `image:${request.imageUrl}:${request.model || 'default'}`;
      const cached = await this.cacheService.get<ImageAnalysisResponse>(cacheKey);
      
      Iif (cached) {
        this.logger.debug(`Cache hit for image analysis: ${request.imageUrl}`);
        return cached;
      }
 
      const response = await this.huggingFaceService.analyzeImage(request);
      
      // Cache for 24 hours
      await this.cacheService.set(cacheKey, response, { ttl: 86400 });
      
      this.trackUsage('HuggingFace', 'imageAnalysis', 1, Date.now() - startTime);
      
      return response;
    } catch (error) {
      this.logger.error('Image analysis failed', error);
      throw error;
    }
  }
 
  // Product similarity search with vector search
  async findSimilarProducts(request: ProductSimilarityRequest): Promise<ProductSimilarityResponse> {
    try {
      // This would integrate with MongoDB Vector Search
      // For now, return mock data
      return {
        similarProducts: [
          {
            productId: 'prod_1',
            similarity: 0.95,
            title: 'Similar Product 1',
            price: 299,
            imageUrl: 'https://example.com/image1.jpg',
          },
          {
            productId: 'prod_2',
            similarity: 0.89,
            title: 'Similar Product 2',
            price: 249,
            imageUrl: 'https://example.com/image2.jpg',
          },
        ],
      };
    } catch (error) {
      this.logger.error('Product similarity search failed', error);
      throw error;
    }
  }
 
  // Style recommendations with advanced AI
  async getStyleRecommendations(request: StyleRecommendationRequest): Promise<StyleRecommendationResponse> {
    const startTime = Date.now();
    
    try {
      // Check cache
      const cached = await this.cacheService.getCachedRecommendations(request.userId, request);
      
      Iif (cached) {
        this.logger.debug(`Cache hit for style recommendations: ${request.userId}`);
        return cached;
      }
 
      // Use Anthropic for detailed style analysis
      const userProfile = { userId: request.userId, preferences: request.preferences };
      const searchContext = { occasion: request.occasion, budget: request.budget };
      const availableProducts = []; // Would fetch from database
 
      const anthropicResponse = await this.anthropicService.generatePersonalizedRecommendations(
        userProfile,
        searchContext,
        availableProducts
      );
 
      // Generate style advice using OpenRouter
      const styleAdvice = await this.openRouterService.generateStyleAdvice(
        request.preferences,
        availableProducts
      );
 
      const response: StyleRecommendationResponse = {
        recommendations: anthropicResponse.recommendations.map(rec => ({
          productId: rec.productId,
          score: rec.score,
          reasoning: rec.reasoning,
          title: `Product ${rec.productId}`,
          price: Math.floor(Math.random() * 500) + 50,
          imageUrl: 'https://example.com/product.jpg',
          category: 'fashion',
        })),
        styleAdvice,
        outfitSuggestions: [
          {
            title: 'Professional Look',
            products: ['prod_1', 'prod_2'],
            occasion: 'work',
          },
        ],
      };
 
      // Cache for 1 hour
      await this.cacheService.cacheRecommendations(request.userId, request, response);
      
      this.trackUsage('Anthropic', 'styleRecommendations', 1000, Date.now() - startTime);
      
      return response;
    } catch (error) {
      this.logger.error('Style recommendations failed', error);
      throw error;
    }
  }
 
  // Conversational search with NLP
  async processConversationalSearch(request: ConversationalSearchRequest): Promise<ConversationalSearchResponse> {
    const startTime = Date.now();
    
    try {
      const response = await this.openRouterService.processConversationalSearch(request);
      
      this.trackUsage('OpenRouter', 'conversationalSearch', request.query.length, Date.now() - startTime);
      
      return response;
    } catch (error) {
      this.logger.error('Conversational search failed', error);
      
      // Fallback response
      return {
        intent: 'search',
        entities: {},
        searchQuery: request.query,
        filters: {},
        response: `I'll help you search for "${request.query}". Let me find the best options for you.`,
        suggestions: ['Show me similar items', 'Filter by price', 'Find deals'],
      };
    }
  }
 
  // Product feature extraction
  async extractProductFeatures(productDescription: string): Promise<any> {
    try {
      return await this.huggingFaceService.extractProductFeatures(productDescription);
    } catch (error) {
      this.logger.error('Product feature extraction failed', error);
      return {
        category: 'unknown',
        style: [],
        colors: [],
        materials: [],
        occasions: [],
      };
    }
  }
 
  // Sustainability analysis
  async analyzeSustainability(productData: any): Promise<any> {
    try {
      return await this.anthropicService.generateSustainabilityInsights(productData);
    } catch (error) {
      this.logger.error('Sustainability analysis failed', error);
      return {
        sustainabilityScore: 50,
        insights: 'Sustainability analysis unavailable',
        improvements: [],
        alternatives: [],
      };
    }
  }
 
  // Usage statistics and monitoring
  async getUsageStats(timeframe: 'hour' | 'day' | 'week' = 'day'): Promise<{
    totalRequests: number;
    totalCost: number;
    averageLatency: number;
    providerBreakdown: Record<string, any>;
    cacheHitRate: number;
  }> {
    const now = Date.now();
    const timeframeMs = {
      hour: 60 * 60 * 1000,
      day: 24 * 60 * 60 * 1000,
      week: 7 * 24 * 60 * 60 * 1000,
    };
 
    const cutoff = now - timeframeMs[timeframe];
    const recentStats = this.usageStats.filter(stat => stat.timestamp.getTime() > cutoff);
 
    const totalRequests = recentStats.length;
    const totalCost = recentStats.reduce((sum, stat) => sum + stat.cost, 0);
    const averageLatency = recentStats.reduce((sum, stat) => sum + stat.latency, 0) / totalRequests || 0;
 
    const providerBreakdown = recentStats.reduce((acc, stat) => {
      Iif (!acc[stat.provider]) {
        acc[stat.provider] = { requests: 0, cost: 0, latency: 0 };
      }
      acc[stat.provider].requests++;
      acc[stat.provider].cost += stat.cost;
      acc[stat.provider].latency += stat.latency;
      return acc;
    }, {});
 
    // Calculate average latency per provider
    Object.keys(providerBreakdown).forEach(provider => {
      providerBreakdown[provider].latency /= providerBreakdown[provider].requests;
    });
 
    const cacheStats = await this.cacheService.getStats();
 
    return {
      totalRequests,
      totalCost,
      averageLatency,
      providerBreakdown,
      cacheHitRate: cacheStats.hitRate,
    };
  }
 
  // Health check for all AI providers
  async healthCheck(): Promise<Record<string, boolean>> {
    const [huggingFace, openRouter, anthropic] = await Promise.allSettled([
      this.huggingFaceService.isAvailable(),
      this.openRouterService.isAvailable(),
      this.anthropicService.isAvailable(),
    ]);
 
    return {
      huggingFace: huggingFace.status === 'fulfilled' && huggingFace.value,
      openRouter: openRouter.status === 'fulfilled' && openRouter.value,
      anthropic: anthropic.status === 'fulfilled' && anthropic.value,
      cache: true, // Redis health would be checked separately
    };
  }
 
  // Private helper methods
 
  private getAvailableChatProviders(): Array<{ name: string; priority: number }> {
    // Return providers in order of preference
    return [
      { name: 'OpenRouter', priority: 1 },
      { name: 'Anthropic', priority: 2 },
    ];
  }
 
  private trackUsage(provider: string, operation: string, tokens: number, latency: number, userId?: string): void {
    const cost = this.getCostForProvider(provider, operation, tokens);
    
    const stat: AIUsageStats = {
      provider,
      operation,
      tokens,
      cost,
      latency,
      timestamp: new Date(),
      userId,
    };
 
    this.usageStats.push(stat);
 
    // Keep only recent stats to prevent memory bloat
    const cutoff = Date.now() - (7 * 24 * 60 * 60 * 1000); // 7 days
    this.usageStats.splice(0, this.usageStats.findIndex(s => s.timestamp.getTime() > cutoff));
 
    this.logger.debug(`AI Usage: ${provider} ${operation} - ${tokens} tokens, ${latency}ms, $${cost.toFixed(4)}`);
  }
 
  private getCostForProvider(provider: string, operation: string, tokens: number): number {
    switch (provider) {
      case 'HuggingFace':
        return this.huggingFaceService.getCost(operation, tokens);
      case 'OpenRouter':
        return this.openRouterService.getCost(operation, tokens);
      case 'Anthropic':
        return this.anthropicService.getCost(operation, tokens);
      default:
        return 0;
    }
  }
}