ChatGPT
is a sophisticated and highly useful chatbot recently released by OpenAI. While
it can be used as a chatbot on the OpenAI website, the company has also
released an API that developers can use to build similar chatbots.
Chatbots are one of the most loved examples of how AI has changed the way we interact with technology and perceive newer technologies. Everyone is continually investigating and developing chatbots that can process natural language conversations and provide appropriate responses to consumers and website visitors.
This post will be useful if you want to learn
what chatGPT is and how to use OpenAI's API and NodeJS together.
Let's start with understanding what chatGPT is.
What is OpenAI’s ChatGPT?
ChatGPT is a large language model developed by OpenAI - a well-known AI research organization that has already delivered some extremely unique AI-driven products. The company is a pioneer in AI research and often comes with innovative AI use cases.
The latest model, ChatGPT is constructed and trained on huge amounts of unstructured and structured data using the unsupervised learning technique and generalized pre-trained transformers. The primary purpose of this research and development is to produce a chatbot that can better understand and serve natural language inquiries from any human.
It is constantly learning and fine-tuning its reactions based on its interactions with humans. The model can do many operations, including understanding and responding to user queries, translating the content into multiple languages, and even helping in summarizing vast amounts of textual information precisely.
OpenAI also provides an API to access this model programmatically so that anyone can build their own chatbot.
So, let’s have a look at how you can build a
simple chatbot with NodeJS and OpenAI’s ChatGPT API.
Building
a Simple Chatbot with NodeJS and ChatGPT API
The first step is to have NodeJS on your system and install two additional NPM libraries to work on this hands-on project. If NodeJS is already installed, create a new folder and launch your command prompt from the new folder.
Once your command prompt opens from the new folder, use the command “npm init –y” to start a new Node project. Run the below-given command after creating the project to download and install the two extra npm packages that we discussed above.
npm install openai readline-sync
The command here will help you install the OpenAI NodeJS library from the npm repository. Meanwhile, it will also install the readline-sync package, which is useful for receiving input from users via the command line interface.
Before going forward, it is mandatory to have an API key linked to your OpenAI account. This API key will help you connect with the ChatGPT model through your code and it will also verify your authenticity.
To get the API key, head over to OpenAI's website, log in with your account credentials, and then create an API key from the dashboard. Once you have the API key, begin the app's implementation.
1.
Starting with the Imports
const {
Configuration, OpenAIApi } = require("openai");
const readlineSync = require("readline-sync");
This code block will help you import both the libraries that you just installed. These libraries will be the base of your project and we will develop the chatbot using these two packages.
2.
Creating an Async Wrapper
(async ()
=> {
// entire application code goes here
})();
Async programming is used heavily in applications that interact with APIs so that execution never stops. The async wrapper we have here ensures that users can send multiple requests, and they will be processed in the queue one after another. Any code inside this async wrapper will execute asynchronously and we will include all of the code that makes the chatbot inside this.
3.
Creating the Configuration and API Setup
const
configuration = new Configuration({
apiKey: OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
To access OpenAI’s servers you should have a valid API key to connect with them. Only if you have a valid API key, you can use the AI model through code. This is what the above code does. It supplies the API key for the connection and establishes a new connection to OpenAI servers.
4.
Setting Chat History
const history = [];
We must first establish an empty array to record the chat history. ChatGPT APIs scan over prior talks to comprehend the discussion and construct a reply that fits the setting. Therefore, storing the chat history is critical. On each call, you'll also need to give this history to the API.
5.
Creating the Chat Loop
while(true){
//all chat
code goes here
}
The conversation loop is a critical component of our project. This loop will continue to execute until it receives a trigger to exit the chatbot. It is set to true since the chat must continue, and it will return false only if the user expresses a desire not to continue the discussion. The conversation loop will be terminated if such input is received.
6.
Getting User Input
const user_input = readlineSync.question("Your input: ");
User input is vital in chatbots, and the above piece of code obtains user input to transmit to the chatbot. It also uses the readline-sync module to obtain command-line input from the user.
7.
Creating Chat History
const
messages = [];
for (const
[input_text, completion_text] of history) {
messages.push({ role: "user",
content: input_text });
messages.push({ role: "assistant",
content: completion_text });
}
messages.push({ role: "user", content: user_input });
The preceding code assists in the creation of a conversation history that can be supplied to the API as a context. The API can comprehend the conversation context and then respond appropriately.
8.
Initializing AI Model
const
completion = await openai.createChatCompletion({
model: "gpt-3.5-turbo",
messages: messages,
});
This code is used to open the chat completion connection and choose a model. You set the model for answers here and transmit the previous messages as a context parameter to the request.
9.
Getting Model’s Response and Adding to History
const
completion_text = completion.data.choices[0].message.content;
history.push([user_input, completion_text]);
You must extract the model's answer from the completion path at data.options[0].message.content. Once the model returns an answer, you need to add the user input and the model’s response to the history array.
10. Ask to Continue the Conversation
Here you can ask whether the user wants to continue the conversation or not. Based on the user input, the chatbot can be terminated or continued. Below is the code for that.
const
user_input_again = readlineSync.question(
"\nWould you like to continue the
conversation? (Y/N)"
);
if
(user_input_again.toUpperCase() === "N") {
return;
} else if
(user_input_again.toUpperCase() !== "Y") {
console.log("Invalid input. Please enter
'Y' or 'N'.");
return;
}
Your NodeJS chatbot is now ready, and you can launch it with the below code.
node <your-file-name>.js
Finally, we have developed a small NodeJS project that has demonstrated OpenAI API and NodeJS possibilities when combined. You can create a user interface using any JS frontend framework and make the chatbot even better.
If you have any doubt related this post, let me know