The Wayback Machine - https://web.archive.org/web/20240807072011/https://www.geeksforgeeks.org/how-to-use-chatgpt-api-in-nodejs/
Open In App

How to Use ChatGPT API in NodeJS?

Last Updated : 25 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

ChatGPT is a very powerful chatbot by OpenAI that uses Natural Language Processing to interact like humans. It has become very popular among developers and is being widely used for some of its state-of-the-art features like understanding and interpreting code and even generating code based on textual requirements. OpenAI has not only provided its functionality as a chatbot on the website but has also provided an API to help integrate ChatGPT into our applications and projects using which we can make an HTTP request and utilize the response appropriately.

Use ChatGPT API in Nodejs

In this article, we will have a look at the step-by-step procedure to integrate ChatGPT API in the Node.js project.

Using ChatGPT in Node.js Application

Adding ChatGPT functionalities to our large-scale NodeJS Application will make that more efficient for the users. So in this article, we will see step by step implementation of where to retrieve the API key, and how to create a NodeJS application that uses OpenAI API, that will work similarly to ChatGPT, and you can make conversation with ChatGPT using that application. Here are the complete steps for using ChatGPT in NodeJS Application.

1. Creating a Node.js Application

First of all, we will create a directory for the project say, chatgpt-api-nodejs, either using GUI or by pasting the below command in the terminal at the desired location in our machine:

mkdir chatgpt-api-nodejs

Now, change the directory to the newly created folder:

cd chatgpt-api-nodejs

To initialize the node.js project, run the below command which creates a package.json file to keep track of project details

npm init -y

We will use axios for making HTTP requests and dotenv for managing environment variables.

npm install axios dotenv

2. Retrieving the OPENAI API Key

To use the API, we need to generate the API keys.

A. For that, go to OpenAI and either sign up or login (if you already have an account).

login

Create OpenAI account

B. Then click on the API option

fdgh

Creating ChatGPT API key


C. On the left corner you will see API keys, click on it and it will open API keys section. Click on ‘Create new secret key, to crate a new one.

iujhgfx

Create new Secret Keys

D. Click on the ‘Create new secret key’ button. It will open up a dialog box asking for the name of the key which is optional. After you are done, click ‘Create secret key’.

SecretKeyName

Create new Secret Keys

E. A dialog box will appear displaying your secret key/API key. Copy it and ‘done’. Save the key safely and do not share it with anyone.

secretKey

Create new Secret Keys

Create a new file to create an environment variable for storing the API key

touch .env

In the file, create a variable OPENAI_API_KEY and replace "YOUR OPEN AI API KEY" with your API key (keeping the quotes)

OPENAI_API_KEY="YOUR OPEN AI API KEY"

3. Implementing NodeJS Application

Create a javascript file say, index.js, and paste the below code inside it.

JavaScript
//index.js

const axios = require("axios");
const dotenv = require("dotenv");
const readline = require("readline");

// Load environment variables from .env file
dotenv.config();

// OpenAI API key
const apiKey = process.env.OPENAI_API_KEY;

// Function to call the ChatGPT API
async function callChatGPT(prompt) {
    const url = "https://api.openai.com/v1/chat/completions";

    const headers = {
        "Content-Type": "application/json",
        Authorization: `Bearer ${apiKey}`,
    };

    const data = {
        model: "gpt-3.5-turbo",
        messages: [
            { role: "system", content: "You are a helpful assistant." },
            { role: "user", content: prompt },
        ],
    };

    try {
        const response = await axios.post(url, data, { headers });
        const result = response.data.choices[0].message.content;
        return result;
    } catch (error) {
        console.error(
            "Error calling ChatGPT API:",
            error.response ? error.response.data : error.message
        );
        throw error;
    }
}

// Create an interface for user input
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});

// Prompt the user for input
rl.question("Enter your input: ", async (prompt) => {
    try {
        const response = await callChatGPT(prompt);
        console.log("ChatGPT response:", response);
    } catch (error) {
        console.error("Error:", error.message);
    } finally {
        rl.close();
    }
});

4. Run the Application

To run the app, run the below command in terminal

node index.js

The above code takes the input prompt through the command line and prints the response generated by the ChatGPT model.

Output

