How to Build an OpenAI Chatbot with ReactJS and NodeJS

How to Build an OpenAI Chatbot with ReactJS and NodeJS

Have you ever wondered how to build AI products? We don’t blame you. After all, chatbots have drastically changed how companies engage with their customers. They not only offer immediate assistance but also lessen the workload on customer care teams and improve the user experience. They better customer service, automate repetitive tasks, and provide intelligent responses to user queries. With OpenAI's GPT-3 (third-generation language prediction model), you can develop an effective and incredibly engaging chatbot for your application. The result? Amazing possibilities for more efficient customer support!

In this post, we will show you how to build an AI bot more specifically, an OpenAI chatbot with ReactJS and NodeJS. It's not as tough as it looks, really. Even if it seems that way, don't worry! By the end of the tutorial, you will have a functional AI chatbot that you can further customize and integrate into your projects. This tutorial serves as a starting point for building more complex and sophisticated AI chatbots by leveraging the power of OpenAI and the flexible nature of ReactJS and NodeJS.

 

What is OpenAI?

openAI logo

Before moving to how to make an OpenAI chatbot, let’s check out what is OpenAI!

OpenAI is a powerful AI tool that utilizes state-of-the-art machine learning algorithms to enable developers to quickly and easily build AI applications, including chatbots. The natural language processing capabilities of OpenAI allow for the development of chatbots that can understand and offer human-like responses to user queries. 

Some of OpenAI's most notable attributes are its pre-trained language models, such GPT-3, which have been trained on enormous volumes of text data to accurately comprehend the subtleties of human speech. Now let’s check out how to build an app using AI 

 

Prerequisites to know about:

Before diving into this tutorial, ensure that you have the following knowledge and tools:

  1. Basic understanding of JavaScript, ReactJS, and NodeJS
  2. NodeJS (version 10.x+) installed
  3. A code editor like Visual Studio Code
  4. Access to the OpenAI API (you can sign up for an API key at openai.com/signup)

 

Step 1: Create a new React app

The first step to build an AI chatbot is to create a new React app using the following command in your terminal:

 

```javascript

npx create-react-app chatbot-app

```

 

Once the installation is complete, navigate to the project directory:

 

```CMD
cd chatbot-app

```

 

Step 2: Create a NodeJS server

The next step on how to build an AI bot is to create a new folder called `server` in your project's root directory. Inside the server folder, create a new file called `index.js`. This is where we'll set up the server.

In the `server.js` file, Install packages such as Express, and OpenAI, and set up a basic server:

 

```javascript
 

const express = require('express');

const cors = require('cors');

const app = express();

require('dotenv').config()

const PORT = process.env.PORT || 3001;

const OPENAI_API_KEY = process.env.OPENAI_API_KEY ;

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

const configuration = new Configuration({

    apiKey: OPENAI_API_KEY,

});

const openai = new OpenAIApi(configuration);

 

app.use(cors());

app.use(express.json());

 

app.listen(PORT, () => console.log(`Server started on http://localhost:${PORT}`));

 

```
 

Step 3: Create the API Endpoint

In this step to build an AI bot, we will establish the API endpoint that will be invoked from the frontend, so we can retrieve responses from OpenAI for our queries.
 

async function sendTextToOpenAI(text) {

    try {

        console.log(text);

        const response = await openai.createCompletion({

            model: "text-davinci-003",

            prompt: text,

        });

        return response.data.choices[0].text;

    } catch (error) {

        console.log(error.message);

    }

}

app.post('/api/chatbot', async (req, res) => {

    try {

        const response = await sendTextToOpenAI(req.body.text);

        res.json({ reply: response });

    } catch (err) {

        console.error(err);

        res.status(500).send({ error: 'Error connecting to OpenAI.' });

    }

});

 

Step 4: Create the Chatbot Frontend

For the next step on how to build an AI chatbot, we need to establish the chatbot frontend. 

Inside the `src` folder of your React app, open `App.js`. Replace the existing code with the following:

 

```javascript

import { useState } from "react";

import "./App.css";

 

function App() {

  const [text, setText] = useState("");

  const [chat, setChat] = useState([]);

 

  const sendMessage = async (e) => {

    e.preventDefault();

 

    if (!text) return;

 

    setChat([...chat, { text, user: "User" }]);

    const currentMessages = []

    setText("");

 

    const response = await fetch("http://localhost:8002/api/chatbot", {

      method: "POST",

      headers: { "Content-Type": "application/json" },

      body: JSON.stringify({ text }),

    });

    const data = await response.json();

 

    setChat(state => [...state, { text: data.reply, user: "Chatbot" }]);

  };

 

  return (

    <div className="App">

      <h1>OpenAI Chatbot</h1>

      <div className="chat-container">

        {chat.map((message, i) => (

          <p key={i}>

            <strong>{message.user}: </strong>

            {message.text}

          </p>

        ))}

      </div>

      <form onSubmit={sendMessage}>

        <input

          type="text"

          value={text}

          onChange={(e) => setText(e.target.value)}

        />

        <button type="submit">Send</button>

      </form>

    </div>

  );

}

 

export default App

```

 

Step 5: Run Your Chatbot

To run your chatbot, open two terminal windows. In one terminal, start the server by running the following command:

 

```

node server

```

 

In the other terminal, start the React app using:

```

npm start

```

 

Navigate to `http://localhost:3000` in your browser, and you should see your chatbot in action!

Congratulations! You have successfully learned how to make an OpenAI chatbot. It took just 5 steps to create a simple chatbot using OpenAI, ReactJS, and NodeJS. You can now explore further to enhance your chatbot's capabilities and improve its design. 

Additionally, you may want to explore OpenAI's documentation to discover more advanced features and fine-tune the AI's behavior.

 

Why Every Business Needs an AI Chatbot?

AI chatbot

In today's digital age, customers expect instant gratification when it comes to receiving information and support from businesses. This is where AI chatbots come in handy. They offer a seamless and efficient way for businesses to communicate with their customers 24/7. Not only do chatbots provide immediate assistance, but they also help businesses save time and money by automating repetitive tasks. With advancements in AI technology, chatbots have become more intelligent and can even provide personalized recommendations to customers. 

 

So, whether you're a small business owner or a large corporation, you can get in touch with our Open AI experts to learn how to build AI bot, how to build an AI application, and how an AI chatbot can improve your customer service and, ultimately, your bottom line

Akshay Naik
Akshay Naik
Tech Lead
Acquia Certification: Tips & Resources by Joshua Fernandes

The Story of My First Acquia Certification

Joshua Fernandes
Coding Tips, Duke Experience

Coding Tips, Duke Experience

Sandeep Kumar
Case Study – Protein Smoothies (Mobile App)

Case Study – Protein Smoothies (Mobile App)

MOHAN PAI