How to Use OpenAI's ChatGPT API in Node.js

Written by Sebastian on March 12, 2023 · 7 min read

tutorial

Artificial Intelligence (AI) has been revolutionizing the way we interact with technology, and chatbots are one of the most prominent examples of this trend. With the increasing need for chatbots that can understand natural language and provide useful responses, OpenAI’s ChatGPT API has become a popular choice among developers. In this blog post, we will explore how to use OpenAI’s ChatGPT API in Node.js, a popular backend language used for building web applications.

We will go through the process step-by-step, starting from setting up the API credentials, to building a chatbot that can understand and respond to user queries in natural language. Whether you are a seasoned developer or just starting with Node.js and AI, this blog post will provide you with a comprehensive guide to getting started with OpenAI’s ChatGPT API.

Creating A New Node.js Project

Let’s start by creating a new project folder:

$ mkdir node-chatgpt-api
$ cd node-chatgpt-api

Inside this new project folder create a new package.json file by using the npm command in the following way:

$ npm init -y

Next we need to add two packages:

$ npm i openai readline-sync

Finally let’s also add the dotenv package to the project:

$ npm i dotenv --save

By using the dotenv package we’ll be able to manage environment variables in a .env file in our project.

Retrieve The OpenAI API Key

In order to be able to make use of OpenAI’s API from within a Node.js application we need to retrieve an API key first from the OpenAI dashboard.

To retrieve your OpenAI API key you need to create a user account at https://openai.com/ and access the API Keys section in the OpenAI dashboard to create a new API key.

Image

This key is secret and must not shared with anybody else. We’ll need to use this key later on when implementing the Node.js program to access OpenAI`s API.

Let’s assign this API key to an environment variable in our Node.js application. Create a new file:

touch .env

Inside that file create the OPENAI_API_KEY variable and assign the value of your key:

OPENAI_API_KEY="YOUR OPEN AI API KEY"

Implement The Node.js Application

Create a new file node-chatgpt-api.js and insert the following code:

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

(async () => {
  const configuration = new Configuration({
    apiKey: process.env.OPENAI_API_KEY,
  });
  const openai = new OpenAIApi(configuration);

  const history = [];

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

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

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

      const completion_text = completion.data.choices[0].message.content;
      console.log(completion_text);

      history.push([user_input, completion_text]);

      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;
      }
    } catch (error) {
      if (error.response) {
        console.log(error.response.status);
        console.log(error.response.data);
      } else {
        console.log(error.message);
      }
    }
  }
})();

This Node.js code defines an interactive chatbot that uses the OpenAI ChatgPT API (gpt-3.5-turbo model) to generate responses to user input. Here’s a detailed breakdown of what each part of the code does:

1. Importing Dependencies:

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

2. Asynchronous Function:

(async () => {
  // Code here
})();

3. Setting up Configuration and API:

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

4. Chat History:

const history = [];

5. Chat Loop:

while (true) {
  // Code here
}

6. User Input:

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

7. Chat History for Context:

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

8. AI Model:

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

9. Response from AI Model:

const completion_text = completion.data.choices[0].message.content;
console.log(completion_text);

10. Chat History Update:

history.push([user_input, completion_text]);

The current user_input and the response generated by the AI model (completion_text) are added to the end of the history array.

11. Should Conversation be continued?

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

12. Error Handling:

} catch (error) {
  if (error.response) {
    console.log(error.response.status);
    console.log(error.response.data);
  } else {
    console.log(error.message);
  }
}

Run The Application

In order to start the Node.js application you need to execute the following command:

$ node node-chatgpt-api.js

You’re being asked for your first input:

Image

Start by entering your first question and hit return:

Image

After every response you’re being asked if the conversation should be continued. If you want to continue you need to input “Y”. You’re then being asked to provide the next input.

As the gpt-3.5-turbo model is able to also take the history of the conversation into account you can ask subsequent questions which are based on the context of the conversation which has taken place so far.

Image

Conclusion

OpenAI’s ChatGPT API is an incredibly powerful tool for building intelligent chatbots that can understand and respond to natural language. With the help of Node.js, developers can easily integrate this API into their web applications and provide users with an exceptional experience. In this blog post, we have walked through the process of setting up the API credentials, creating a chatbot, and testing it out in real-time. By following these steps, you can create your own chatbot that can interact with users and provide them with personalized responses. With the continuous development of AI, we can only expect chatbots to become even more sophisticated and effective in the years to come. By learning how to use OpenAI’s ChatGPT API in Node.js, you are setting yourself up for success in the future of AI-powered chatbots.