ваше сообщение коммита
This commit is contained in:
@@ -44,9 +44,9 @@ async function checkAdminRole(address) {
|
||||
if (fs.existsSync(keyPath)) {
|
||||
encryptionKey = fs.readFileSync(keyPath, 'utf8').trim();
|
||||
}
|
||||
} catch (keyError) {
|
||||
console.error('Error reading encryption key:', keyError);
|
||||
}
|
||||
} catch (keyError) {
|
||||
// console.error('Error reading encryption key:', keyError);
|
||||
}
|
||||
|
||||
// Получаем токены и RPC из базы с расшифровкой
|
||||
const tokensResult = await db.getQuery()(
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
* GitHub: https://github.com/HB3-ACCELERATOR
|
||||
*/
|
||||
|
||||
console.log('[ai-assistant] loaded');
|
||||
// console.log('[ai-assistant] loaded');
|
||||
|
||||
const { ChatOllama } = require('@langchain/ollama');
|
||||
const { HNSWLib } = require('@langchain/community/vectorstores/hnswlib');
|
||||
@@ -51,7 +51,7 @@ class AIAssistant {
|
||||
this.isModelLoaded = false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Model health check failed:', error);
|
||||
// console.error('Model health check failed:', error);
|
||||
this.isModelLoaded = false;
|
||||
}
|
||||
|
||||
@@ -142,7 +142,7 @@ class AIAssistant {
|
||||
// Основной метод для получения ответа
|
||||
async getResponse(message, language = 'auto', history = null, systemPrompt = '', rules = null) {
|
||||
try {
|
||||
console.log('getResponse called with:', { message, language, history, systemPrompt, rules });
|
||||
// console.log('getResponse called with:', { message, language, history, systemPrompt, rules });
|
||||
|
||||
// Очищаем старый кэш
|
||||
this.cleanupCache();
|
||||
@@ -150,7 +150,7 @@ class AIAssistant {
|
||||
// Проверяем здоровье модели
|
||||
const isHealthy = await this.checkModelHealth();
|
||||
if (!isHealthy) {
|
||||
console.warn('Model is not healthy, returning fallback response');
|
||||
// console.warn('Model is not healthy, returning fallback response');
|
||||
return 'Извините, модель временно недоступна. Пожалуйста, попробуйте позже.';
|
||||
}
|
||||
|
||||
@@ -161,7 +161,7 @@ class AIAssistant {
|
||||
});
|
||||
const cachedResponse = aiCache.get(cacheKey);
|
||||
if (cachedResponse) {
|
||||
console.log('Returning cached response');
|
||||
// console.log('Returning cached response');
|
||||
return cachedResponse;
|
||||
}
|
||||
|
||||
@@ -207,7 +207,7 @@ class AIAssistant {
|
||||
|
||||
// Определяем язык, если не указан явно
|
||||
const detectedLanguage = language === 'auto' ? this.detectLanguage(message) : language;
|
||||
console.log('Detected language:', detectedLanguage);
|
||||
// console.log('Detected language:', detectedLanguage);
|
||||
|
||||
// Формируем system prompt с учётом правил
|
||||
let fullSystemPrompt = systemPrompt || '';
|
||||
@@ -234,22 +234,22 @@ class AIAssistant {
|
||||
|
||||
// Пробуем прямой API запрос (OpenAI-совместимый endpoint)
|
||||
try {
|
||||
console.log('Trying direct API request...');
|
||||
// console.log('Trying direct API request...');
|
||||
response = await this.fallbackRequestOpenAI(messages, detectedLanguage, fullSystemPrompt);
|
||||
console.log('Direct API response received:', response);
|
||||
// console.log('Direct API response received:', response);
|
||||
} catch (error) {
|
||||
console.error('Error in direct API request:', error);
|
||||
// console.error('Error in direct API request:', error);
|
||||
|
||||
// Если прямой запрос не удался, пробуем через ChatOllama (склеиваем сообщения в текст)
|
||||
const chat = this.createChat(detectedLanguage, fullSystemPrompt);
|
||||
try {
|
||||
const prompt = messages.map(m => `${m.role === 'user' ? 'Пользователь' : m.role === 'assistant' ? 'Ассистент' : 'Система'}: ${m.content}`).join('\n');
|
||||
console.log('Sending request to ChatOllama...');
|
||||
// console.log('Sending request to ChatOllama...');
|
||||
const chatResponse = await chat.invoke(prompt);
|
||||
console.log('ChatOllama response:', chatResponse);
|
||||
// console.log('ChatOllama response:', chatResponse);
|
||||
response = chatResponse.content;
|
||||
} catch (chatError) {
|
||||
console.error('Error using ChatOllama:', chatError);
|
||||
// console.error('Error using ChatOllama:', chatError);
|
||||
throw chatError;
|
||||
}
|
||||
}
|
||||
@@ -261,7 +261,7 @@ class AIAssistant {
|
||||
|
||||
return response;
|
||||
} catch (error) {
|
||||
console.error('Error in getResponse:', error);
|
||||
// console.error('Error in getResponse:', error);
|
||||
return 'Извините, я не смог обработать ваш запрос. Пожалуйста, попробуйте позже.';
|
||||
}
|
||||
}
|
||||
@@ -269,7 +269,7 @@ class AIAssistant {
|
||||
// Новый метод для OpenAI/Qwen2.5 совместимого endpoint
|
||||
async fallbackRequestOpenAI(messages, language, systemPrompt = '') {
|
||||
try {
|
||||
console.log('Using fallbackRequestOpenAI with:', { messages, language, systemPrompt });
|
||||
// console.log('Using fallbackRequestOpenAI with:', { messages, language, systemPrompt });
|
||||
const model = this.defaultModel;
|
||||
|
||||
// Создаем AbortController для таймаута
|
||||
@@ -315,7 +315,7 @@ class AIAssistant {
|
||||
}
|
||||
return data.response || '';
|
||||
} catch (error) {
|
||||
console.error('Error in fallbackRequestOpenAI:', error);
|
||||
// console.error('Error in fallbackRequestOpenAI:', error);
|
||||
if (error.name === 'AbortError') {
|
||||
throw new Error('Request timeout - модель не ответила в течение 120 секунд');
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ async function getSettings() {
|
||||
encryptionKey = fs.readFileSync(keyPath, 'utf8').trim();
|
||||
}
|
||||
} catch (keyError) {
|
||||
console.error('Error reading encryption key:', keyError);
|
||||
// console.error('Error reading encryption key:', keyError);
|
||||
}
|
||||
|
||||
// Получаем связанные данные из telegram_settings и email_settings
|
||||
|
||||
@@ -148,7 +148,7 @@ async function getAllLLMModels() {
|
||||
}
|
||||
}
|
||||
} catch (ollamaError) {
|
||||
console.error('Error checking Ollama models:', ollamaError);
|
||||
// console.error('Error checking Ollama models:', ollamaError);
|
||||
// Если не удалось проверить Ollama, добавляем базовые модели
|
||||
allModels.push({ id: 'qwen2.5:7b', provider: 'ollama' });
|
||||
}
|
||||
@@ -167,7 +167,7 @@ async function getAllLLMModels() {
|
||||
|
||||
return uniqueModels;
|
||||
} catch (error) {
|
||||
console.error('Error getting LLM models:', error);
|
||||
// console.error('Error getting LLM models:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -213,7 +213,7 @@ async function getAllEmbeddingModels() {
|
||||
}
|
||||
}
|
||||
} catch (ollamaError) {
|
||||
console.error('Error checking Ollama embedding models:', ollamaError);
|
||||
// console.error('Error checking Ollama embedding models:', ollamaError);
|
||||
// Если не удалось проверить Ollama, добавляем базовые embedding модели
|
||||
allModels.push({ id: 'mxbai-embed-large:latest', provider: 'ollama' });
|
||||
}
|
||||
@@ -232,7 +232,7 @@ async function getAllEmbeddingModels() {
|
||||
|
||||
return uniqueModels;
|
||||
} catch (error) {
|
||||
console.error('Error getting embedding models:', error);
|
||||
// console.error('Error getting embedding models:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
* GitHub: https://github.com/HB3-ACCELERATOR
|
||||
*/
|
||||
|
||||
console.log('[EmailBot] emailBot.js loaded');
|
||||
// console.log('[EmailBot] emailBot.js loaded');
|
||||
const encryptedDb = require('./encryptedDatabaseService');
|
||||
const db = require('../db');
|
||||
const nodemailer = require('nodemailer');
|
||||
@@ -28,7 +28,7 @@ const { isUserBlocked } = require('../utils/userUtils');
|
||||
|
||||
class EmailBotService {
|
||||
constructor() {
|
||||
console.log('[EmailBot] constructor called');
|
||||
// console.log('[EmailBot] constructor called');
|
||||
}
|
||||
|
||||
async getSettingsFromDb() {
|
||||
@@ -43,7 +43,7 @@ class EmailBotService {
|
||||
encryptionKey = fs.readFileSync(keyPath, 'utf8').trim();
|
||||
}
|
||||
} catch (keyError) {
|
||||
console.error('Error reading encryption key:', keyError);
|
||||
// console.error('Error reading encryption key:', keyError);
|
||||
}
|
||||
|
||||
const { rows } = await db.getQuery()(
|
||||
@@ -530,7 +530,7 @@ class EmailBotService {
|
||||
|
||||
async start() {
|
||||
try {
|
||||
console.log('[EmailBot] start() called');
|
||||
// console.log('[EmailBot] start() called');
|
||||
logger.info('[EmailBot] start() called');
|
||||
const imapConfig = await this.getImapConfig();
|
||||
// Логируем IMAP-конфиг (без пароля)
|
||||
@@ -580,7 +580,7 @@ class EmailBotService {
|
||||
};
|
||||
tryConnect();
|
||||
} catch (err) {
|
||||
console.error('[EmailBot] Ошибка при старте:', err);
|
||||
// console.error('[EmailBot] Ошибка при старте:', err);
|
||||
logger.error('[EmailBot] Ошибка при старте:', err);
|
||||
throw err;
|
||||
}
|
||||
@@ -592,5 +592,5 @@ class EmailBotService {
|
||||
}
|
||||
}
|
||||
|
||||
console.log('[EmailBot] module.exports = EmailBotService');
|
||||
// console.log('[EmailBot] module.exports = EmailBotService');
|
||||
module.exports = EmailBotService;
|
||||
|
||||
@@ -20,34 +20,34 @@ class EncryptedDataService {
|
||||
this.isEncryptionEnabled = !!this.encryptionKey;
|
||||
|
||||
if (this.isEncryptionEnabled) {
|
||||
console.log('🔐 Шифрование базы данных активировано');
|
||||
console.log('📋 Автоматическое определение зашифрованных колонок');
|
||||
// console.log('🔐 Шифрование базы данных активировано');
|
||||
// console.log('📋 Автоматическое определение зашифрованных колонок');
|
||||
} else {
|
||||
console.log('⚠️ Шифрование базы данных отключено - ключ не найден');
|
||||
// console.log('⚠️ Шифрование базы данных отключено - ключ не найден');
|
||||
}
|
||||
}
|
||||
|
||||
loadEncryptionKey() {
|
||||
try {
|
||||
const keyPath = path.join(__dirname, '../../ssl/keys/full_db_encryption.key');
|
||||
console.log(`[EncryptedDB] Trying key path: ${keyPath}`);
|
||||
// console.log(`[EncryptedDB] Trying key path: ${keyPath}`);
|
||||
if (fs.existsSync(keyPath)) {
|
||||
const key = fs.readFileSync(keyPath, 'utf8').trim();
|
||||
console.log(`[EncryptedDB] Key loaded from: ${keyPath}, length: ${key.length}`);
|
||||
// console.log(`[EncryptedDB] Key loaded from: ${keyPath}, length: ${key.length}`);
|
||||
return key;
|
||||
}
|
||||
// Попробуем альтернативный путь относительно корня приложения
|
||||
const altKeyPath = '/app/ssl/keys/full_db_encryption.key';
|
||||
console.log(`[EncryptedDB] Trying alternative key path: ${altKeyPath}`);
|
||||
// console.log(`[EncryptedDB] Trying alternative key path: ${altKeyPath}`);
|
||||
if (fs.existsSync(altKeyPath)) {
|
||||
const key = fs.readFileSync(altKeyPath, 'utf8').trim();
|
||||
console.log(`[EncryptedDB] Key loaded from: ${altKeyPath}, length: ${key.length}`);
|
||||
// console.log(`[EncryptedDB] Key loaded from: ${altKeyPath}, length: ${key.length}`);
|
||||
return key;
|
||||
}
|
||||
console.log(`[EncryptedDB] No key file found, using default key`);
|
||||
// console.log(`[EncryptedDB] No key file found, using default key`);
|
||||
return 'default-key';
|
||||
} catch (error) {
|
||||
console.error('❌ Ошибка загрузки ключа шифрования:', error);
|
||||
// console.error('❌ Ошибка загрузки ключа шифрования:', error);
|
||||
return 'default-key';
|
||||
}
|
||||
}
|
||||
@@ -75,7 +75,7 @@ class EncryptedDataService {
|
||||
const selectFields = columns.map(col => {
|
||||
if (col.column_name.endsWith('_encrypted')) {
|
||||
const originalName = col.column_name.replace('_encrypted', '');
|
||||
console.log(`🔓 Расшифровываем поле ${col.column_name} -> ${originalName}`);
|
||||
// console.log(`🔓 Расшифровываем поле ${col.column_name} -> ${originalName}`);
|
||||
if (col.data_type === 'jsonb') {
|
||||
return `decrypt_json(${col.column_name}, $1) as "${originalName}"`;
|
||||
} else {
|
||||
@@ -89,7 +89,7 @@ class EncryptedDataService {
|
||||
|
||||
// Если есть зашифрованная версия, пропускаем незашифрованную
|
||||
if (hasEncryptedVersion) {
|
||||
console.log(`⚠️ Пропускаем незашифрованное поле ${col.column_name} (есть зашифрованная версия)`);
|
||||
// console.log(`⚠️ Пропускаем незашифрованное поле ${col.column_name} (есть зашифрованная версия)`);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -171,16 +171,16 @@ class EncryptedDataService {
|
||||
query += ` LIMIT ${limit}`;
|
||||
}
|
||||
|
||||
console.log(`🔍 [getData] Выполняем запрос:`, query);
|
||||
console.log(`🔍 [getData] Параметры:`, params);
|
||||
// console.log(`🔍 [getData] Выполняем запрос:`, query);
|
||||
// console.log(`🔍 [getData] Параметры:`, params);
|
||||
|
||||
const { rows } = await db.getQuery()(query, params);
|
||||
|
||||
console.log(`📊 Результат запроса из ${tableName}:`, rows);
|
||||
// console.log(`📊 Результат запроса из ${tableName}:`, rows);
|
||||
|
||||
return rows;
|
||||
} catch (error) {
|
||||
console.error(`❌ Ошибка получения данных из ${tableName}:`, error);
|
||||
// console.error(`❌ Ошибка получения данных из ${tableName}:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -223,19 +223,19 @@ class EncryptedDataService {
|
||||
const encryptedColumn = columns.find(col => col.column_name === `${key}_encrypted`);
|
||||
const unencryptedColumn = columns.find(col => col.column_name === key);
|
||||
|
||||
console.log(`🔍 Обрабатываем поле ${key} = "${value}" (тип: ${typeof value})`);
|
||||
// console.log(`🔍 Обрабатываем поле ${key} = "${value}" (тип: ${typeof value})`);
|
||||
|
||||
if (encryptedColumn) {
|
||||
// Если есть зашифрованная колонка, шифруем данные
|
||||
// Проверяем, что значение не пустое перед шифрованием
|
||||
if (value === null || value === undefined || (typeof value === 'string' && value.trim() === '')) {
|
||||
// Пропускаем пустые значения
|
||||
console.log(`⚠️ Пропускаем пустое зашифрованное поле ${key}`);
|
||||
// console.log(`⚠️ Пропускаем пустое зашифрованное поле ${key}`);
|
||||
continue;
|
||||
}
|
||||
const currentParamIndex = paramIndex++;
|
||||
filteredData[key] = value; // Добавляем в отфильтрованные данные
|
||||
console.log(`✅ Добавили зашифрованное поле ${key} в filteredData`);
|
||||
// console.log(`✅ Добавили зашифрованное поле ${key} в filteredData`);
|
||||
if (encryptedColumn.data_type === 'jsonb') {
|
||||
encryptedData[`${key}_encrypted`] = `encrypt_json($${currentParamIndex}, ${hasEncryptedFields ? '$1::text' : 'NULL'})`;
|
||||
} else {
|
||||
@@ -247,15 +247,15 @@ class EncryptedDataService {
|
||||
if ((value === null || value === undefined || (typeof value === 'string' && value.trim() === '')) &&
|
||||
key !== 'role' && key !== 'sender_type') {
|
||||
// Пропускаем пустые значения, кроме role и sender_type
|
||||
console.log(`⚠️ Пропускаем пустое незашифрованное поле ${key}`);
|
||||
// console.log(`⚠️ Пропускаем пустое незашифрованное поле ${key}`);
|
||||
continue;
|
||||
}
|
||||
filteredData[key] = value; // Добавляем в отфильтрованные данные
|
||||
unencryptedData[key] = `$${paramIndex++}`;
|
||||
console.log(`✅ Добавили незашифрованное поле ${key} в filteredData и unencryptedData`);
|
||||
// console.log(`✅ Добавили незашифрованное поле ${key} в filteredData и unencryptedData`);
|
||||
} else {
|
||||
// Если колонка не найдена, пропускаем
|
||||
console.warn(`⚠️ Колонка ${key} не найдена в таблице ${tableName}`);
|
||||
// console.warn(`⚠️ Колонка ${key} не найдена в таблице ${tableName}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -263,9 +263,9 @@ class EncryptedDataService {
|
||||
|
||||
// Проверяем, есть ли данные для сохранения
|
||||
if (Object.keys(allData).length === 0) {
|
||||
console.warn(`⚠️ Нет данных для сохранения в таблице ${tableName} - все значения пустые`);
|
||||
console.warn(`⚠️ Исходные данные:`, data);
|
||||
console.warn(`⚠️ Отфильтрованные данные:`, filteredData);
|
||||
// console.warn(`⚠️ Нет данных для сохранения в таблице ${tableName} - все значения пустые`);
|
||||
// console.warn(`⚠️ Исходные данные:`, data);
|
||||
// console.warn(`⚠️ Отфильтрованные данные:`, filteredData);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -301,7 +301,7 @@ class EncryptedDataService {
|
||||
return rows[0];
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`❌ Ошибка сохранения данных в ${tableName}:`, error);
|
||||
// console.error(`❌ Ошибка сохранения данных в ${tableName}:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -352,7 +352,7 @@ class EncryptedDataService {
|
||||
const result = await db.getQuery()(query, params);
|
||||
return result.rows;
|
||||
} catch (error) {
|
||||
console.error(`❌ Ошибка удаления данных из ${tableName}:`, error);
|
||||
// console.error(`❌ Ошибка удаления данных из ${tableName}:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
* GitHub: https://github.com/HB3-ACCELERATOR
|
||||
*/
|
||||
|
||||
console.log('[identity-service] loaded');
|
||||
// console.log('[identity-service] loaded');
|
||||
|
||||
const encryptedDb = require('./encryptedDatabaseService');
|
||||
const db = require('../db');
|
||||
|
||||
@@ -14,23 +14,23 @@ const encryptedDb = require('./encryptedDatabaseService');
|
||||
const vectorSearch = require('./vectorSearchClient');
|
||||
const { getProviderSettings } = require('./aiProviderSettingsService');
|
||||
|
||||
console.log('[RAG] ragService.js loaded');
|
||||
// console.log('[RAG] ragService.js loaded');
|
||||
|
||||
// Простой кэш для RAG результатов
|
||||
const ragCache = new Map();
|
||||
const RAG_CACHE_TTL = 5 * 60 * 1000; // 5 минут
|
||||
|
||||
async function getTableData(tableId) {
|
||||
console.log(`[RAG] getTableData called for tableId: ${tableId}`);
|
||||
// console.log(`[RAG] getTableData called for tableId: ${tableId}`);
|
||||
|
||||
const columns = await encryptedDb.getData('user_columns', { table_id: tableId });
|
||||
console.log(`[RAG] Found ${columns.length} columns:`, columns.map(col => ({ id: col.id, name: col.name, purpose: col.options?.purpose })));
|
||||
// console.log(`[RAG] Found ${columns.length} columns:`, columns.map(col => ({ id: col.id, name: col.name, purpose: col.options?.purpose })));
|
||||
|
||||
const rows = await encryptedDb.getData('user_rows', { table_id: tableId });
|
||||
console.log(`[RAG] Found ${rows.length} rows:`, rows.map(row => ({ id: row.id, name: row.name })));
|
||||
// console.log(`[RAG] Found ${rows.length} rows:`, rows.map(row => ({ id: row.id, name: row.name })));
|
||||
|
||||
const cellValues = await encryptedDb.getData('user_cell_values', { row_id: { $in: rows.map(row => row.id) } });
|
||||
console.log(`[RAG] Found ${cellValues.length} cell values`);
|
||||
// console.log(`[RAG] Found ${cellValues.length} cell values`);
|
||||
|
||||
const getColId = purpose => columns.find(col => col.options?.purpose === purpose)?.id;
|
||||
const questionColId = getColId('question');
|
||||
@@ -40,14 +40,14 @@ async function getTableData(tableId) {
|
||||
const priorityColId = getColId('priority');
|
||||
const dateColId = getColId('date');
|
||||
|
||||
console.log(`[RAG] Column IDs:`, {
|
||||
question: questionColId,
|
||||
answer: answerColId,
|
||||
context: contextColId,
|
||||
product: productColId,
|
||||
priority: priorityColId,
|
||||
date: dateColId
|
||||
});
|
||||
// console.log(`[RAG] Column IDs:`, {
|
||||
// question: questionColId,
|
||||
// answer: answerColId,
|
||||
// context: contextColId,
|
||||
// product: productColId,
|
||||
// priority: priorityColId,
|
||||
// date: dateColId
|
||||
// });
|
||||
|
||||
const data = rows.map(row => {
|
||||
const cells = cellValues.filter(cell => cell.row_id === row.id);
|
||||
@@ -61,34 +61,34 @@ async function getTableData(tableId) {
|
||||
priority: cells.find(c => c.column_id === priorityColId)?.value,
|
||||
date: cells.find(c => c.column_id === dateColId)?.value,
|
||||
};
|
||||
console.log(`[RAG] Processed row ${row.id}:`, result);
|
||||
// console.log(`[RAG] Processed row ${row.id}:`, result);
|
||||
return result;
|
||||
});
|
||||
return data;
|
||||
}
|
||||
|
||||
async function ragAnswer({ tableId, userQuestion, product = null, threshold = 10 }) {
|
||||
console.log(`[RAG] ragAnswer called: tableId=${tableId}, userQuestion="${userQuestion}"`);
|
||||
// console.log(`[RAG] ragAnswer called: tableId=${tableId}, userQuestion="${userQuestion}"`);
|
||||
|
||||
// Проверяем кэш
|
||||
const cacheKey = `${tableId}:${userQuestion}:${product}`;
|
||||
const cached = ragCache.get(cacheKey);
|
||||
if (cached && (Date.now() - cached.timestamp) < RAG_CACHE_TTL) {
|
||||
console.log(`[RAG] Returning cached result for: ${cacheKey}`);
|
||||
// console.log(`[RAG] Returning cached result for: ${cacheKey}`);
|
||||
return cached.result;
|
||||
}
|
||||
|
||||
const data = await getTableData(tableId);
|
||||
console.log(`[RAG] Got ${data.length} rows from database`);
|
||||
// console.log(`[RAG] Got ${data.length} rows from database`);
|
||||
|
||||
// Подробное логирование данных
|
||||
data.forEach((row, index) => {
|
||||
console.log(`[RAG] Row ${index}:`, {
|
||||
id: row.id,
|
||||
question: row.question,
|
||||
answer: row.answer,
|
||||
product: row.product
|
||||
});
|
||||
// console.log(`[RAG] Row ${index}:`, {
|
||||
// id: row.id,
|
||||
// question: row.question,
|
||||
// answer: row.answer,
|
||||
// product: row.product
|
||||
// });
|
||||
});
|
||||
|
||||
const questions = data.map(row => row.question && typeof row.question === 'string' ? row.question.trim() : row.question);
|
||||
@@ -108,61 +108,61 @@ async function ragAnswer({ tableId, userQuestion, product = null, threshold = 10
|
||||
}
|
||||
}));
|
||||
|
||||
console.log(`[RAG] Prepared ${rowsForUpsert.length} rows for upsert`);
|
||||
console.log(`[RAG] First row:`, rowsForUpsert[0]);
|
||||
// console.log(`[RAG] Prepared ${rowsForUpsert.length} rows for upsert`);
|
||||
// console.log(`[RAG] First row:`, rowsForUpsert[0]);
|
||||
|
||||
// Upsert все вопросы в индекс (можно оптимизировать по изменению)
|
||||
if (rowsForUpsert.length > 0) {
|
||||
await vectorSearch.upsert(tableId, rowsForUpsert);
|
||||
console.log(`[RAG] Upsert completed`);
|
||||
// console.log(`[RAG] Upsert completed`);
|
||||
} else {
|
||||
console.log(`[RAG] No rows to upsert, skipping`);
|
||||
// console.log(`[RAG] No rows to upsert, skipping`);
|
||||
}
|
||||
|
||||
// Поиск
|
||||
let results = [];
|
||||
if (rowsForUpsert.length > 0) {
|
||||
results = await vectorSearch.search(tableId, userQuestion, 2); // Уменьшаем до 2 результатов
|
||||
console.log(`[RAG] Search completed, got ${results.length} results`);
|
||||
// console.log(`[RAG] Search completed, got ${results.length} results`);
|
||||
|
||||
// Подробное логирование результатов поиска
|
||||
results.forEach((result, index) => {
|
||||
console.log(`[RAG] Search result ${index}:`, {
|
||||
row_id: result.row_id,
|
||||
score: result.score,
|
||||
metadata: result.metadata
|
||||
});
|
||||
// console.log(`[RAG] Search result ${index}:`, {
|
||||
// row_id: result.row_id,
|
||||
// score: result.score,
|
||||
// metadata: result.metadata
|
||||
// });
|
||||
});
|
||||
} else {
|
||||
console.log(`[RAG] No data in table, skipping search`);
|
||||
// console.log(`[RAG] No data in table, skipping search`);
|
||||
}
|
||||
|
||||
// Фильтрация по тегам/продукту
|
||||
let filtered = results;
|
||||
console.log(`[RAG] Before filtering: ${filtered.length} results`);
|
||||
// console.log(`[RAG] Before filtering: ${filtered.length} results`);
|
||||
|
||||
if (product) {
|
||||
console.log(`[RAG] Filtering by product:`, product);
|
||||
// console.log(`[RAG] Filtering by product:`, product);
|
||||
filtered = filtered.filter(row => Array.isArray(row.metadata.product) ? row.metadata.product.includes(product) : row.metadata.product === product);
|
||||
console.log(`[RAG] After product filtering: ${filtered.length} results`);
|
||||
// console.log(`[RAG] After product filtering: ${filtered.length} results`);
|
||||
}
|
||||
|
||||
// Берём ближайший результат с учётом порога (по модулю)
|
||||
console.log(`[RAG] Looking for best result with abs(threshold): ${threshold}`);
|
||||
// console.log(`[RAG] Looking for best result with abs(threshold): ${threshold}`);
|
||||
const best = filtered.reduce((acc, row) => {
|
||||
if (Math.abs(row.score) <= threshold && (acc === null || Math.abs(row.score) < Math.abs(acc.score))) {
|
||||
return row;
|
||||
}
|
||||
return acc;
|
||||
}, null);
|
||||
console.log(`[RAG] Best result:`, best);
|
||||
// console.log(`[RAG] Best result:`, best);
|
||||
|
||||
// Логируем все результаты с их score для диагностики
|
||||
if (filtered.length > 0) {
|
||||
console.log(`[RAG] All filtered results with scores:`);
|
||||
filtered.forEach((result, index) => {
|
||||
console.log(`[RAG] ${index}: score=${result.score}, meets_threshold=${Math.abs(result.score) <= threshold}`);
|
||||
});
|
||||
// console.log(`[RAG] All filtered results with scores:`);
|
||||
// filtered.forEach((result, index) => {
|
||||
// console.log(`[RAG] ${index}: score=${result.score}, meets_threshold=${Math.abs(result.score) <= threshold}`);
|
||||
// });
|
||||
}
|
||||
|
||||
const result = {
|
||||
@@ -238,18 +238,18 @@ async function generateLLMResponse({
|
||||
model,
|
||||
language
|
||||
}) {
|
||||
console.log(`[RAG] generateLLMResponse called with:`, {
|
||||
userQuestion,
|
||||
context,
|
||||
answer,
|
||||
systemPrompt,
|
||||
userTags,
|
||||
product,
|
||||
priority,
|
||||
date,
|
||||
model,
|
||||
language
|
||||
});
|
||||
// console.log(`[RAG] generateLLMResponse called with:`, {
|
||||
// userQuestion,
|
||||
// context,
|
||||
// answer,
|
||||
// systemPrompt,
|
||||
// userTags,
|
||||
// product,
|
||||
// priority,
|
||||
// date,
|
||||
// model,
|
||||
// language
|
||||
// });
|
||||
|
||||
try {
|
||||
const aiAssistant = require('./ai-assistant');
|
||||
@@ -286,10 +286,10 @@ async function generateLLMResponse({
|
||||
rules
|
||||
);
|
||||
|
||||
console.log(`[RAG] LLM response generated:`, llmResponse);
|
||||
// console.log(`[RAG] LLM response generated:`, llmResponse);
|
||||
return llmResponse;
|
||||
} catch (error) {
|
||||
console.error(`[RAG] Error generating LLM response:`, error);
|
||||
// console.error(`[RAG] Error generating LLM response:`, error);
|
||||
return 'Извините, произошла ошибка при генерации ответа.';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,13 +40,13 @@ async function getTelegramSettings() {
|
||||
|
||||
// Создание и настройка бота
|
||||
async function getBot() {
|
||||
console.log('[TelegramBot] getBot() called');
|
||||
// console.log('[TelegramBot] getBot() called');
|
||||
if (!botInstance) {
|
||||
console.log('[TelegramBot] Creating new bot instance...');
|
||||
// console.log('[TelegramBot] Creating new bot instance...');
|
||||
const settings = await getTelegramSettings();
|
||||
console.log('[TelegramBot] Got settings, creating Telegraf instance...');
|
||||
// console.log('[TelegramBot] Got settings, creating Telegraf instance...');
|
||||
botInstance = new Telegraf(settings.bot_token);
|
||||
console.log('[TelegramBot] Telegraf instance created');
|
||||
// console.log('[TelegramBot] Telegraf instance created');
|
||||
|
||||
// Обработка команды /start
|
||||
botInstance.command('start', (ctx) => {
|
||||
@@ -489,7 +489,7 @@ async function getBot() {
|
||||
});
|
||||
|
||||
// Запуск бота с таймаутом
|
||||
console.log('[TelegramBot] Before botInstance.launch()');
|
||||
// console.log('[TelegramBot] Before botInstance.launch()');
|
||||
try {
|
||||
// Запускаем бота с таймаутом
|
||||
const launchPromise = botInstance.launch();
|
||||
@@ -498,12 +498,12 @@ async function getBot() {
|
||||
});
|
||||
|
||||
await Promise.race([launchPromise, timeoutPromise]);
|
||||
console.log('[TelegramBot] After botInstance.launch()');
|
||||
// console.log('[TelegramBot] After botInstance.launch()');
|
||||
logger.info('[TelegramBot] Бот запущен');
|
||||
} catch (error) {
|
||||
console.error('[TelegramBot] Error launching bot:', error);
|
||||
// console.error('[TelegramBot] Error launching bot:', error);
|
||||
// Не выбрасываем ошибку, чтобы не блокировать запуск сервера
|
||||
console.log('[TelegramBot] Bot launch failed, but continuing...');
|
||||
// console.log('[TelegramBot] Bot launch failed, but continuing...');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,23 +13,23 @@
|
||||
const encryptedDb = require('./encryptedDatabaseService');
|
||||
|
||||
async function deleteUserById(userId) {
|
||||
console.log('[DELETE] Вызван deleteUserById для userId:', userId);
|
||||
// console.log('[DELETE] Вызван deleteUserById для userId:', userId);
|
||||
try {
|
||||
console.log('[DELETE] Начинаем удаление user_identities для userId:', userId);
|
||||
// console.log('[DELETE] Начинаем удаление user_identities для userId:', userId);
|
||||
const resIdentities = await encryptedDb.deleteData('user_identities', { user_id: userId });
|
||||
console.log('[DELETE] Удалено user_identities:', resIdentities.length);
|
||||
// console.log('[DELETE] Удалено user_identities:', resIdentities.length);
|
||||
|
||||
console.log('[DELETE] Начинаем удаление messages для userId:', userId);
|
||||
// console.log('[DELETE] Начинаем удаление messages для userId:', userId);
|
||||
const resMessages = await encryptedDb.deleteData('messages', { user_id: userId });
|
||||
console.log('[DELETE] Удалено messages:', resMessages.length);
|
||||
// console.log('[DELETE] Удалено messages:', resMessages.length);
|
||||
|
||||
console.log('[DELETE] Начинаем удаление пользователя из users:', userId);
|
||||
// console.log('[DELETE] Начинаем удаление пользователя из users:', userId);
|
||||
const result = await encryptedDb.deleteData('users', { id: userId });
|
||||
console.log('[DELETE] Результат удаления пользователя:', result.length, result);
|
||||
// console.log('[DELETE] Результат удаления пользователя:', result.length, result);
|
||||
|
||||
return result.length;
|
||||
} catch (e) {
|
||||
console.error('[DELETE] Ошибка при удалении пользователя:', e);
|
||||
// console.error('[DELETE] Ошибка при удалении пользователя:', e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user