Integrating ChatGPT with Node and Vue

Websolutionstuff | Jul-17-2023 | Categories : VueJs Node.js

In a world where technology and human interaction blend seamlessly, artificial intelligence (AI) holds incredible potential to shape our future. One exciting development in this field is ChatGPT, an advanced AI-based application that has captured our imagination.

In this blog post, we will explore how ChatGPT can be integrated with Node and Vue, two popular technologies.

Get ready to witness the extraordinary possibilities that arise when human creativity meets the power of AI. Let's dive into the promising world of ChatGPT integration

The flow of ChatGPT Integration with Node and Vue

flow-of-integration

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

 

Step 1: Dummy Project Setup

Combining Node.js and Vue.js in the ChatGPT project will open many exciting possibilities in web development.

With Node.js as the backend and Vue.js as the frontend, our project focuses on creating a connection between the two using a simple backend setup.

By configuring a single endpoint that accepts POST requests, we enable seamless communication between the frontend and the backend, ultimately integrating the powerful capabilities of ChatGPT.

This harmonious blend of technologies has the potential to elevate ordinary connections into extraordinary experiences.

When it comes to the front end, simplicity is the key. In this case, we have a ChatBox component that serves as the messenger between users and ChatGPT.

It's responsible for sending messages and receiving the corresponding responses, making the interaction seamless and user-friendly.

 

Step 2: Set the OpenAI SDK/Package

OpenAI is like the middleman between users and the ChatGPT server. It's the official package for ChatGPT, making communication smooth and easy. It's the essential link that ensures a seamless and enjoyable experience for everyone involved.

Also, it is the official package for ChatGPT, to explore more and dive deeper into the details refer to the Documentation.

Next, we will install the OpenAI package in the backend with this command:

npm install openai

Now, we will configure chatGpt.controller.js which will communicate with ChatGPT APIs from the backend. See this:

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
}

 

 

Step 3: Set Up the Frontend

We've designed a special component called ChatBox.vue, which you can find in the /src/components directory.

This component plays a crucial role in connecting with the backend of our application. To make this connection possible, we rely on Axios, a powerful tool for handling API requests.

Now, here is an explanation of how we use Axios to communicate with our backend.

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 like this:

<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, the coding part is done, so we will move forward to test it.

 

Step 4: Test the Flow

Here, we have served the backend on http://localhost:3000 and the Frontend on http://localhost:8080.

For Backend

node  index.js

For Frontend

npm run serve

Now, you will see a ChatGPT input box on the top. Just input a question and you will receive its respective answer from ChatGPT.

So, we have successfully integrated ChatGPT with Node and Vue.

To make the functioning smooth and efficient, understanding the basics of ChatGPT services will be beneficial.

 

Basic Terminologies of ChatGPT

When we use the ChatGPT services, we can customize our requests by specifying certain properties.

These properties play a vital role in determining the responses we receive from the ChatGPT APIs.

To understand this better, let's take a closer look at each property and how it influences the answers we get. It's like unlocking a magical world where our requests shape the outcomes.

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

Here, we have used the ‘text-davinci-003’ model. As we know, ChatGPT is trained with huge data sets, you can choose which model to use while making the request, depending on your use case as well.

 

Prompt

The prompt is the question that we have to ask ChatGPT. In our project, it is a message requested from the client side.

 

Temperature

Temperature determines the diversity of answers you receive, allowing you to choose the level of variation that suits your needs. Lower values below 1.0 offer more predictable responses, while higher values offer more imaginative and diverse outcomes.

 

Max_Tokens

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

 

Conclusion

Integrating ChatGPT with Node and Vue brings exciting opportunities for developers and bloggers.

This combination allows us to create interactive chat interfaces that utilize the power of natural language processing and the user-friendly features of Vue.

Through this, we can enhance customer support, build intelligent chatbots, and craft immersive storytelling experiences that captivate our audience.

With ChatGPT, Node, and Vue, the possibilities for creative and innovative conversational AI are limitless.

 


You might also like:

Recommended Post
Featured Post
How To Check Password Strength Using JQuery
How To Check Password Strength...

In this article, we will see how to check password strength using jquery. here we will check whether password ...

Read More

Sep-04-2020

How To Integrate Swagger In laravel 10
How To Integrate Swagger In la...

In the dynamic realm of modern web development, ensuring that APIs are well-documented, easy to comprehend, and seamless...

Read More

Aug-18-2023

How To Add Ckeditor In Laravel
How To Add Ckeditor In Laravel

In this article, I will explain you how to add ckeditor in laravel, CKEditor is a WYSIWYG rich text edito...

Read More

Jun-18-2020

How To Validate Password And Confirm Password Using JQuery
How To Validate Password And C...

In this article, we'll explore a simple way to validate passwords and confirm passwords using jQuery. Password valid...

Read More

Sep-02-2020