Building a Basic Chatbot Using ChatGPT and React JS with OpenAI API šŸš€

Posted by

Simple Chatbot with chatGPT and React.js

body {
font-family: Arial, sans-serif;
background-color: #f1f1f1;
padding: 20px;
}
.container {
max-width: 600px;
margin: 0 auto;
background-color: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.chatbox {
max-height: 300px;
overflow-y: auto;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
.input-container {
display: flex;
margin-top: 10px;
}
input[type=”text”] {
flex: 1;
padding: 10px;
border-radius: 5px;
border: 1px solid #ccc;
margin-right: 10px;
}
button {
padding: 10px 20px;
background-color: #007bff;
color: #fff;
border: 0;
border-radius: 5px;
cursor: pointer;
}

Simple Chatbot with chatGPT and React.js

ChatGPT: Hello! How can I assist you today?

function sendMessage() {
const userInput = document.getElementById(‘userInput’).value;
const chatbox = document.querySelector(‘.chatbox’);
const userMessage = `

You: ${userInput}

`;
chatbox.innerHTML += userMessage;
document.getElementById(‘userInput’).value = ”;

// Call GPT API here to get response and add it to the chatbox
// Example:
// fetch(‘https://api.openai.com/v1/engines/davinci-codex/completions’, {
// method: ‘POST’,
// headers: {
// ‘Content-Type’: ‘application/json’,
// ‘Authorization’: ‘Bearer YOUR_OPENAI_API_KEY’
// },
// body: JSON.stringify({
// prompt: userInput,
// max_tokens: 150
// })
// })
// .then(response => response.json())
// .then(data => {
// const chatGPTMessage = `

ChatGPT: ${data.choices[0].text.trim()}

`;
// chatbox.innerHTML += chatGPTMessage;
// chatbox.scrollTop = chatbox.scrollHeight;
// })
// .catch(error => console.error(‘Error:’, error));

// For demonstration purposes, adding a hardcoded response
const chatGPTMessage = `

ChatGPT: Sure! I can help you with that.

`;
chatbox.innerHTML += chatGPTMessage;
chatbox.scrollTop = chatbox.scrollHeight;
}