UNPKG

cyber-mysql-openai

Version:

Intelligent natural language to SQL translator with self-correction capabilities using OpenAI and MySQL

172 lines 5.78 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Logger = void 0; exports.countTokens = countTokens; // src/utils/index.ts const fs_1 = __importDefault(require("fs")); const path_1 = __importDefault(require("path")); /** * Clase Logger que maneja diferentes niveles de log */ class Logger { constructor(level = 'info', logDir = './logs', enabled = true) { this.level = level; this.logDir = logDir; this.enabled = enabled && level !== 'none'; if (this.enabled) { this.ensureDirectoryExists(this.logDir); } } /** * Configura el nivel de log */ setLevel(level) { this.level = level; this.enabled = this.enabled && level !== 'none'; } /** * Habilita o deshabilita los logs */ setEnabled(enabled) { this.enabled = enabled && this.level !== 'none'; } /** * Configura el directorio de logs */ setLogDirectory(dir) { this.logDir = dir; if (this.enabled) { this.ensureDirectoryExists(this.logDir); } } /** * Registra un mensaje de error */ error(message, data) { if (this.enabled && this.level !== 'none') { this.log('error', message, data); } } /** * Registra un mensaje de advertencia */ warn(message, data) { if (this.enabled && ['error', 'warn', 'info', 'debug'].includes(this.level)) { this.log('warn', message, data); } } /** * Registra un mensaje informativo */ info(message, data) { if (this.enabled && ['info', 'debug'].includes(this.level)) { this.log('info', message, data); } } /** * Registra un mensaje de depuración */ debug(message, data) { if (this.enabled && this.level === 'debug') { this.log('debug', message, data); } } /** * Función interna de log */ log(level, message, data = '') { const date = new Date().toISOString(); const colorMap = { info: '\x1b[36m', // cyan error: '\x1b[31m', // red warn: '\x1b[33m', // yellow debug: '\x1b[35m' // purple }; const resetColor = '\x1b[0m'; const color = colorMap[level] || ''; const dataStr = typeof data === 'object' ? JSON.stringify(data) : data; const logMessage = `[${date}] [${level.toUpperCase()}] ${message} ${dataStr}`; console.log(`${color}${logMessage}${resetColor}`); try { const logFile = path_1.default.join(this.logDir, `${level}.log`); fs_1.default.appendFileSync(logFile, `${logMessage}\n`); } catch (error) { console.error('Error writing to log file:', error); } } /** * Asegura que exista un directorio */ ensureDirectoryExists(dirPath) { if (!fs_1.default.existsSync(dirPath)) { fs_1.default.mkdirSync(dirPath, { recursive: true }); } } /** * Registra el uso de tokens en un archivo de log */ logTokenUsage(requestId, operation, promptTokens, completionTokens, totalTokens, model) { if (!this.enabled) return; try { const logFile = path_1.default.join(this.logDir, 'token_usage.log'); const timestamp = new Date().toISOString(); const logEntry = `${timestamp}|${requestId}|${operation}|${promptTokens}|${completionTokens}|${totalTokens}|${model}\n`; fs_1.default.appendFileSync(logFile, logEntry); this.debug('Token usage logged', { requestId, operation, totalTokens }); } catch (error) { this.error('Error logging token usage:', error); } } /** * Registra prompts y respuestas para análisis */ logPromptAndResponse(requestId, operation, prompt, response, success, attempt = 1, model = 'unknown') { if (!this.enabled) return; try { // Log resumido const logFile = path_1.default.join(this.logDir, 'prompts_responses.log'); const timestamp = new Date().toISOString(); const status = success ? 'SUCCESS' : 'FAILURE'; const logEntry = `${timestamp}|${requestId}|${operation}|${status}|${attempt}|${model}\n`; fs_1.default.appendFileSync(logFile, logEntry); // Log detallado en archivos JSON separados const detailsDir = path_1.default.join(this.logDir, 'details'); this.ensureDirectoryExists(detailsDir); const detailFile = path_1.default.join(detailsDir, `${requestId}_${operation}_${attempt}.json`); const detailData = { timestamp, requestId, operation, success, attempt, model, prompt, response }; fs_1.default.writeFileSync(detailFile, JSON.stringify(detailData, null, 2)); this.debug('Prompt and response logged', { requestId, operation, success }); } catch (error) { this.error('Error logging prompt and response:', error); } } } exports.Logger = Logger; /** * Cuenta tokens en un texto (estimación simple) */ function countTokens(text) { if (!text) return 0; // Una estimación simple: cada 4 caracteres es aproximadamente un token return Math.ceil(text.length / 4); } exports.default = Logger; //# sourceMappingURL=index.js.map