output

How to Use ChatGPT API in NodeJS? – FAQs

Is ChatGPT API free?

Yes, but it has some limitations after that we have to Pay for use of API. To use the API, one needs to create an account on OpenAI which can be created for free.

What are the rate limits for ChatGPT API?

As per the official OpenAI documentation, the number of requests per minute is limited to 3 RPM (for the free tier) and tokens per minute to 40,000 TPM.

Can ChatGPT API be brought to commercial use?

Yes, ChatGPT API can be integrated into the projects for commercial use. For that, one might need to purchase the pay-as-you-go plan to get an increased rate limit for API calls. ChatGPT API is well designed keeping in mind the scalability as the application grows.



Similar Reads

How to Use ChatGPT API in Python?
ChatGPT and its inevitable applications. Day by Day everything around us seems to be getting automated by several AI models using different AI and Machine learning techniques and Chatbot with Python, there are numerous uses of Chat GPT and one of its useful applications we will be discussing today. So, before moving to its application let's know a
5 min read
ChatGPT Tips & Tricks: 5 Secret Tips That Can Boost Your ChatGPT Game to God Mode
Are you one of those folks who've tried using ChatGPT but ended up feeling a bit frustrated? Well, let us tell you, you're not alone in this sad situation. Whether you're a student or a tech whiz working in IT, ChatGPT has been a helpful companion for everyone! But the thing is, not everyone knows how to make the most out of it. But fear not! This
7 min read
How to Build a ChatGPT Like App in Android using OpenAI API?
Chat GPT is nowadays one of the famous AI tools which are like a chatbot. This chatbot answers all the queries which are sent to it. In this article, we will be building a simple ChatGPT-like android application by integrating the OpenAI API(ChatGPT) where we can ask any question and get an appropriate answer. We have created a sample application a
5 min read
What is ChatGPT API?
ChatGPT is a groundbreaking Natural Language Processing (NLP) tool developed by OpenAI. ChatGPT has advanced significantly since its original release in late 2022, resulting in the creation of an API that allows developers to integrate state-of-the-art model capabilities into their applications. Through this article, we will go through the chatGPT
8 min read
How to Create a ChatBot Application using ChatGPT API in Flutter?
A ChatBot is a computer program that uses Artificial Intelligence (AI) and Natural Language Processing (NLP) to understand customers' questions and give responses to them simulating human behavior. Building our own ChatBot from scratch requires us to train the Machine Learning (ML) model with rigorous amounts of text-based data, providing it with d
11 min read
How To Use MongoDB Aggregation Framework in NodeJS?
The MongoDB aggregation framework in Node.js performs data aggregation operations such as filtering, grouping and transforming documents within a collection. This is achieved using aggregation pipelines. An aggregation pipeline consists of multiple stages, with an output of using stage being passed to the next stage as input. This allows to process
4 min read
How to Use math.js in NodeJS And Browser?
Math.js can be used to perform complex mathematical computations in both NodeJS and browser environments. It is a powerful library that supports a wide range of mathematical functions, including algebra, calculus, and statistical operations. By integrating math.js into your projects, you can handle mathematical tasks efficiently, whether you're wor
3 min read
10 Best ChatGPT Plugins You Should Use
ChatGPT is a Natural Language Processing tool released by OpenAI in 2023. Almost like a human, this tool can interact with the person by its ability to answer follow-up questions, admit mistakes, correct responses challenge incorrect premises, reject inappropriate requests, and much more. With these abilities, ChatGPT has become a very powerful and
9 min read
How to Use ChatGPT with Siri on iPhone
In today's tech-savvy world, we're constantly amazed by the wonders of artificial intelligence (AI). And guess what? Two incredible AI innovations, ChatGPT and Siri, have joined forces to revolutionize your iPhone experience! ChatGPT is your go-to buddy for generating human-like text and engaging conversations, while Siri is the voice assistant tha
7 min read
How to Use ChatGPT to Analyze Data?
In an age where everything is online, increased data in all formats is almost obvious. This data forms the basis of most of the marketing strategies and further product design and assembly. It is almost impossible to work without data today. Right from social media to online shopping, everything is data-driven, and this data drive the business ahea
9 min read
three90RightbarBannerImg