File size: 2,684 Bytes
a38d127 784284e 21ab711 3a8dd40 784284e 21ab711 784284e 21ab711 a38d127 21ab711 784284e a38d127 21ab711 784284e 21ab711 784284e 21ab711 784284e 21ab711 784284e 21ab711 b20aff0 21ab711 784284e a38d127 21ab711 a38d127 e24e31f 3a8dd40 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
<!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>
|