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

0% Statements 0/96
0% Branches 0/39
0% Functions 0/17
0% Lines 0/91

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import axios, { AxiosInstance } from 'axios';
import {
  ChatRequest,
  ChatResponse,
  ConversationalSearchRequest,
  ConversationalSearchResponse,
  AIProvider,
} from '../interfaces/ai.interface';
 
@Injectable()
export class OpenRouterService implements AIProvider {
  private readonly logger = new Logger(OpenRouterService.name);
  private readonly httpClient: AxiosInstance;
  private readonly apiKey: string;
  private readonly baseUrl: string;
 
  // Available models with their costs (per 1M tokens)
  private readonly models = {
    chat: 'anthropic/claude-3-sonnet',
    fallback: 'openai/gpt-4-turbo',
    fast: 'openai/gpt-3.5-turbo',
    creative: 'anthropic/claude-3-opus',
  };
 
  private readonly modelCosts = {
    'anthropic/claude-3-sonnet': { input: 3.0, output: 15.0 },
    'openai/gpt-4-turbo': { input: 10.0, output: 30.0 },
    'openai/gpt-3.5-turbo': { input: 0.5, output: 1.5 },
    'anthropic/claude-3-opus': { input: 15.0, output: 75.0 },
  };
 
  private requestCount = 0;
  private dailyRequestCount = 0;
 
