ChatGPT Integration: The Evolution of AI Chatbots with Node and Vue

Kartik BhaleraoKartik Bhalerao
8 min read

Quick Summary:

As technology becomes increasingly integrated into our daily lives, it’s important to consider how it will shape the future. One area that’s particularly promising is Artificial Intelligence (AI), which has become even more significant with the development of advanced AI-based applications like ChatGPT. In this blog post, we have covered the basics of ChatGPT along with the ChatGPT Integration with Node and Vue.

Table of Contents

1. Introduction

2. What is ChatGPT?

3. Flow of ChatGPT Integration with Node and Vue

4. Basic Terminologies of ChatGPT Services

5. Conclusion

Introduction

With more than 100 million users as of January 2023, the ChatGPT tool is significantly growing the AI industry and is the fastest-growing consumer application to date. The market has undergone a paradigm change recently, and ChatGPT integration with Node and Vue is part of it. Before we proceed with the topic, let us first go over the integration flow in general terms using the diagram that is provided below:

flow of integration

Note: ChatGPT recommends that we not store tokens on the client side but instead use the backend to request ChatGPT APIs.

Before jumping into the in-depth flow of the ChatGPT integration with Node and Vue, let us brush up on what ChatGPT is.

What is ChatGPT?

We can refer to ChatGPT as an AI-based chatbot platform created by OpenAI which leverages the power of the advanced GPT-3 language model. GPT-3, also known as Generative Pre-Training Transformer 3, is a natural language processing model. It is trained on a vast stretch of human-generated content in a number of languages and styles.

ChatGPT uses a transformer architecture, which is a neutral network effective in processing sequential data like text. It can perform tasks like writing, summarizing, translating, asking questions, and answering texts, making it a powerful tool for building interactive chatbots. ChatGPT allows for the creation of chatbots that can give users a natural conversation experience. It is customizable, and it is easy to integrate chatbots into applications and platforms. ChatGPT enables the building of interactive chatbots that can deliver personalized user experiences.

Flow of ChatGPT Integration with Node and Vue

Now that we have been through the understanding of ChatGPT and the architecture of the ChatGPT flow of integration,. Let us move forward with the process of ChatGPT Integration with Node and Vue.

Step 1: Dummy Project Setup for ChatGPT Integration with Node.js and Vue.js

Using Node.js as Backend and Vue.js as the Frontend for the ChatGPT integration with Node.js and Vue.js project. This project entails a simple backend, for which we have configured only one endpoint with a POST request, and with the help of this endpoint, we will make a connection between the frontend and the backend with ChatGPT. Given below is an example of what the backend will look like, where we can also see the only controller that serves to the requested data.

Dummy Project Setup for ChatGPT Integration

Moving forward with the frontend, it is also basic in nature and needs only one component, that is the 'ChatBox', which will be responsible for sending message to ChatGPT and receiving the respective responses, as illustrated in the image given below:

ChatBox

Moving forward, let us jump to setting up the OpenAI package for Node.js.

Step 2: Setting Up OpenAI SDK/Package for Node.js

In your ChatGPT Integration with Node and Vue, OpenAI is a package that is responsible for managing all the communications between the User and the ChatGPT server. Also, it is the official package for ChatGPT. To explore more and dive deeper into the details, refer to the Documentation.

Next, let us install the OpenAI package in the backend using the command as given below:

Copy Text

npm install openai

Now, lets configure chatGpt.controller.js, which will communicate with ChatGPT APIs from the backend as given below:

Copy Text

// chatGpt.controller.js


const {Configuration, OpenAIApi} = require('openai')




const askToChatGpt = async function (req, res) {


   /**
    * 1. Create/configure OpenAI Instance
    */
   const openAIInstance = await _createOpenAIInstance()


   /**
    * 2. Let's talk to chatGPT
    */
   await openAIInstance.createCompletion({
       model: 'text-davinci-003',
       prompt: req.body.message,
       temperature: 0,
       max_tokens: 500
   })
   .then((response) => {
       const repliedMessage = response.data.choices[0].text
       res.send({from: 'chatGpt', data: repliedMessage})
   })
   .catch((error) => {
       //Report error
       console.log('Error ', error)
   });
}




const _createOpenAIInstance = async () => {
   const conf = await new Configuration({
       apiKey: process.env['CHATGPT_TOKEN']
   })
   return await new OpenAIApi(conf)
}


module.exports = {
   askToChatGpt
}

Note: Keep the ChatGPT token in the env of Node.js on the key of CHATGPT_TOKEN. You can create the .env file, copy and paste the content of the.env.example, and replace the token. Then, generate the token from the profile section of the ChatGPT account.

The one point to keep in mind is to put ChatGPT token in the env of Node.js on the key of CHATGPT_TOKEN. Also, you can create a .env file, copy and paste the content of the .env example and replace the token. You can generate your token from the profile section of the ChatGPT account.

Now that our main logic is ready for testing, To check it, make a request to http://localhost:3000/ask-to-chat-gp mentioning your message and you will get the appropriate response from ChatGPT.

After the main logic comes the next step, that is the frontend to make requests to the Node.js server.

Step 3: Setting Up the Frontend with Vue.js

