whatsapp

How To Use OpenAI’s ChatGPT API In NodeJS

Open AI ChatGPT API In NodeJS

Our ancestors never would have thought that we could talk to machines one day but chatbots made that happen. They have transformed the way we engage with technology and are one of the most finest examples of how far artificial intelligence has come.

With the growing need for chatbots that can comprehend natural language and deliver relevant replies to consumers, people are constantly exploring and improving current chatbots. One such chatbot that released recently is ChatGPT by OpenAI. While it can be used as a chatbot on the OpenAI website, there is also an API that developers can use to construct chatbots similar to this.

To understand how you can use OpenAI’s ChatGPT API in NodeJS, it is important to know what is ChatGPT and NodeJS. So, let’s first start with understanding what ChatGPT API In NodeJS .

If you already know about it, feel free to skip to the section building a chatbot in NodeJS with ChatGPT API.

What is OpenAI’s ChatGPT?

ChatGPT is a large language model created by the well-known AI research firm OpenAI. It was created and trained using the unsupervised learning approach on massive volumes of unstructured and structured data. The major goal of this research and development is to create a chatbot that can better comprehend and serve consumers’ natural language questions.

It is continuously learning from the interactions with people and fine-tuning its responses. It can perform a wide variety of tasks like understanding and answering users’ requests, translating them into different languages, and even summarizing large pieces of text.

While ChatGPT is accessible through OpenAI’s website, there is another way to access it through API. The company provides an API to access it programmatically and build your chatbots.

ChatGPT is an important artificial intelligence software used in building the chatbot. Having known about it, now let us understand what NodeJS is.

What is NodeJS?

NodeJS enables developers to write server-side code using JavaScript. This framework is based on the JavaScript engine Chrome’s V8, which was written in C++ for superfast execution. It also features an event-driven and non-blocking IO model that is suitable for real-time and data-intensive applications.

NodeJS is used by some of the biggest companies in the technology space. So there has to be something special about it, right? The next section is all about understanding why NodeJS is widely used.

Why Use NodeJS?

1. Superfast Execution

Due to its Chrome JavaScript V8 engine, which is designed in C++, Node.js is exceptionally fast. Also, it supports a non-blocking IO mechanism, which prevents applications from stopping the main thread. Despite being a single-threaded language, it easily outperforms multi-threaded languages in terms of performance and execution speed.

2. Real-time Performance

The non-blocking IO paradigm is a distinct NodeJS feature in which the main thread is never blocked for any request. If a request requires access to another resource, it can be sidelined and executed independently while the next request in the queue is picked up and provided. In this manner, regardless of how many requests are sent to the NodeJS server, the server will never lag and will continue to fulfill requests in real time for excellent performance.

3. Memory Efficient

NodeJS uses very less memory and responds to queries faster, making it a memory-efficient programming language. Because of their fast execution and efficient code, NodeJS apps do not require high-spec servers or memory devices.

Moreover, NodeJS is equipped with cutting-edge memory management algorithms and is capable of releasing resources as soon as the job is over. It ensures the data that is no longer required is not held in the main memory.

4. Single Language in Frontend and Backend

When you choose NodeJS for backend development, you get the benefit of using JavaScript at the front-end and backend of your projects. With the same language across your project, data transfers between the front-end and the backend become easier. And anyone with basic knowledge of APIs can build or maintain simple APIs in your projects.

You can hire node js programmers if you are planning to use node language across your project. The developers can assist you in using node with both front-end and backend simultaneously. With this, your team size can also decrease, and you can save significantly on costs.

5. Node Package Manager

NPM is one of the world’s largest code repositories, with millions of libraries and modules that can be utilized directly in IoT projects. One can use free to utilize ready-made libraries in their apps instead of building everything from scratch.

These libraries are routinely used by developers, and maintained by top developers and open-source contributors all around the world. Moreover, feature updates are released frequently for most libraries that make work easier and more exciting for everyone involved in the app development.

Now that you know about ChatGPT and NodeJS, it is time to find out how you can build a chatbot by leveraging the ChatGPT API.

Building a Chatbot in NodeJS with ChatGPT API

To get started with this, you’ll need NodeJS to be installed on your system and two more NPM libraries. If you already have NodeJS installed on your system, then:

  • Create a new folder and open your command prompt from that folder.
  • From your command prompt, run the npm init -y command to initiate a new node project.
  • After creating the project, run the command npm install openai readline-sync to add two npm packages. It will install the readline-sync package, which helps get inputs from users through the command line interface.
  • You will need to have an API key for your OpenAI account. To get the key, head over to OpenAI’s page, log in with your credentials, and create an API key from the dashboard.

Now let’s start the app’s implementation.

1. Starting with the Imports

const { Configuration, OpenAIApi } = require("openai");
const readlineSync = require("readline-sync");

The above two lines will import openai and readline-sync packages in your main file. With these two packages, you can create a chatbot. They are the essential building blocks of your application.

2. Creating an Async Wrapper

(async () => {
  // entire application code goes here
})();

It is necessary to create an async wrapper function for this application to have the best performance. Every code that makes your chatbot will stay inside this code block.

