Today, the most talked-about AI tool on the market is ChatGPT. With the onset of AI tools, they have primarily focused on making complex processes easier and more efficient. And ChatGPT does the same. From brainstorming to summarising to coding, if you understand the core of ChatGPT, you have a very powerful and intelligent companion for your tasks.
Imagine combining it with the most popular technology of today, Node.js! Node.js is a well-known scalable runtime environment based on Google’s v8 engine with several impressive features for superfast API calls. So, if you integrate the ChatGPT API in Node.js, you can build outstanding, robust applications and websites.
So, let’s understand ChatGPT more and learn to integrate it into your Node.js project.
What is ChatGPT?
ChatGPT, an easy name for Chat Generative Pre-trained Transformer, is a powerful tool based on machine learning and Natural Language Processing (NLP). Developed by OpenAI, ChatGPT is a self-learning AI chatbot that responds to human language queries based on the collected database from the internet. From generating smart, relevant content and graphics to solving problems, it has opened many possibilities for what a digital solution can do.
Benefits
Notably, integrating ChatGPT into your web products has many advantages, especially if it is a Node .js-based solution. As you enhance your NodeJS applications with ChatGPT functionalities, some of the many benefits it brings are:
- Get instant, relevant responses to your specific prompts for your tasks.
- Create user-centric, SEO-friendly content and language-driven apps.
- It remarkably elevates your processes, optimises performance, and builds an impactful user experience.
- Gives you a competitive edge in your business with hyper-personalised solutions.
- Quick error detection, text generation and analysis, and activating security measures.
Convinced of the power duo of ChatGPT and Node.js, let’s learn to combine the two. Starting from scratch, we will go bit-by-bit through the coding journey in this article to integrate this AI tool into your Node.js project.
How to Integrate OpenAI’s ChatGPT into Node.js
First, you need basic knowledge of Nodejs and its NPM (Node Package Manager), along with acquiring the ChatGPT API key from OpenAI, to integrate and implement them. Let’s look at them step-by-step.
- First step: Start with creating a Node.js application.
To start, you will need to create a directory for the project, for instance, ChatGPT-API-Nodejs. You can do this either by using the GUI or by running this command.
mkdir chatgpt-api-nodejs
Now, you can change the directory to a newly created folder named Node.js Project with default settings.
cd chatgpt-api-nodejs
To start the project, create the package.json file to track your project details. Run the following command:
npm init -y
It is time to move on to the next step.
- Second step: Retrieve the OpenAI API Key.
Now, you need to generate API keys. For that, you must visit OpenAI and log into the account (sign in if you are new).
- Once logged in, you will find three options: ChatGPT, API, and Dall-e. Click on the API option.
- On the right-hand corner of the page, you will see the option to view API keys.
- Now, click on the ‘Create new secret key’ option. It will open a box asking you for the name of the key. You can create a secret key with this option.
- After which, a dialog box will flash on the screen with your secret key. You can copy this and then click on the save option. After you have obtained your secret key, let’s go back to our main project.
Install the necessary library for integrating an API into your Node.js application and a readline-sync library that helps read the user inputs from the command line.
npm i openai readline-sync
Further, add the openai npm, express, and dotenv packages to your project. You can use the command:
npm i dotenv
Also, you can create a new environment conducive to strengthening your API key. In the file, you can create an open API key and replace it with your generated key.
OPENAI_SECRET_KEY=”YOUR OPEN AI API KEY”
- Third Step: Implementing the Nodejs function.
Create a JavaScript file and paste this code:
const { Configuration, OpenAIApi } = require(“openai”);
const readlineSync = require(“readline-sync”);
require(“dotenv”).config();
let APIcall = async () => {
const newConfig = new Configuration({
apiKey: process.env.OPENAI_SECRET_KEY
});
const openai = new OpenAIApi(newConfig);
const chatHistory = [];
do {
const user_input = readlineSync.question(“Enter your input: “);
const messageList = chatHistory.map(([input_text, completion_text]) => ({
role: “user” === input_text ? “ChatGPT” : “user”,
content: input_text
}));
messageList.push({ role: “user”, content: user_input });
try {
const GPTOutput = await openai.createChatCompletion({
model: “gpt-3.5-turbo”,
messages: messageList,
});
const output_text = GPTOutput.data.choices[0].message.content;
console.log(output_text);
chatHistory.push([user_input, output_text]);
} catch (err) {
if (err.response) {
console.log(err.response.status);
console.log(err.response.data);
} else {
console.log(err.message);
}
}
} while (readlineSync.question(“\nYou Want more Results? (Y/N)”).toUpperCase() === “Y”);
};
APIcall();
This integrates the tool into your app. Now, you can run the app with this command:
node index.js
This code uses the input prompt through the command line and prints the response generated by ChatGPT. It also asks if you want to continue the conversation, then type Y, or to terminate it, type N.
How to use ChatGPT API in Node.js?
- Start by importing dependencies.
Use the code:
const { Configuration, OpenAIApi } = require(“openai”);
const readlineSync = require(“readline-sync”);
require(“dotenv”).config();
In the code’s first line, the OpenAI API and configuration classes form the OpenAPI package to connect to the OpenAI API. Further, the readline-sync package uses the input from the command prompt. The dotenv package helps load the environment variables from the ENV file.
- Create an Asynchronous Function.
let APIcall = async () => {
//code here
};
- How to configure and use the API setup?
const newConfig = new Configuration({
apiKey: process.env.OPENAI_SECRET_KEY
});
const openai = new OpenAIApi(newConfig);
The process.env.OPENAI_SECRET_KEY will retrieve the API key from the environment variable inside an ENV file.
- How to create a chat history?
To create a chat history, you can use this command:
const chatHistory = [];
With this command, you can create an empty array that stores the chat history. It will further help your AI model generate responses.
- How to create a chat loop?
You can use this command to create a chat loop.
do{
//code
}while (readlineSync.question(“\nYou Want more Results? (Y/N)”).toUpperCase() === “Y”);
Now, you can create a do-while loop that continuously takes user input and creates a response untill further instruction. Besides, every time it completes a single iteration, it will ask the users whether they want to continue the conversation.
- How to get user input?
const user_input = readlineSync.question(“Enter your input: “);
With this line prompt, you can store the user prompt in user_input.
- How to use the context of chat history?
the
const messageList = chatHistory.map(([input_text, completion_text]) => ({
role: “user” === input_text ? “ChatGPT” : “user”,
content: input_text
}));
messageList.push({ role: “user”, content: user_input });
With this command, you can create a message list in the format of the OpenAI ChatGPT API using the map method. You can add the current user input to the last array.
- Using the AI model
Use the command:
const GPTOutput = await openai.createChatCompletion({
model: “gpt-3.5-turbo”,
messages: messageList,
});
With this, you can generate a response from the OpenAI API. Also, you can specify the ChatGPT model to generate a response.
- Response with an AI model
By using this command,
const output_text = GPTOutput.data.choices[0].message.content;
console.log(output_text);
The object response generated will be extracted and stored in the variable.
- How to update the chat history?
With the command
chatHistory.push([user_input, output_text]);
You can store the user input and model response.
- How to handle an error?
catch (err) {
if (err.response) {
console.log(err.response.status);
console.log(err.response.data);
} else {
console.log(err.message);
}
}
The catch block executes when an error occurs and prints the message on the console.
- Calling the Asynchronous function.
APIcall(); – will call the Asynchronous call function.
Conclusion
Constantly evolving with time, Open AI’s ChatGPT is a game-changer that you can leverage with your dynamic Node.js projects. With this detailed guide on how to use it in Node.js, you can now create your own chatbot to deliver real-time tailored experiences to your end-users. It forges an assured product with next-gen features for keeping your business future-ready.