So, for the frontend, we are using Vue.js. However, you can use any other frontend of your choice, like React, Angular, Native HTML, JavaScript, or any other. The core intent behind this frontend is to just make a request to the API endpoint that we have created above.

In this case, we have created a ChatBox.vue component under the /src/components directory, which is responsible for communicating with the backend. Here, we are using Axios for API requests. Below is the process of how we are making the request to our backend, and for the logic, you can find the said logic in the GitHub repository as mentioned.

Copy Text

methods: {
   async sendMessage (message) {
    this. messages. push ({
     from: ‘user’,
     data: message
   })
   await axios.post('http://localhost:3000/ask-to-chat-gpt', {
     message: message
   })
   .then( (response) => {
      this. messages. push response. data)
   })
  }
}

This is how our ChatBox.vue component looks:

Copy Text

<template>
 <div class="hello">
   <h1>Ask to chatGpt</h1>
   <input v-model="currentMessage" type="text"> <span><button @click="sendMessage(currentMessage)">Ask</button></span>
   <div class="messageBox">
    <template v-for="message in messages">
     <div :class="message.from=='user' ? 'messageFromUser' :'messageFromChatGpt'" :key="message" v-html="message.data"></div>
   </template>
   </div>
 </div>
</template>


<script>
import axios from 'axios'
export default {
 name: "ChatBos",
 data() {
   return {
     messages: [],
     currentMessage: null
   }
 },


 methods: {
   async sendMessage(message) {
     this.messages.push({
       from: 'user',
       data: message
     })
     await axios.post('http://localhost:3000/ask-to-chat-gpt', {
       message: message
     })
     .then((response) => {
       this.messages.push(response.data)
     })
   }
 }
};
</script>


<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
input {
 width: 300px;
 padding: 10px;
}


button {
 height: 40px;
 background-color: powderblue;
 padding: 10px;
}
.messageBox {
 height: 500px;
 background-color: gainsboro;
 /* margin-left: 10%;
 margin-right: 10%; */
 margin: 0 20% 0 20%;
 margin-top: 20px;
 padding: 5%;
}


.messageFromUser {
 text-align: right;
 background-color: aliceblue;
 border-radius: 10px;
 padding: 10px;
 margin-top: 15px;
 margin-bottom: 15px;
 width: 30%;
 margin-left: 70%;
}


.messageFromChatGpt {
 text-align: left;
 background-color: antiquewhite;
 border-radius: 10px;
 padding: 10px;
 margin-top: 15px;
 margin-bottom: 15px;
 width: 30%;
 margin-right: 70%;
}
</style>

Now that we are done with Step 4, Server the Frontend, Backend and Test the Flow

Then, you need to serve the projects and your work is done. Here, we have served the backend on http://localhost:3000 and the Frontend on http://localhost:8080, and these command can be used for serving the Frontend as well as the Backend.

For Backend

Copy Text

node  index.js

For Frontend

Copy Text

npm run serve

You will then see the following screen, as given below:

Ask ChatGPT

Now, enter your question in the input box at the top, as shown in the image above, and you will receive the desired response from ChatGPT.

Congratulations! We have successfully completed your ChatGPT Integration with Node.js and Vue. To ensure its proper functioning, understand the basic stuff of ChatGPT services, shared by our skilled and experienced OpenAI Developers.

Basic Terminologies of ChatGPT Services

In the below image, you can observe that we have mentioned some properties while making a request to the ChatGPT services from backend (chatGpt.controller.js), The value of this parameter also modifies the answer which we will get from the ChatGPT APIs. Let us have a look at it one by one.

Copy Text

await openAIInstance.createCompletion({
    model: 'text-davinci-003',
    prompt: req.body.message,
    temperature: 0,
    max_tokens: 500
})
.then {(response) => {
      const repliedMessage = response.data.choices[0].text
      res.send({from: 'chatGpt', data: repliedMessage})
})
.catch( (error) => {
    //Report error
    console. log('Error ', error)
});

🟠 Model

You must have observed that we have used ‘text-davinci-003’ model, which is the name of the model that we have used. As we know, that ChatGPT is trained with a huge amount of data, so you can choose which model to use while making the request, depending on your use case as well.

🟠 Prompt

Prompt here contains or entails the question that we have to ask ChatGPT, which based on this project is a message requested from the client side.

🟠 Temperature

Temperature here denotes and is responsible for the diversity od answers; you can decide your preferred diversity based on your use case. Keeping the value below 1.0 generates predictable answers.

🟠 Max_tokens

It directly refers to the length of the answers and defines the number of words, punctuation marks, etc.

Conclusion

So, this is what we have in our information bank referring to the ChatGPT Integration with Node and Vue. We hope and believe this tutorial has been beneficial for your to understand the basics of ChatGPT API integrations and services and how it can benefit your business, product owner or developer. If you are also a business owner and planning to integrate ChatGPT to your ChatBot, thenHire Full stack developers to help you throughout your web application journey and gain the conviction to move forward with your next project.**e-code, let us move forward and test it.

0
Subscribe to my newsletter

Read articles from Kartik Bhalerao directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Kartik Bhalerao
Kartik Bhalerao