All files / src/modules/ai ai.controller.ts

0% Statements 0/37
0% Branches 0/5
0% Functions 0/13
0% Lines 0/35

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
import {
  Controller,
  Post,
  Get,
  Body,
  Query,
  UseGuards,
  Request,
  HttpStatus,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiBearerAuth,
} from '@nestjs/swagger';
import { AIService } from './services/ai.service';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import {
  GenerateEmbeddingsDto,
  ChatRequestDto,
  ImageAnalysisDto,
  ProductSimilarityDto,
  StyleRecommendationDto,
  ConversationalSearchDto,
  ProductFeatureExtractionDto,
  SustainabilityAnalysisDto,
} from './dto/ai.dto';
 
@ApiTags('AI & Machine Learning')
@Controller('ai')
export class AIController {
  constructor(private readonly aiService: AIService) {}
 
  @Post('embeddings')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth('JWT-auth')
  @ApiOperation({ summary: 'Generate text embeddings for similarity search' })
  @ApiResponse({ 
    status: HttpStatus.OK, 
    description: 'Embeddings generated successfully',
    schema: {
      type: 'object',
      properties: {
        embeddings: { type: 'array', items: { type: 'number' } },
        model: { type: 'string' },
        usage: { type: 'object' },
      },
    },
  })
  async generateEmbeddings(@Body() dto: GenerateEmbeddingsDto) {
    return this.aiService.generateEmbeddings(dto);
  }
 
  @Post('chat')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth('JWT-auth')
  @ApiOperation({ summary: 'Chat with AI assistant' })
  @ApiResponse({ 
    status: HttpStatus.OK, 
    description: 'Chat response generated successfully',
    schema: {
      type: 'object',
      properties: {
        message: { type: 'string' },
        model: { type: 'string' },
        usage: { type: 'object' },
        finishReason: { type: 'string' },
      },
    },
  })
  async chat(@Body() dto: ChatRequestDto) {
    return this.aiService.chat(dto);
  }
 
  @Post('analyze-image')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth('JWT-auth')
  @ApiOperation({ summary: 'Analyze product images using computer vision' })
  @ApiResponse({ 
    status: HttpStatus.OK, 
    description: 'Image analysis completed successfully',
    schema: {
      type: 'object',
      properties: {
        description: { type: 'string' },
        tags: { type: 'array', items: { type: 'string' } },
        colors: { type: 'array', items: { type: 'string' } },
        confidence: { type: 'number' },
        model: { type: 'string' },
      },
    },
  })
  async analyzeImage(@Body() dto: ImageAnalysisDto) {
    return this.aiService.analyzeImage(dto);
  }
 
  @Post('similar-products')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth('JWT-auth')
  @ApiOperation({ summary: 'Find similar products using vector similarity' })
  @ApiResponse({ 
    status: HttpStatus.OK, 
    description: 'Similar products found successfully',
    schema: {
      type: 'object',
      properties: {
        similarProducts: {
          type: 'array',
          items: {
            type: 'object',
            properties: {
              productId: { type: 'string' },
              similarity: { type: 'number' },
              title: { type: 'string' },
              price: { type: 'number' },
              imageUrl: { type: 'string' },
            },
          },
        },
      },
    },
  })
  async findSimilarProducts(@Body() dto: ProductSimilarityDto) {
    return this.aiService.findSimilarProducts(dto);
  }
 
  @Post('style-recommendations')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth('JWT-auth')
  @ApiOperation({ summary: 'Get personalized style recommendations' })
  @ApiResponse({ 
    status: HttpStatus.OK, 
    description: 'Style recommendations generated successfully',
    schema: {
      type: 'object',
      properties: {
        recommendations: {
          type: 'array',
          items: {
            type: 'object',
            properties: {
              productId: { type: 'string' },
              score: { type: 'number' },
              reasoning: { type: 'string' },
              title: { type: 'string' },
              price: { type: 'number' },
              imageUrl: { type: 'string' },
              category: { type: 'string' },
            },
          },
        },
        styleAdvice: { type: 'string' },
        outfitSuggestions: { type: 'array' },
      },
    },
  })
  async getStyleRecommendations(@Body() dto: StyleRecommendationDto, @Request() req) {
    // Use authenticated user ID if not provided
    Iif (!dto.userId) {
      dto.userId = req.user.id;
    }
    return this.aiService.getStyleRecommendations(dto);
  }
 
  @Post('conversational-search')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth('JWT-auth')
  @ApiOperation({ summary: 'Process natural language search queries' })
  @ApiResponse({ 
    status: HttpStatus.OK, 
    description: 'Conversational search processed successfully',
    schema: {
      type: 'object',
      properties: {
        intent: { type: 'string' },
        entities: { type: 'object' },
        searchQuery: { type: 'string' },
        filters: { type: 'object' },
        response: { type: 'string' },
        suggestions: { type: 'array', items: { type: 'string' } },
      },
    },
  })
  async processConversationalSearch(@Body() dto: ConversationalSearchDto, @Request() req) {
    // Use authenticated user ID if not provided
    Iif (!dto.userId) {
      dto.userId = req.user.id;
    }
    return this.aiService.processConversationalSearch(dto);
  }
 
  @Post('extract-features')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth('JWT-auth')
  @ApiOperation({ summary: 'Extract features from product descriptions' })
  @ApiResponse({ 
    status: HttpStatus.OK, 
    description: 'Product features extracted successfully',
    schema: {
      type: 'object',
      properties: {
        category: { type: 'string' },
        style: { type: 'array', items: { type: 'string' } },
        colors: { type: 'array', items: { type: 'string' } },
        materials: { type: 'array', items: { type: 'string' } },
        occasions: { type: 'array', items: { type: 'string' } },
      },
    },
  })
  async extractProductFeatures(@Body() dto: ProductFeatureExtractionDto) {
    return this.aiService.extractProductFeatures(dto.productDescription);
  }
 
  @Post('sustainability-analysis')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth('JWT-auth')
  @ApiOperation({ summary: 'Analyze product sustainability and environmental impact' })
  @ApiResponse({ 
    status: HttpStatus.OK, 
    description: 'Sustainability analysis completed successfully',
    schema: {
      type: 'object',
      properties: {
        sustainabilityScore: { type: 'number' },
        insights: { type: 'string' },
        improvements: { type: 'array', items: { type: 'string' } },
        alternatives: { type: 'array', items: { type: 'string' } },
      },
    },
  })
  async analyzeSustainability(@Body() dto: SustainabilityAnalysisDto) {
    return this.aiService.analyzeSustainability(dto.productData);
  }
 
  @Get('usage-stats')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth('JWT-auth')
  @ApiOperation({ summary: 'Get AI usage statistics and costs' })
  @ApiResponse({ 
    status: HttpStatus.OK, 
    description: 'Usage statistics retrieved successfully',
    schema: {
      type: 'object',
      properties: {
        totalRequests: { type: 'number' },
        totalCost: { type: 'number' },
        averageLatency: { type: 'number' },
        providerBreakdown: { type: 'object' },
        cacheHitRate: { type: 'number' },
      },
    },
  })
  async getUsageStats(@Query('timeframe') timeframe: 'hour' | 'day' | 'week' = 'day') {
    return this.aiService.getUsageStats(timeframe);
  }
 
  @Get('health')
  @ApiOperation({ summary: 'Check health status of AI providers' })
  @ApiResponse({ 
    status: HttpStatus.OK, 
    description: 'Health status retrieved successfully',
    schema: {
      type: 'object',
      properties: {
        huggingFace: { type: 'boolean' },
        openRouter: { type: 'boolean' },
        anthropic: { type: 'boolean' },
        cache: { type: 'boolean' },
      },
    },
  })
  async healthCheck() {
    return this.aiService.healthCheck();
  }
 
  @Post('voice-to-text')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth('JWT-auth')
  @ApiOperation({ summary: 'Convert voice input to text for voice search' })
  @ApiResponse({ 
    status: HttpStatus.OK, 
    description: 'Voice converted to text successfully',
    schema: {
      type: 'object',
      properties: {
        text: { type: 'string' },
        confidence: { type: 'number' },
        language: { type: 'string' },
      },
    },
  })
  async voiceToText(@Body() body: { audioData: string; language?: string }) {
    // This would integrate with speech recognition service
    // For now, return mock response
    return {
      text: 'I am looking for a blue dress under 300 AED',
      confidence: 0.95,
      language: body.language || 'en',
    };
  }
 
  @Post('text-to-voice')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth('JWT-auth')
  @ApiOperation({ summary: 'Convert text response to voice for audio feedback' })
  @ApiResponse({ 
    status: HttpStatus.OK, 
    description: 'Text converted to voice successfully',
    schema: {
      type: 'object',
      properties: {
        audioUrl: { type: 'string' },
        duration: { type: 'number' },
        format: { type: 'string' },
      },
    },
  })
  async textToVoice(@Body() body: { text: string; voice?: string; language?: string }) {
    // This would integrate with text-to-speech service
    // For now, return mock response
    return {
      audioUrl: 'https://savepal.ai/audio/response.mp3',
      duration: 5.2,
      format: 'mp3',
    };
  }
}