import { LogParser } from './log-parser'; import { logger } from './logger'; export class ResponseMatcher { private static patterns: Map = new Map(); private static initialized = false; static async initialize(): Promise { if (this.initialized) return; try { this.patterns = await LogParser.getResponsePatterns(); this.initialized = true; logger.info(`Initialized response matcher with ${this.patterns.size} patterns`); } catch (error) { logger.error('Failed to initialize response matcher', { error: (error as Error).message }); } } static async findMatchingResponse(method: string, endpoint: string, requestBody?: unknown): Promise { await this.initialize(); const key = `${method.toUpperCase()} ${endpoint}`; const patterns = this.patterns.get(key); if (!patterns || patterns.length === 0) { logger.debug(`No patterns found for ${key}`); return null; } // If we have multiple patterns, try to find the best match based on request body if (patterns.length > 1 && requestBody) { const bestMatch = this.findBestMatch(patterns, requestBody); if (bestMatch) { logger.debug(`Found best match for ${key} based on request body`); return bestMatch; } } // Return a random pattern if no specific match found const randomPattern = patterns[Math.floor(Math.random() * patterns.length)]; logger.debug(`Using random pattern for ${key}`); return randomPattern; } private static findBestMatch(patterns: unknown[], requestBody: unknown): unknown | null { // Simple matching based on request body properties for (const pattern of patterns) { if (this.matchesRequestBody(pattern, requestBody)) { return pattern; } } return null; } private static matchesRequestBody(pattern: unknown, requestBody: unknown): boolean { // Check if the pattern was generated from a similar request // This is a simplified matching - in a real implementation, you might want more sophisticated matching if (!requestBody || !pattern) return false; // Check for common fields that might indicate a match const commonFields = ['replica_id', 'persona_id', 'conversation_name']; for (const field of commonFields) { if (requestBody[field] && pattern[field] && requestBody[field] === pattern[field]) { return true; } } return false; } static async getResponseVariation(baseResponse: unknown, _variationLevel = 0.1): Promise { if (!baseResponse) return baseResponse; const variation = { ...baseResponse }; // Add some random variation to IDs and timestamps if (variation.conversation_id) { variation.conversation_id = this.addVariation(variation.conversation_id); } if (variation.conversation_url) { variation.conversation_url = this.addVariation(variation.conversation_url); } if (variation.access_token) { variation.access_token = this.addVariation(variation.access_token); } if (variation.created_at) { variation.created_at = new Date().toISOString(); } return variation; } private static addVariation(value: string): string { const timestamp = Date.now().toString(36); const random = Math.random().toString(36).substring(2, 6); return `${value}_${timestamp}${random}`; } static async getErrorResponse(errorType: string, _statusCode: number): Promise { const errorResponses = { 'out_of_conversational_credits': { error: 'out_of_conversational_credits', message: 'You have run out of conversational credits. Please upgrade your plan.', status_code: 402 }, 'invalid_api_key': { error: 'invalid_api_key', message: 'Invalid API key provided', status_code: 401 }, 'rate_limit_exceeded': { error: 'rate_limit_exceeded', message: 'Rate limit exceeded. Please try again later.', status_code: 429 }, 'not_found': { error: 'not_found', message: 'Resource not found', status_code: 404 }, 'validation_error': { error: 'validation_error', message: 'Request validation failed', status_code: 400 } }; return errorResponses[errorType] || { error: 'unknown_error', message: 'An unknown error occurred', status_code: statusCode }; } }