3. Creating the Configuration and API Setup

const configuration = new Configuration({
apiKey: OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

To create a connection to OpenAI’s servers, you need to create an API connection and pass in the configuration object to the OpenAI package. The above code does exactly that. It specifies the API key to use for the connection and creates a new connection to OpenAI servers.

4. Setting Chat History

const history = [];

We have to create an empty array that can store the chat history. Storing the chat history is important as ChatGPT APIs skim past chats to understand the dialogue and create a reply that suits the setup. You’ll also need to pass this history to the API on each call.
Also ReadMobile App Development Process in 2023

5. Creating the Chat Loop

while(true){
//all chat code goes here
}

The chat loop keeps running till it gets a false value from somewhere. It is set to true because the chat needs to continue, and it will receive false only when the user says that he does not want to continue the chat. At such input, it will terminate the chat loop.

6. Getting User Input

const user_input = readlineSync.question("Your input: ");

User input is an essential part of chatbots, and the above line of code gets the input from the user to pass to the chatbot. It also uses the readline-sync package to get the input from the command line interface.

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 above code helps in creating a chat history that can be passed to the API as a context. The API can understand the chat context and then send the appropriate response.

8. Initializing the AI Model

const completion = await openai.createChatCompletion({
  model: "gpt-3.5-turbo",
  messages: messages,
});

This code is used in opening up the chat completion connection and selecting the model. Here you specify the model that should be used for responses, and you need to send 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]);

To get the model’s response, you need to extract it from the completion.data.choices[0].message.content path. Once you have the model’s response, you add the user input and response to the history array.

10. Ask for Conversation Continuation

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;
}

The above code asks the user whether he wants to continue the conversation or not. If the user enters N, the chat loop is terminated, and program execution stops. On the other hand, if the user inputs Y, the chatbot prompts for new input from the user to continue the chat.

Now the app is ready, and the only thing left is to run the chatbot. To run the application, write the below code in your command prompt.

node .js

Once you press enter, the chatbot will be ready for interaction. You can start interacting with it.

Final Words

You can develop a simple chatbot in NodeJS using OpenAI API. You can even develop a frontend using any frontend framework to make the chatbot even more user-friendly. Hope this helps! Tell us in the comments below if you found any difficulty in creating the chatbot.

Leave A Comment

Thank You for Choosing Us: Let's Create Magic Together!

Thank you for choosing Knotsync. The more we know about you, the better we can serve you. By sharing your information, you open the door to a world of customized experiences, tailored recommendations, and improved results. We can curate our services specifically designed to meet your unique requirements.

Fill out the form, provide the necessary details, and let us take care of the rest. We look forward to welcoming you to the Knotsync family!

Error: Contact form not found.

Thank You for Choosing Us: Let's Create Magic Together!

Thank you for choosing Knotsync. The more we know about you, the better we can serve you. By sharing your information, you open the door to a world of customized experiences, tailored recommendations, and improved results. We can curate our services specifically designed to meet your unique requirements.

Fill out the form, provide the necessary details, and let us take care of the rest. We look forward to welcoming you to the Knotsync family!

    Thank You for Choosing Us: Let's Create Magic Together!

    Thank you for choosing Knotsync. The more we know about you, the better we can serve you. By sharing your information, you open the door to a world of customized experiences, tailored recommendations, and improved results. We can curate our services specifically designed to meet your unique requirements.

    Fill out the form, provide the necessary details, and let us take care of the rest. We look forward to welcoming you to the Knotsync family!

      Thank You for Choosing Us: Let's Create Magic Together!

      Thank you for choosing Knotsync. The more we know about you, the better we can serve you. By sharing your information, you open the door to a world of customized experiences, tailored recommendations, and improved results. We can curate our services specifically designed to meet your unique requirements.

      Fill out the form, provide the necessary details, and let us take care of the rest. We look forward to welcoming you to the Knotsync family!

        Thank You for Choosing Us: Let's Create Magic Together!

        Thank you for choosing Knotsync. The more we know about you, the better we can serve you. By sharing your information, you open the door to a world of customized experiences, tailored recommendations, and improved results. We can curate our services specifically designed to meet your unique requirements.

        Fill out the form, provide the necessary details, and let us take care of the rest. We look forward to welcoming you to the Knotsync family!

          Thank You for Choosing Us: Let's Create Magic Together!

          Thank you for choosing Knotsync. The more we know about you, the better we can serve you. By sharing your information, you open the door to a world of customized experiences, tailored recommendations, and improved results. We can curate our services specifically designed to meet your unique requirements.

          Fill out the form, provide the necessary details, and let us take care of the rest. We look forward to welcoming you to the Knotsync family!

            Thank You for Choosing Us: Let's Create Magic Together!

            Thank you for choosing Knotsync. The more we know about you, the better we can serve you. By sharing your information, you open the door to a world of customized experiences, tailored recommendations, and improved results. We can curate our services specifically designed to meet your unique requirements.

            Fill out the form, provide the necessary details, and let us take care of the rest. We look forward to welcoming you to the Knotsync family!