Sunday, June 11, 2023

Create your ChatBot using NodeJs and ReactJs with ChatGPT API in 10 minutes

 Today, I am going to show here how easily we can develop our chatbot with in few minutes using ChatGPT api. Here, I am using followings:

  1. ReactJs for creating user front end
  2. NodeJs for server api interacting with ChatGPT API
  3. ChatGPT API
Here, we have to complete 3 tasks:

Task 1: Create your ChatGPT API secret key to be used in your code. You need to follow below steps:
  1. Open the url https://openai.com/ and login here using your Google Id or create your own login Id and password.
  2. Create your ChatGPT secret key by clicking on the "Create new Secret key" in the url given in below screenshot. Copy and paste this key in your notepad file. You will not be able to retrieve it again. 
        


Task2: Create Node Js api: Here, we should follow the below steps:
  1. Install NodeJs and NPM
  2. Create a node js project by command npm init -y
  3. Install express and axios dependencies.
       {
  "name": "chatnode",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Jitendra Kumar Singh",
  "license": "ISC",
  "dependencies": {
    "axios": "^1.4.0",
    "express": "^4.18.2"
  }
}


4. Create a new file server.js file where you will define port, start server and create api for interacting with ChatGPT api

const express = require('express');
const axios = require('axios');

const app = express();
const port = 3001; // Set your desired port number

app.use(function (req, res, next) {
  res.header("Access-Control-Allow-origin", "http://localhost:3000")
  res.setHeader('Access-Control-Allow-Methods', "GET,POST,OPTIONS")
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
  next();
})

// Middleware to parse JSON request bodies
app.use(express.json());

// POST endpoint to handle user queries
app.post('/api/query', async (req, res) => {
  const { query } = req.body;

  try {
    // Make a POST request to the ChatGPT API
    const response = await axios.post('https://api.openai.com/v1/chat/completions', {
      model: 'gpt-3.5-turbo',
      messages: [{ role: 'system', content: 'You are a helpful assistant.' }, { role: 'user', content: query }],
    }, {
      headers: {
        'Authorization': 'Bearer YOUR_CHATGPT_API_SECRET_KEY', // Replace with your ChatGPT API key
        'Content-Type': 'application/json',
      },
    });

    res.json({ reply: response.data.choices[0].message.content });
  } catch (error) {
    console.error('Error:', error.response.data);
    res.status(500).json({ error: 'An error occurred while processing the request.' });
  }
});

// Start the server
app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});


5) Start your node js server by npm start

Task 3: Create ReactJS user interface:  Here, we need to follow below steps:

  1. In another separate directory, create ReactJs project by using command npx create-react-app your_project_name
  2. Once installation is done, then create dependency of axios. Your final package.json file would be like
{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^1.4.0",
    "concurrently": "^8.2.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}


3) Then open App.js file inside folder named as src and add below code

import React, { useState } from 'react';
import axios from 'axios';

const App = () => {
  const [query, setQuery] = useState('');
  const [reply, setReply] = useState('');

  const handleSubmit = async (event) => {
    event.preventDefault();

    try {
      const response = await axios.post('http://localhost:3001/api/query', { query });

      setReply(response.data.reply);
    } catch (error) {
      console.error('Error:', error.response.data);
    }
  };

  return (
    <div>
      <h1>My Chatbot</h1>
      <form onSubmit={handleSubmit}>
        <input type="text" value={query} onChange={(e) => setQuery(e.target.value)} />
        <button type="submit">Send</button>
      </form>
      {reply && <p>{reply}</p>}
    </div>
  );
};

export default App;

4) Start your UI react application by using command npm start

So, finally when you start UI and Node Js server then you will get functionality as shown below: