How to Build an Intelligent Chatbot Using OpenAI’s Pre-Trained Models with Javascript
Chatbots are becoming increasingly popular, and they can be used for various purposes, such as customer service, lead generation, and sales. Thanks to advancements in artificial intelligence (AI), chatbots are now more intelligent than ever before, and can carry out more complex tasks. One of the leading companies in the field of AI is OpenAI, which provides state-of-the-art AI tools and models to developers and businesses.
OpenAI was founded in 2015 by a group of tech luminaries, including Elon Musk, Sam Altman, Greg Brockman, Ilya Sutskever, and John Schulman. The company’s mission is to create safe and beneficial AI that can benefit humanity as a whole. OpenAI has since become a leader in the field of AI, and has developed a wide range of models and tools that can be used to create intelligent applications and systems.
One of the most impressive models developed by OpenAI is GPT (Generative Pre-trained Transformer), a machine learning model that can generate human-like text. GPT has been pre-trained on massive amounts of text data, and can generate coherent and contextually appropriate responses to a wide range of prompts. OpenAI has also released several pre-trained versions of GPT, including GPT-2 and GPT-3, which have been used to create some of the most impressive chatbots to date.
OpenAI also provides a chat service, which allows developers and businesses to integrate chatbots into their websites and applications with ease. The service provides access to pre-trained GPT models, as well as a powerful API that allows for customization and control over the chatbot’s behavior.
In this tutorial, we’ll be using OpenAI’s pre-trained models, including GPT-3, to create a chatbot web/mobile application. By leveraging the power of OpenAI’s natural language processing capabilities, we can create an intelligent chatbot, i called it iChatGPT, that can respond to user input in a way that feels natural and human-like. So let’s get started!
Step 1: The HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta http-equiv="Content-Security-Policy" content="default-src * data: gap: content: https://ssl.gstatic.com; style-src * 'unsafe-inline'; script-src * 'unsafe-inline' 'unsafe-eval'">
<!-- monaca resources -->
<script src="components/loader.js"></script>
<link rel="stylesheet" href="components/loader.css">
<!-- css -->
<link rel="stylesheet" href="css/style.css">
<title>iChatGPT</title>
</head>
<body>
<div class="container messages">
<!-- Chat messages will be added here -->
</div>
<form class="chat-form" id="chat-form">
<input type="text" class="chat-input" id="chat-input" placeholder="Ask me...">
<button type="submit" class="chat-send" id="chat-send">
<img src="send-icon.png" width="20px" height="20px" alt="Send" id="send-img">
</button>
<div class="loader"></div>
</form>
<!-- javascript -->
<script src="main.js"></script>
</body>
</html>
Let’s go over what each part of the code does:
- The
div
element with a class ofcontainer messages
will hold the chat messages. The messages from the user and responses from the bot - The
form
element with a class ofchat-form
and an ID ofchat-form
will be used to submit the user's chat message. We will later apply css to fix and position it at the bottom of the page. - The
input
element with a type oftext
, a class ofchat-input
, and an ID ofchat-input
is where the user will type their chat message. - The
div
element with a class ofloader
will be used to display a loading animation when the chat message is being sent. - Finally, the
script
tag includes a JavaScript file calledmain.js
that will contain the code for the chat interface.
That’s it for the HTML code! Now let’s move on to the CSS code.
Step 2: The CSS
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
background-color: #f2f2f2;
font-family: Arial, sans-serif;
font-size: 16px;
line-height: 1.5;
height: 100vh;
display: flex;
flex-direction: column;
}
.container {
flex: 1;
padding: 20px;
padding-bottom: 70px !important;
display: flex;
flex-direction: column;
overflow-y: scroll;
scroll-behavior: smooth;
}
.message {
max-width: 80%;
margin: 10px;
padding: 10px;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
}
.user-message {
align-self: flex-end;
background-color: #2D81D8;
color: white;
}
.bot-message {
align-self: flex-start;
background-color: #f2f2f2;
}
.chat-form {
display: flex;
position: fixed;
bottom: 0;
left: 0;
right: 0;
padding: 10px;
background-color: white;
box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.3);
z-index: 1;
}
.chat-input {
flex: 1;
border: none;
border-radius: 5px;
padding: 10px;
margin-right: 10px;
font-size: 16px;
}
.chat-send {
background-color: #2D81D8;
color: white;
border: none;
border-radius: 5px;
padding: 10px 15px;
cursor: pointer;
font-size: 16px;
}
.loader {
display: none;
margin-left: 10px;
margin-top: 10px;
border: 4px solid #f3f3f3;
border-top: 4px solid #2D81D8;
border-radius: 50%;
width: 20px;
height: 20px;
animation: spin 2s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
This is the CSS code for styling the HTML document. It sets some default styles for all elements on the page using the universal selector (*), including box-sizing, margin, and padding.
The .container
class is used to style the div
element that contains the chat messages. It sets flex properties to make it stretch to fill the available space, sets padding to create a margin around the messages, and sets overflow-y to scroll so that users can scroll through the messages. The .message, .user-message, and .bot-message classes are used to style the individual chat messages, with different background colors for messages sent by the user and messages received from the bot.
The .chat-form class is used to style the form element used to send messages. It is given a fixed position at the bottom of the page using the position property, and padding to create some space around the form elements.
Finally, the .loader class is used to style the loading animation that appears when the bot is thinking, using the border, border-radius, width, height, and animation properties. The @keyframes spin
rule defines an animation sequence that is used to rotate the .loader
element to create a spinning animation. The spin
animation is set to run infinitely using the infinite
value of the animation-iteration-count
property.
The @keyframes
rule is used to define a sequence of CSS styles to be applied to an element over time. In this case, it defines two keyframes - one at 0% and the other at 100%. The transform
property is used to rotate the .loader
element, starting at 0 degrees and ending at 360 degrees at the end of the animation sequence. This creates a spinning effect.
When the .loader
element is shown, the display
property is set to block
, which causes it to be displayed. When it is hidden, the display
property is set to none
, which causes it to be hidden.
Now, let’s add the magic with javascript.
Step 3: The Javascript
// DOM
const chatForm = document.querySelector('#chat-form');
const chatInput = document.querySelector('#chat-input');
const chatSend = document.querySelector('#chat-send');
const messageContainer = document.querySelector('.messages');
const sendImg = document.querySelector('#send-img');
const loader = document.querySelector('.loader');
// OpenAI API
const OPENAI_MODEL = 'gpt-3.5-turbo'; // gpt-3.5-turbo, gpt-3.5-turbo-0301
const OPENAI_URL = 'https://api.openai.com/v1/chat/completions';
// Input Your OpenAI API Key Here.
// You can sign up and get API Key from here
// https://platform.openai.com/account/api-keys
let apiKey = '';
const messages = []; // store previous messages to remember whole conversation
// Function to add a chat message to the container
function addMessage(message, isUser) {
const messageDiv = document.createElement('div');
messageDiv.classList.add('message');
messageDiv.classList.add(isUser ? 'user-message' : 'bot-message');
messageDiv.textContent = message;
messageContainer.appendChild(messageDiv);
// Scroll to the bottom of the chat container
messageContainer.scrollTop = messageContainer.scrollHeight;
}
// Function to handle user input
function handleUserInput(event) {
event.preventDefault();
const message = chatInput.value.trim();
if (message !== '') {
messages.push({
'role': 'user',
'content': message
});
addMessage(message, true);
chatInput.value = '';
showLoader();
// Other request body from here https://platform.openai.com/docs/api-reference/chat/create
fetch(OPENAI_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + apiKey
},
body: JSON.stringify({
'model': OPENAI_MODEL,
'messages': messages
})
})
.then(response => response.json())
.then(data => {
hideLoader();
const responseMessage = data.choices[0].message;
addMessage(responseMessage.content, false);
messages.push(responseMessage);
})
.catch(() => {
hideLoader();
addMessage('Oops! Something went wrong. Please try again later.', false);
});
}
}
// Function to show the loader icon
function showLoader() {
loader.style.display = 'inline-block';
chatSend.disabled = true;
}
// Function to hide the loader icon
function hideLoader() {
loader.style.display = 'none';
chatSend.disabled = false;
}
// Ask user to input his/her API Key
function checkAPIKey() {
if (!apiKey) apiKey = prompt('Please input OpenAI API Key.');
if (!apiKey) alert('You have not entered the API Key. The application will not work.');
}
// Add an event listener to the form
chatForm.addEventListener('submit', handleUserInput);
// check
checkAPIKey();
- The first block of code defines variables that represent different elements of the chat interface, such as the chat form, chat input, send button, message container, loader, and send image.
- The next block defines constants for the OpenAI API, including the model name and API endpoint URL. The code also defines a variable for the API key and an array to store previous messages to remember the whole conversation.
You can get a free API key here at https://platform.openai.com/account/api-keys.
- The
addMessage
function is defined to add a new message to the message container, either from the user or the bot. The function creates a new messagediv
element, adds the appropriate CSS class based on the sender, and appends the message to the message container. The function also scrolls the message container to the bottom to show the latest messages. - The
handleUserInput
function is defined to handle user input when the user sends a message. The function first prevents the default behavior of the form submission. If the input is not empty, the function pushes the message to themessages
array, adds the message to the message container with theaddMessage
function, clears the input field, shows the loader, and sends a request to the OpenAI API to get a response. The request body includes the model name and the previous messages stored in themessages
array.
we store all the messages from the users and bots so that model could understand the context and previous conversation. As you can see in the screenshots, we just say — “how about in Japanese?”, “Chinese” and the bot know exactly what to do based on its previous conversation.
- If the request is successful, the function hides the loader, retrieves the response message from the API response, adds the message to the message container with the
addMessage
function, and pushes the response message to themessages
array. - The
showLoader
andhideLoader
functions are defined to show and hide the loader icon, respectively. The functions change thedisplay
CSS property of the loader and disable or enable the send button. - The
checkAPIKey
function is defined to prompt the user to input their OpenAI API key if it's not already defined. If the user does not input the API key, the function shows an alert message.
It is all done now. If you put them together, you would be able to run this on a browser. All the source code is available here https://github.com/monaca-samples/iChatGPT.
If you want to make it as mobile application, you can sign up a free account with Monaca and import this project. You can then run it on both android and iphone devices in no time.
Conclusion
In this article, we have learned how to use OpenAI to develop a simple chatbot web/mobile application. This is just a simple introduction and a small part of what OpenAI can offer. You can read more about the services more here.
Happy Coding.