Create logicHandler/aiService.js
Browse files
processors/logicHandler/aiService.js
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const { GoogleGenerativeAI } = require("@google/generative-ai");
|
| 2 |
+
const fs = require("fs");
|
| 3 |
+
const path = require("path");
|
| 4 |
+
const googleSheets = require("../../services/googleSheets");
|
| 5 |
+
|
| 6 |
+
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
|
| 7 |
+
const MEMORY_PATH = path.join(process.cwd(), 'learned_keywords.json');
|
| 8 |
+
|
| 9 |
+
// --- CẤU HÌNH SONG MÃ (2 MODEL) ---
|
| 10 |
+
const sysPrompt = "JSON ONLY. NO TALK. NO EXPLANATION. Fields: reply, intent, keyword, regex.";
|
| 11 |
+
|
| 12 |
+
const model31b = genAI.getGenerativeModel({
|
| 13 |
+
model: "gemma-4-31b-it",
|
| 14 |
+
systemInstruction: sysPrompt
|
| 15 |
+
});
|
| 16 |
+
|
| 17 |
+
const model26b = genAI.getGenerativeModel({
|
| 18 |
+
model: "gemma-4-26b-a4b-it",
|
| 19 |
+
systemInstruction: sysPrompt
|
| 20 |
+
});
|
| 21 |
+
|
| 22 |
+
/**
|
| 23 |
+
* HÀM CHÍNH: Nhận thêm biến session để biết khách là ai
|
| 24 |
+
*/
|
| 25 |
+
async function askTeacher(message, session = {}) {
|
| 26 |
+
console.log("📩 Khách nhắn:", message);
|
| 27 |
+
|
| 28 |
+
// Trích xuất thông tin khách từ session
|
| 29 |
+
const customerInfo = {
|
| 30 |
+
name: session.entities?.name || "Mẹ",
|
| 31 |
+
weight: session.entities?.weight ? `${session.entities.weight}kg` : "chưa rõ cân nặng",
|
| 32 |
+
address: session.entities?.address || "Đà Nẵng",
|
| 33 |
+
age: session.entities?.age || "bé"
|
| 34 |
+
};
|
| 35 |
+
|
| 36 |
+
// Đưa thông tin khách vào Prompt để AI "thân mật" hơn
|
| 37 |
+
const prompt = `[HƯỚNG DẪN TỐI CAO]:
|
| 38 |
+
1. Bối cảnh: Bạn là nhân viên shop Hương Kid.
|
| 39 |
+
2. Khách hàng: ${customerInfo.name} (Bé ${customerInfo.weight}, ở ${customerInfo.address}).
|
| 40 |
+
3. Quy tắc trả lời:
|
| 41 |
+
- Luôn gọi "Mẹ" hoặc "Chị", xưng "Em" hoặc "Shop".
|
| 42 |
+
- Câu trả lời phải THÂN MẬT, VUI VẺ.
|
| 43 |
+
- CẤM nói mỗi câu "Đợi em tí".
|
| 44 |
+
- LUÔN KẾT THÚC BẰNG CÂU HỎI hoặc GỢI Ý HÀNH ĐỘNG (Ví dụ: Mẹ muốn xem mẫu váy hay bộ đồ ạ? Mẹ thích tông màu sáng hay tối cho bé?).
|
| 45 |
+
|
| 46 |
+
Tin nhắn khách: "${message}"
|
| 47 |
+
|
| 48 |
+
YÊU CẦU: Trả về duy nhất 1 object JSON.
|
| 49 |
+
Mẫu JSON: {"reply": "Câu trả lời + Câu hỏi gợi mở", "intent": "CONSULT", "keyword": "...", "regex": "..."}`;
|
| 50 |
+
|
| 51 |
+
let result;
|
| 52 |
+
try {
|
| 53 |
+
// --- GIỮ NGUYÊN CƠ CHẾ SONG MÃ (31b/26b) ---
|
| 54 |
+
try {
|
| 55 |
+
result = await model31b.generateContent(prompt);
|
| 56 |
+
} catch (err) {
|
| 57 |
+
result = await model26b.generateContent(prompt);
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
const responseText = result.response.text();
|
| 61 |
+
const matches = responseText.match(/\{[\s\S]*?\}/g);
|
| 62 |
+
if (!matches) throw new Error("AI không trả về JSON");
|
| 63 |
+
|
| 64 |
+
const cleanJson = matches[matches.length - 1].replace(/[\u0000-\u001F\u007F-\u009F]/g, "").trim();
|
| 65 |
+
const data = JSON.parse(cleanJson);
|
| 66 |
+
|
| 67 |
+
// Lưu log (giữ nguyên)
|
| 68 |
+
saveEverything(message, data).catch(e => console.error("❌ Lỗi lưu:", e.message));
|
| 69 |
+
|
| 70 |
+
return data;
|
| 71 |
+
} catch (e) {
|
| 72 |
+
return { reply: `Dạ ${customerInfo.name} đợi em xíu nhen, em kiểm tra kho ạ!`, intent: "CONSULT", keyword: "lỗi", regex: ".*" };
|
| 73 |
+
}
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
/**
|
| 77 |
+
* HÀM GHI DỮ LIỆU TỔNG HỢP
|
| 78 |
+
*/
|
| 79 |
+
async function saveEverything(userText, aiData) {
|
| 80 |
+
try {
|
| 81 |
+
if (!aiData.keyword) return;
|
| 82 |
+
|
| 83 |
+
// 1. Lưu Local JSON
|
| 84 |
+
let memory = {};
|
| 85 |
+
if (fs.existsSync(MEMORY_PATH)) {
|
| 86 |
+
const raw = fs.readFileSync(MEMORY_PATH, 'utf-8');
|
| 87 |
+
memory = raw ? JSON.parse(raw) : {};
|
| 88 |
+
}
|
| 89 |
+
memory[aiData.keyword.toLowerCase()] = {
|
| 90 |
+
...aiData,
|
| 91 |
+
learnedAt: new Date().toLocaleString('vi-VN')
|
| 92 |
+
};
|
| 93 |
+
fs.writeFileSync(MEMORY_PATH, JSON.stringify(memory, null, 2));
|
| 94 |
+
|
| 95 |
+
// 2. Lưu Google Sheets (Đầy đủ 9 cột)
|
| 96 |
+
const now = new Date();
|
| 97 |
+
const timeId = `${now.getFullYear()}-${(now.getMonth()+1).toString().padStart(2,'0')}-${now.getDate().toString().padStart(2,'0')}_${now.getHours()}h${now.getMinutes()}`;
|
| 98 |
+
|
| 99 |
+
const rowData = [
|
| 100 |
+
timeId, // A: Thời gian
|
| 101 |
+
aiData.intent || "CONSULT", // B: Intent
|
| 102 |
+
aiData.keyword, // C: Keyword
|
| 103 |
+
"", // D: Trống
|
| 104 |
+
aiData.regex || ".*", // E: Regex
|
| 105 |
+
"5", // F: Ưu tiên
|
| 106 |
+
"Tactical", // G: Tuyến
|
| 107 |
+
aiData.reply, // H: Trả lời
|
| 108 |
+
"RETAIN" // I: Trạng thái
|
| 109 |
+
];
|
| 110 |
+
|
| 111 |
+
if (googleSheets && typeof googleSheets.appendTacticalLog === 'function') {
|
| 112 |
+
await googleSheets.appendTacticalLog(rowData);
|
| 113 |
+
console.log(`✅ [Hệ thống] Đã học kiến thức mới: [${aiData.keyword}]`);
|
| 114 |
+
}
|
| 115 |
+
} catch (err) {
|
| 116 |
+
console.error("❌ Lỗi saveEverything:", err.message);
|
| 117 |
+
}
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
module.exports = {
|
| 121 |
+
askTeacher,
|
| 122 |
+
callAI_To_Analyze: askTeacher
|
| 123 |
+
};
|