const chatbotToggler = document.querySelector(".chatbot-toggler");
const closeBtn = document.querySelector(".close-btn");
const chatbox = document.querySelector(".chatbox");
const chatInput = document.querySelector(".chat-input textarea");
const sendChatBtn = document.querySelector(".chat-input span");
//const HF_TOKEN = process.env.hf_tok || null;
let userMessage = null; // Variable to store user's message
//// Paste your API key here
const inputInitHeight = chatInput.scrollHeight;
const createChatLi = (message, className) => {
// Create a chat
element with passed message and className
const chatLi = document.createElement("li");
chatLi.classList.add("chat", `${className}`);
let chatContent = className === "outgoing" ? `` : `smart_toy`;
chatLi.innerHTML = chatContent;
chatLi.querySelector("p").textContent = message;
return chatLi; // return chat element
}
function extractAndDecodeAllUnicode(inputString) {
// Регулярное выражение для извлечения содержимого между квадратными скобками после "data: ["
const regexDataContent = /data: \[([^\]]+)\]/;
// Поиск совпадений в строке
const match = inputString.match(regexDataContent);
if (!match || match.length < 2) {
return "В строке нет данных для декодирования."; // Возвращаем сообщение, если совпадений не найдено или они некорректны
}
// Содержимое между квадратными скобками
const dataContent = match[1];
// Регулярное выражение для поиска и замены Unicode-последовательностей вида \uXXXX на соответствующий символ
const decodedString = dataContent.replace(/\\u([\da-f]{4})/gi, function(match, grp) {
return String.fromCharCode(parseInt(grp, 16));
});
return decodedString; // Возвращаем декодированную строку с сохранением пробелов и переносов строк
}
const generateResponse = (chatElement) => {
const API_URL = "https://artem733733-ai-assistant2.hf.space/call/chat2";
//const url1= "https://artem733733-ai-assistant2.hf.space/call/chat2/53daee8b406c45609ef32cb614d3cf64";
const messageElement = chatElement.querySelector("p");
// Предполагается, что userMessage определен где-то вне этой функции или передан в нее как параметр
//const userMessage = "Hello!!"; // Пример сообщения пользователя
const requestOptions = {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
"data": [userMessage]
})
}
//fetch(url1, requestOptions1)
fetch(API_URL, requestOptions)
.then(res => res.json())
.then(result => {
const eventId = String(result.event_id).trim(); // Извлечение eventId из ответа
const url = "https://artem733733-ai-assistant2.hf.space/call/chat2/" + eventId; // Формирование URL для второго запроса
return fetch(url, { method: "GET" }); // Выполнение второго запроса
})
.then(response => response.text())
.then(data => {
const result0 = String(data).trim();
const result1 = extractAndDecodeAllUnicode(result0);
messageElement.textContent = result1; // Обновление элемента сообщения данными из ответа
}).catch(() => {
messageElement.classList.add("error");
messageElement.textContent = "Упс! Что-то пошло не так. Пожалуйста, попробуйте еще раз.";
}).finally(() => chatbox.scrollTo(0, chatbox.scrollHeight));
}
/////const generateResponse = (chatElement) => {
//const API_URL = "https://api.openai.com/v1/chat/completions";
///// const API_URL = "https://artem733733-ai-assistant2.hf.space/call/chat2";
///// const messageElement = chatElement.querySelector("p");
// Define the properties and message for the API request
///// const requestOptions = {
///// method: "POST",
///// headers: {
///// "Content-Type": "application/json",
//"Authorization": `Bearer ${API_KEY}`
//HF_TOKEN=os.environ.get('hf_tok', None)
//"Authorization: Bearer $HF_TOKEN"
///// },
///// body: JSON.stringify({
///// //model: "gpt-3.5-turbo",
///// //model: "gpt-4o-mini",
//messages: [{role: "user", content: userMessage}],
///// "data": [userMessage]
///// })
///// }
///// fetch(API_URL, requestOptions).then(res => res.json()).then(result => {
///// eventId = String(result.event_id).trim(); // Вам нужно будет адаптировать этот шаг в зависимости от структуры ответа
///// url = "https://artem733733-ai-assistant2.hf.space/call/chat2/" + eventId;
///// fetch(url).then(response => response.json()).then(data => {
//return data;
//}).then(response => response.json()).then(data => {
///// messageElement.textContent = String(data).trim() // Обработка данных второго запроса
///// }).catch(() => {
///// messageElement.classList.add("error");
///// messageElement.textContent = "Упс! Что-то пошло не так. Пожалуйста, попробуйте еще раз.";
///// }).finally(() => chatbox.scrollTo(0, chatbox.scrollHeight));
///// }
const handleChat = () => {
userMessage = chatInput.value.trim(); // Get user entered message and remove extra whitespace
if(!userMessage) return;
// Clear the input textarea and set its height to default
chatInput.value = "";
chatInput.style.height = `${inputInitHeight}px`;
// Append the user's message to the chatbox
chatbox.appendChild(createChatLi(userMessage, "outgoing"));
chatbox.scrollTo(0, chatbox.scrollHeight);
setTimeout(() => {
// Display "Thinking..." message while waiting for the response
const incomingChatLi = createChatLi("Думаю...", "incoming");
chatbox.appendChild(incomingChatLi);
chatbox.scrollTo(0, chatbox.scrollHeight);
generateResponse(incomingChatLi);
}, 600);
}
chatInput.addEventListener("input", () => {
// Adjust the height of the input textarea based on its content
chatInput.style.height = `${inputInitHeight}px`;
chatInput.style.height = `${chatInput.scrollHeight}px`;
});
chatInput.addEventListener("keydown", (e) => {
// If Enter key is pressed without Shift key and the window
// width is greater than 800px, handle the chat
if(e.key === "Enter" && !e.shiftKey && window.innerWidth > 800) {
e.preventDefault();
handleChat();
}
});
sendChatBtn.addEventListener("click", handleChat);
closeBtn.addEventListener("click", () => document.body.classList.remove("show-chatbot"));
chatbotToggler.addEventListener("click", () => document.body.classList.toggle("show-chatbot"));