AAII/static/script.js

118 lines
2.9 KiB
JavaScript

import { marked } from "https://cdn.jsdelivr.net/npm/marked/lib/marked.esm.js";
const promptInput = document.getElementById("userInput");
const chatContainer = document.getElementById("chatContainer");
const typingIndicator = document.getElementById("typingIndicator");
const sendButton = document.getElementById("sendButton");
const session_uuid = self.crypto.randomUUID();
sendButton.addEventListener("click", () => {
sendMessage();
});
promptInput.addEventListener("input", () => {
if (promptInput.value.split("\n").length == 1) {
promptInput.style.height = "2.5rem";
} else {
promptInput.style.height = "";
promptInput.style.height = promptInput.scrollHeight + "px";
}
});
promptInput.addEventListener("keydown", () => {
handleKeyPress(event);
});
async function sendMessage() {
const prompt = promptInput.value.trim();
if (!prompt) {
alert("Please enter a message.");
return;
}
addMessage(prompt, 'user');
promptInput.value = "";
showTypingIndicator();
const generatedText = await generateText(prompt);
addMessage(generatedText, 'bot');
hideTypingIndicator();
}
async function generateText(prompt) {
try {
const response = await fetch("./generate_text_stream", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ session_uuid ,prompt }),
});
if (!response.ok) {
console.error("Error:", response.statusText);
return "Error occurred while generating response.";
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let isFinished = false;
let generatedTextContent = "";
while (!isFinished) {
const { done, value } = await reader.read();
if (done) {
isFinished = true;
break;
}
generatedTextContent += decoder.decode(value, {stream: true});
}
return generatedTextContent;
} catch (error) {
console.error("Error:", error);
return "An error occurred.";
}
}
function addMessage(rawText, type) {
const messageDiv = document.createElement("div");
messageDiv.className = `message ${type}`;
var text = marked.parse(rawText)
messageDiv.innerHTML = `<div class="message-bubble fadeIn">${text}</div>`;
chatContainer.appendChild(messageDiv);
chatContainer.scrollTop = chatContainer.scrollHeight;
hideTypingIndicator();
}
let typingTimeout;
function showTypingIndicator() {
clearTimeout(typingTimeout);
typingIndicator.style.display = "inline-block";
}
function hideTypingIndicator() {
typingTimeout = setTimeout(() => {
typingIndicator.style.display = "none";
}, 1000);
}
function handleKeyPress(event) {
if (event.isComposing || event.keyCode === 229) {
return;
}
if (event.key == "Enter" && !event.shiftKey) {
event.preventDefault();
sendMessage();
}
}
window.onload = () => addMessage("This session is: " + session_uuid, 'bot');