How To Implement ChatGPT In NodeJS

Introduction

In this article, I am going to explain how to implement ChatGPT into a NodeJS application. First, I am going to explain chatGPT. ChatGPT is an Artificial Intelligence chatbot. We can use it as a search engine also. For example, if we want a simple nodejs program we can ask a question after that it will accumulate and give an answer. Another example is if want to learn about stacks here also it will accumulate and give answers. Below I mentioned the example screenshot. So here I will explain how can we use ChatGPT in our web application.

Implementing ChatGPT in NodeJS

Requirements

  • VS code
  • Nodejs v18.9.0(https://nodejs.org/en/download/)
  • npm openai package (https://www.npmjs.com/package/openai)

Nodejs

Node.js is an open-source server-side runtime environment built on Chrome’s V8 JavaScript engine. Node.js is a single-threaded application. It is a non-blocking I/O. It is an event-driven programming language as per the Nodejs document.

Implementing ChatGPT in NodeJS

Step 1

First, we have to create nodejs server application using express framework. So here I am going to nodejs project 

npm init

Then it will create package.json file. After that, we should create app.js file for creating the server. Below I mention a code snippet for creating nodejs server.

var express = require("express");
var bodyParser = require("body-parser");
var http = require("http");
var app = express();
var cors = require('cors')
var server = http.createServer(app);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());
app.use(function(err, req, res, next) {
    res.header("Access-Control-Allow-Origin", "https://www.sandbox.paypal.com");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next(err);
    });
server.listen(4000, function () {
    console.log('Example app listening on port 4000!');
});

Next, we will create controllers and routes. Here I am creating a controller file chatController.js

const methods = {};

methods.getAnswer = (req) => {
    console.log(req.body);
    return new Promise(async(resolve, reject) => { 
      resolve(success);
    })
}
module.exports = methods;

After that, I will create a route file for mapping to functionality to Rest API chatRoute.js

var express = require("express");
var router = express.Router();
var chatController = require("./chatController");
router.post("/getAnswer", (req, res) => {
    console.log("req.body",req.body);
    chatController.getAnswer(req).then(data => res.json(data)).catch(err => res.send(err))
});
module.exports = router;

 Then I have to map my routes file to the main file in app.js

//import routes file
var chatRoute = require('./chatRoute');

app.use("/api",chatRoute);

Step 2

Now  here we are going to add openai npm package for accessing OpenAI chatGPT

The OpenAI Node.js library provides convenient access to the OpenAI API from Node.js applications. For more details go through the below link

https://www.npmjs.com/package/openai

Now we will run the npm command

npm install openai

After that we have to add openai library to our controller file

const { Configuration, OpenAIApi } = require("openai");

Step 3

We have to go to https://openai.com/ site and we should register and login and go to our profile and click on View API Key.

Implementing ChatGPT in NodeJS

And we have to create new API Keys.

Implementing ChatGPT in NodeJS

Then we have to set the configuration for OpenAI package and set the API key.

const configuration = new Configuration({
  apiKey: "API_KEY",
});

const openai = new OpenAIApi(configuration);

Step 4

After that, we will write code for requesting to OpenAI module and we will put the code into the controller file.

  openai.createCompletion({
            model: "text-davinci-001",
            prompt: req.body.question,
          }).then((data)=>{
console.log(data)
          });

Code snippet for chatController.js

const methods = {};
const { Configuration, OpenAIApi } = require("openai");

const configuration = new Configuration({
  apiKey: "sk-API_KEYS",
});
const openai = new OpenAIApi(configuration);
methods.getAnswer = (req) => {
    return new Promise(async(resolve, reject) => { 
       try{
        openai.createCompletion({
            model: "text-davinci-001",
            prompt: req.body.question,
          }).then((data)=>{
            resolve({status:200,message:data.data.choices[0].text});

          });
       
       }catch(e){
          reject(e);
       }
    })
}
module.exports = methods;

Now we will hit the Rest API for getting answers from OpenAI package (chatGPT). While hitting RESTAPI we should pass the question

http://localhost:4000/api/getAnswer
{
    "question":"how are you?"
}

Output

Implementing ChatGPT in NodeJS