AI-API / templates /index.html
JJ94's picture
Update templates/index.html
21ab711 verified
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Chatbot</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body { padding: 20px; }
#chatBox { height: 400px; overflow-y: auto; border: 1px solid #ddd; padding: 10px; border-radius: 5px; background: #f8f9fa; }
.message { margin-bottom: 10px; padding: 8px 12px; border-radius: 8px; max-width: 75%; }
.user { background: #007bff; color: white; align-self: flex-end; }
.bot { background: #e9ecef; color: black; align-self: flex-start; }
</style>
</head>
<body>
<div class="container">
<h2 class="text-center mb-4">Chatbot</h2>
<div id="chatBox" class="d-flex flex-column"></div>
<div class="input-group mt-3">
<input type="text" id="userInput" class="form-control" placeholder="Type a message...">
<button class="btn btn-primary" onclick="sendMessage()">Send</button>
</div>
</div>
<script>
async function sendMessage() {
let inputField = document.getElementById("userInput");
let chatBox = document.getElementById("chatBox");
let userMessage = inputField.value.trim();
if (!userMessage) return;
inputField.value = "";
// Display user message
let userMsgElement = document.createElement("div");
userMsgElement.className = "message user align-self-end";
userMsgElement.textContent = userMessage;
chatBox.appendChild(userMsgElement);
// Add bot response container
let botMsgElement = document.createElement("div");
botMsgElement.className = "message bot align-self-start";
chatBox.appendChild(botMsgElement);
// Fetch response from backend
let response = await fetch("/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: userMessage })
});
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
let token = decoder.decode(value, { stream: true });
botMsgElement.textContent += token;
// Auto-scroll
chatBox.scrollTop = chatBox.scrollHeight;
}
}
</script>
</body>
</html>