generate html , css and javascript code for website that has integrated ai chatbot
- User
generate html , css and javascript code for website that has integrated ai chatbot
- Assistant
generate html , css and javascript code for website that has integrated ai chatbot
Certainly! Below is a simple implementation of a website with an integrated AI chatbot using HTML, CSS, and JavaScript. This example uses the OpenAI API to power the chatbot. Please note that you'll need an OpenAI API key to make the chatbot functional. For security reasons, it's important to handle the API key securely on the server side. However, for simplicity, this example includes the API call in the JavaScript code. In a production environment, you should set up a server-side proxy to handle API requests securely.
index.html)<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AI Chatbot Integration</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="chat-container">
<div id="chatbox">
<div class="message bot-message">
<div class="message-content">Hello! I'm your AI assistant. How can I help you today?</div>
</div>
</div>
<div class="input-container">
<input type="text" id="userInput" placeholder="Type your message here..." autocomplete="off">
<button id="sendButton">Send</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
styles.css)body {
background-color: #f5f5f5;
font-family: Arial, sans-serif;
}
.chat-container {
width: 400px;
max-width: 90%;
margin: 50px auto;
border: 1px solid #ccc;
background-color: #fff;
display: flex;
flex-direction: column;
height: 500px;
}
#chatbox {
flex: 1;
padding: 15px;
overflow-y: auto;
}
.message {
margin-bottom: 15px;
display: flex;
}
.user-message {
justify-content: flex-end;
}
.bot-message {
justify-content: flex-start;
}
.message-content {
max-width: 70%;
padding: 10px 15px;
border-radius: 15px;
position: relative;
}
.user-message .message-content {
background-color: #0084ff;
color: #fff;
border-bottom-right-radius: 0;
}
.bot-message .message-content {
background-color: #e5e5ea;
color: #000;
border-bottom-left-radius: 0;
}
.input-container {
display: flex;
border-top: 1px solid #ccc;
}
#userInput {
flex: 1;
padding: 10px;
border: none;
outline: none;
}
#sendButton {
padding: 10px 20px;
background-color: #0084ff;
color: #fff;
border: none;
cursor: pointer;
}
#sendButton:hover {
background-color: #006fdd;
}
script.js)// Replace 'YOUR_OPENAI_API_KEY' with your actual OpenAI API key
const OPENAI_API_KEY = 'YOUR_OPENAI_API_KEY';
const chatbox = document.getElementById('chatbox');
const userInput = document.getElementById('userInput');
const sendButton = document.getElementById('sendButton');
sendButton.addEventListener('click', () => {
const message = userInput.value.trim();
if (message !== '') {
addMessage(message, 'user');
userInput.value = '';
getBotResponse(message);
}
});
userInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
sendButton.click();
}
});
function addMessage(message, sender) {
const messageElement = document.createElement('div');
messageElement.classList.add('message', `${sender}-message`);
const content = document.createElement('div');
content.classList.add('message-content');
content.textContent = message;
messageElement.appendChild(content);
chatbox.appendChild(messageElement);
chatbox.scrollTop = chatbox.scrollHeight;
}
async function getBotResponse(userMessage) {
addMessage('Typing...', 'bot');
try {
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${OPENAI_API_KEY}`
},
body: JSON.stringify({
model: 'gpt-3.5-turbo',
messages: [{ role: 'user', content: userMessage }]
})
});
const data = await response.json();
const botMessage = data.choices[0].message.content.trim();
// Remove 'Typing...' message
const typingMessage = chatbox.querySelector('.bot-message:last-child');
if (typingMessage) {
chatbox.removeChild(typingMessage);
}
addMessage(botMessage, 'bot');
} catch (error) {
console.error('Error:', error);
// Remove 'Typing...' message
const typingMessage = chatbox.querySelector('.bot-message:last-child');
if (typingMessage) {
chatbox.removeChild(typingMessage);
}
addMessage('Sorry, something went wrong. Please try again later.', 'bot');
}
}
Save the files: Create three files in the same directory: index.html, styles.css, and script.js. Copy the corresponding code into each file.
Set up the API Key:
'YOUR_OPENAI_API_KEY' in the script.js file with your actual API key.Secure the API Key:
Run the Website:
index.html in a web browser.Below is a simple example of how you might set up a server-side proxy using Node.js and Express to handle API requests securely.
Install Dependencies
npm install express axios cors
Create server.js
const express = require('express');
const axios = require('axios');
const cors = require('cors');
const app = express();
app.use(express.json());
app.use(cors());
// Replace 'YOUR_OPENAI_API_KEY' with your actual OpenAI API key
const OPENAI_API_KEY = 'YOUR_OPENAI_API_KEY';
app.post('/api/chat', async (req, res) => {
const userMessage = req.body.message;
try {
const response = await axios.post('https://api.openai.com/v1/chat/completions', {
model: 'gpt-3.5-turbo',
messages: [{ role: 'user', content: userMessage }]
}, {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${OPENAI_API_KEY}`
}
});
const botMessage = response.data.choices[0].message.content.trim();
res.json({ reply: botMessage });
} catch (error) {
console.error('Error:', error.response ? error.response.data : error.message);
res.status(500).json({ error: 'Error communicating with OpenAI API' });
}
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Update script.js
Modify the getBotResponse function to send the message to your server instead of directly to the OpenAI API.
async function getBotResponse(userMessage) {
addMessage('Typing...', 'bot');
try {
const response = await fetch('http://localhost:3000/api/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ message: userMessage })
});
const data = await response.json();
const botMessage = data.reply;
// Remove 'Typing...' message
const typingMessage = chatbox.querySelector('.bot-message:last-child');
if (typingMessage) {
chatbox.removeChild(typingMessage);
}
addMessage(botMessage, 'bot');
} catch (error) {
console.error('Error:', error);
// Remove 'Typing...' message
const typingMessage = chatbox.querySelector('.bot-message:last-child');
if (typingMessage) {
chatbox.removeChild(typingMessage);
}
addMessage('Sorry, something went wrong. Please try again later.', 'bot');
}
}
Run the Server
node server.js
By following these steps, you've created a simple website with an integrated AI chatbot. This setup allows users to interact with the chatbot, which leverages the power of OpenAI's GPT model to generate responses. Remember to handle your API key securely and consider expanding the functionalities and design according to your needs.