|
<!DOCTYPE html> |
|
<html lang="en"> |
|
<head> |
|
<meta charset="UTF-8"> |
|
<meta name="viewport" content="width=device-width, initial-scale=1"> |
|
<title>Chat with AI</title> |
|
|
|
|
|
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"> |
|
|
|
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js" defer></script> |
|
|
|
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> |
|
|
|
<style> |
|
body { |
|
background-color: #f8f9fa; |
|
} |
|
.chat-box { |
|
height: 400px; |
|
overflow-y: auto; |
|
background: white; |
|
padding: 15px; |
|
border-radius: 10px; |
|
box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1); |
|
} |
|
.message { |
|
padding: 8px 12px; |
|
border-radius: 8px; |
|
margin-bottom: 10px; |
|
} |
|
.user-message { |
|
background-color: #d1e7dd; |
|
text-align: right; |
|
} |
|
.ai-message { |
|
background-color: #e2e3e5; |
|
} |
|
</style> |
|
</head> |
|
<body> |
|
|
|
<div class="container mt-5" x-data="chatApp()"> |
|
<h2 class="text-center mb-4">💬 Chat with AI</h2> |
|
|
|
<div class="chat-box mb-3" id="chatBox"> |
|
<template x-for="message in messages"> |
|
<div :class="{'user-message': message.role === 'user', 'ai-message': message.role === 'ai'}" class="message"> |
|
<strong x-text="message.role === 'user' ? 'You: ' : 'AI: '"></strong> |
|
<span x-text="message.text"></span> |
|
</div> |
|
</template> |
|
</div> |
|
|
|
<div class="input-group"> |
|
<input type="text" class="form-control" placeholder="Type a message..." x-model="userMessage" @keydown.enter="sendMessage"> |
|
<button class="btn btn-primary" @click="sendMessage">Send</button> |
|
</div> |
|
</div> |
|
|
|
<script> |
|
function chatApp() { |
|
return { |
|
userMessage: '', |
|
messages: [], |
|
|
|
async sendMessage() { |
|
if (!this.userMessage.trim()) return; |
|
|
|
let messageText = this.userMessage; |
|
this.messages.push({ role: 'user', text: messageText }); |
|
this.userMessage = ''; |
|
|
|
let aiResponse = { role: 'ai', text: '' }; |
|
this.messages.push(aiResponse); |
|
|
|
let response = await fetch('/chat', { |
|
method: 'POST', |
|
headers: { 'Content-Type': 'application/json' }, |
|
body: JSON.stringify({ message: messageText }) |
|
}); |
|
|
|
const reader = response.body.getReader(); |
|
const decoder = new TextDecoder(); |
|
|
|
while (true) { |
|
const { done, value } = await reader.read(); |
|
if (done) break; |
|
aiResponse.text += decoder.decode(value, { stream: true }); |
|
} |
|
|
|
|
|
this.$nextTick(() => { |
|
let chatBox = document.getElementById('chatBox'); |
|
chatBox.scrollTop = chatBox.scrollHeight; |
|
}); |
|
} |
|
}; |
|
} |
|
</script> |
|
|
|
</body> |
|
</html> |
|
|
|
|