It has become an integral part of modern web applications, improving user engagement and interaction. In this blog, we will explore how to integrate ChatGPT, a powerful language model developed by OpenAI, into a web application using Vanilla JavaScript for the front-end and Node.js for the back-end.
Prerequisites
Before you begin, make sure you have the following options installed.
Node.js and npm – You can download the latest stable version from the official Node.js website (https://nodejs.org).
Step 1: Set up the project
Run the following command to setup back-end-server
mkdir chatbot app
cd chatbot-app
npm init -y
Step 2: Install the Dependencies
We will need a few libraries to handle the server and front end. Use npm to install the necessary dependencies:
npm install express body-parser
Step 3: Set up the Backend Server
Create a new file named server.js in the root directory of your project. This file will handle the communication with the ChatGPT API and serve the frontend files. Add the following code to server.js:
const express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios');
const app = express();
const port = 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// API endpoint for processing user messages
app.post('/api/chat', async (req, res) => {
try {
const { message } = req.body;
const apiKey = 'YOUR_OPENAI_API_KEY';
const apiUrl = 'https://api.openai.com/v1/engines/davinci-codex/completions';
// Send user message to ChatGPT API
const response = await axios.post(apiUrl, {
prompt: message,
max_tokens: 150,
}, {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
},
});
// Extract and send the response from ChatGPT back to the frontend
res.status(200).json({ reply: response.data.choices[0].text.trim() });
} catch (error) {
console.log("🚀 ~ file: index.js:39 ~ app.post ~ error:", error)
console.error('Error:', error.message);
res.status(500).json({ error: 'Something went wrong' });
}
});
// Start the server
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Step 4: Create Frontend
Within the project directory for the front end, create another directory named client. This directory contains our front-end HTML, CSS, and JavaScript files. Create a new file called index.html inside the public directory and add the following HTML structure.
<!DOCTYPE html>
<html>
<head>
<title>ChatGPT Integration</title>
<!-- Add your CSS styles if needed -->
</head>
<body>
<div id="chatbox">
<div id="messages"></div>
<input type="text" id="userInput" placeholder="Type your message here...">
</div>
<script src="./app.js"></script>
</body>
</html>
Step 5: Implementing Frontend Logic
Create a new file named app.js in the public directory and add the following JavaScript code
document.addEventListener('DOMContentLoaded', () => {
const messagesContainer = document.getElementById('messages');
const userInput = document.getElementById('userInput');
const addMessage = (text, sender) => {
const messageElem = document.createElement('div');
messageElem.classList.add('message');
messageElem.classList.add(sender);
messageElem.textContent = text;
messagesContainer.appendChild(messageElem);
messagesContainer.scrollTop = messagesContainer.scrollHeight;
};
const fetchMessageFromChatGpt = async (message) => {
try {
const response = await fetch('/api/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message }),
});
const data = await response.json();
addMessage(data.reply, 'server');
} catch (error) {
console.error('Error:', error.message);
addMessage('Something went wrong', 'server');
}
};
userInput.addEventListener('keypress', (event) => {
if (event.key === 'Enter') {
const message = userInput.value.trim();
if (message !== '') {
addMessage(message, 'user');
userInput.value = '';
fetchMessageFromChatGpt(message);
}
}
});
});
Step 6: Add Styling (Optional)
You can add CSS styles to the index.html file to make the chat interface visually appealing or create a separate CSS file and link to the head section of the HTML
Step 7: Get the OpenAI API Key
Before running the application you must obtain the API key from OpenAI. Visit the OpenAI website (https://beta.openai.com/signup/) to register and get your API key.
Step 8: Run the Backend-server
Run the following command on your terminal to run the Backend Server. In the server.js directory
node server.js
conclusion
In this blog, we went through the process of integrating ChatGPT into a web application using Vanilla JavaScript for the front-end and Node.js for the back-end. By following the steps outlined here, you have created a chatbot that can effectively engage in natural language conversations with users. From here, you can further enhance the chatbot by tweaking the UI, adding user credibility, and expanding the types of interactions it can handle. Happy coding!