  constructor(private configService: ConfigService) {
    this.apiKey = this.configService.get<string>('ai.openrouter.apiKey');
    this.baseUrl = this.configService.get<string>('ai.openrouter.baseUrl');
 
    this.httpClient = axios.create({
      baseURL: this.baseUrl,
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json',
        'HTTP-Referer': 'https://savepal.ai',
        'X-Title': 'SavePal AI Shopping Assistant',
      },
      timeout: 60000, // 60 seconds for longer responses
    });
  }
 
  get name(): string {
    return 'OpenRouter';
  }
 
  async isAvailable(): Promise<boolean> {
    try {
      const response = await this.httpClient.get('/models');
      return response.status === 200;
    } catch (error) {
      this.logger.error('OpenRouter API is not available', error);
      return false;
    }
  }
 
  getCost(operation: string, tokens: number): number {
    const model = this.models.chat;
    const costs = this.modelCosts[model];
    
    Iif (!costs) return 0;
    
    // Estimate input/output split (70% input, 30% output)
    const inputTokens = Math.floor(tokens * 0.7);
    const outputTokens = Math.floor(tokens * 0.3);
    
    return ((inputTokens * costs.input) + (outputTokens * costs.output)) / 1000000;
  }
 
  getRateLimit(): { requestsPerMinute: number; requestsPerDay: number } {
    return this.configService.get('ai.rateLimits.openrouter', {
      requestsPerMinute: 60,
      requestsPerDay: 5000,
    });
  }
 
  async chat(request: ChatRequest): Promise<ChatResponse> {
    const startTime = Date.now();
    
    try {
      await this.checkRateLimit();
      
      const model = request.model || this.models.chat;
      
      const messages = request.systemPrompt 
        ? [{ role: 'system', content: request.systemPrompt }, ...request.messages]
        : request.messages;
 
      const response = await this.httpClient.post('/chat/completions', {
        model,
        messages,
        temperature: request.temperature || 0.7,
        max_tokens: request.maxTokens || 2000,
        stream: false,
      });
 
      const completion = response.data;
      const message = completion.choices[0]?.message?.content || '';
      
      this.trackUsage('chat', completion.usage?.total_tokens || 0, Date.now() - startTime);
 
      return {
        message,
        model,
        usage: completion.usage ? {
          promptTokens: completion.usage.prompt_tokens,
          completionTokens: completion.usage.completion_tokens,
          totalTokens: completion.usage.total_tokens,
        } : undefined,
        finishReason: completion.choices[0]?.finish_reason,
      };
    } catch (error) {
      this.logger.error('OpenRouter chat failed', error);
      throw new Error(`OpenRouter chat failed: ${error.message}`);
    }
  }
 
  async processConversationalSearch(request: ConversationalSearchRequest): Promise<ConversationalSearchResponse> {
    try {
      const systemPrompt = `You are SavePal, an AI shopping assistant for the GCC region. Your job is to understand user shopping queries and convert them into structured search parameters.
 
User Context:
- Region: GCC (UAE, Saudi Arabia, Qatar, Kuwait)
- Currency: AED (default)
- Available retailers: Namshi, Noon, Amazon UAE
 
For each query, provide:
1. Intent classification (search, compare, recommend, style_advice, budget_help)
2. Extracted entities (category, brand, color, size, price_range, occasion)
3. Structured search query
4. Appropriate filters
5. Natural language response
6. Follow-up suggestions
 
Always be helpful, culturally aware, and focused on saving money.`;
 
      const userMessage = `Query: "${request.query}"
${request.context ? `Context: ${JSON.stringify(request.context)}` : ''}
 
Please analyze this shopping query and provide structured output.`;
 
      const chatResponse = await this.chat({
        messages: [{ role: 'user', content: userMessage }],
        systemPrompt,
        temperature: 0.3, // Lower temperature for more consistent parsing
        maxTokens: 1000,
      });
 
      // Parse the AI response to extract structured data
      const parsedResponse = this.parseConversationalResponse(chatResponse.message, request.query);
      
      return parsedResponse;
    } 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 range',
          'Find deals and coupons',
        ],
      };
    }
  }
 
  async generateProductDescription(productData: any): Promise<string> {
    try {
      const systemPrompt = `You are a professional product copywriter for SavePal, an AI shopping platform in the GCC region. Create engaging, SEO-friendly product descriptions that highlight value and savings opportunities.
 
Guidelines:
- Focus on benefits and value proposition
- Mention potential savings opportunities
- Use culturally appropriate language for GCC market
- Include relevant keywords naturally
- Keep descriptions concise but informative (100-200 words)`;
 
      const userMessage = `Create a product description for:
Title: ${productData.title}
Brand: ${productData.brand}
Category: ${productData.category}
Price: ${productData.price} ${productData.currency}
Features: ${JSON.stringify(productData.features || {})}`;
 
      const response = await this.chat({
        messages: [{ role: 'user', content: userMessage }],
        systemPrompt,
        temperature: 0.8,
        maxTokens: 300,
      });
 
      return response.message;
    } catch (error) {
      this.logger.error('Product description generation failed', error);
      return productData.title || 'Product description not available';
    }
  }
 
  async generateStyleAdvice(userPreferences: any, products: any[]): Promise<string> {
    try {
      const systemPrompt = `You are SavePal's AI style consultant. Provide personalized styling advice for users in the GCC region, considering local culture, climate, and fashion preferences.
 
Guidelines:
- Be culturally sensitive and appropriate
- Consider the GCC climate (hot, humid)
- Suggest versatile pieces that offer good value
- Include styling tips for different occasions
- Mention potential cost savings through smart shopping`;
 
      const userMessage = `User Preferences: ${JSON.stringify(userPreferences)}
Available Products: ${JSON.stringify(products.slice(0, 5))}
 
Provide styling advice and outfit suggestions.`;
 
      const response = await this.chat({
        messages: [{ role: 'user', content: userMessage }],
        systemPrompt,
        temperature: 0.9,
        maxTokens: 500,
      });
 
      return response.message;
    } catch (error) {
      this.logger.error('Style advice generation failed', error);
      return 'Style advice is currently unavailable. Please try again later.';
    }
  }
 
  private parseConversationalResponse(aiResponse: string, originalQuery: string): ConversationalSearchResponse {
    try {
      // Try to extract JSON from the response
      const jsonMatch = aiResponse.match(/\{[\s\S]*\}/);
      Iif (jsonMatch) {
        const parsed = JSON.parse(jsonMatch[0]);
        return {
          intent: parsed.intent || 'search',
          entities: parsed.entities || {},
          searchQuery: parsed.searchQuery || originalQuery,
          filters: parsed.filters || {},
          response: parsed.response || aiResponse,
          suggestions: parsed.suggestions || [],
        };
      }
    } catch (error) {
      this.logger.warn('Failed to parse structured AI response', error);
    }
 
    // Fallback: extract basic information using simple parsing
    return {
      intent: this.extractIntent(aiResponse),
      entities: this.extractEntities(aiResponse),
      searchQuery: originalQuery,
      filters: {},
      response: aiResponse,
      suggestions: this.generateSuggestions(originalQuery),
    };
  }
 
  private extractIntent(text: string): string {
    const intentKeywords = {
      search: ['find', 'search', 'look for', 'show me'],
      compare: ['compare', 'vs', 'versus', 'difference'],
      recommend: ['recommend', 'suggest', 'best', 'good'],
      style_advice: ['style', 'outfit', 'match', 'coordinate'],
      budget_help: ['cheap', 'budget', 'affordable', 'save money'],
    };
 
    for (const [intent, keywords] of Object.entries(intentKeywords)) {
      Iif (keywords.some(keyword => text.toLowerCase().includes(keyword))) {
        return intent;
      }
    }
 
    return 'search';
  }
 
  private extractEntities(text: string): Record<string, any> {
    const entities: Record<string, any> = {};
    
    // Simple entity extraction (in production, use more sophisticated NLP)
    const priceMatch = text.match(/(\d+)\s*(aed|dirham|dollar)/i);
    Iif (priceMatch) {
      entities.price_max = parseInt(priceMatch[1]);
    }
 
    const colorMatch = text.match(/(black|white|red|blue|green|yellow|pink|brown|gray|grey)/i);
    Iif (colorMatch) {
      entities.color = colorMatch[1].toLowerCase();
    }
 
    return entities;
  }
 
  private generateSuggestions(query: string): string[] {
    return [
      'Show me similar items',
      'Filter by price range',
      'Find deals and coupons',
      'Compare with other brands',
      'Get styling advice',
    ];
  }
 
  private async checkRateLimit(): Promise<void> {
    const limits = this.getRateLimit();
    
    Iif (this.dailyRequestCount >= limits.requestsPerDay) {
      throw new Error('Daily rate limit exceeded for OpenRouter API');
    }
 
    Iif (this.requestCount >= limits.requestsPerMinute) {
      await new Promise(resolve => setTimeout(resolve, 60000));
      this.requestCount = 0;
    }
 
    this.requestCount++;
    this.dailyRequestCount++;
  }
 
  private trackUsage(operation: string, tokens: number, latency: number): void {
    const cost = this.getCost(operation, tokens);
    
    this.logger.log(`OpenRouter ${operation}: ${tokens} tokens, ${latency}ms, $${cost.toFixed(4)}`);
  }
}