Part 2: Creating a Chatbot with Node.js, Express, React and OpenAI's API

Part 2: Creating a Chatbot with Node.js, Express, React and OpenAI's API

In this article we will cover the creation of a backend service using Node.js and Express framework to communicate with OpenAI

Hey all! In this blog post, we will talk about creating the backend API with Node.js and Express that will call OpenAI's API to gather information for users. In our last post we covered making the front-end application with React that can act as the user interface! Use that post and this one in order to build a Full Stack Javascript Application that can communicate with OpenAI. If you enjoy this article, sign up for my newsletter and give me a follow on @TheDevInnovator for more software tips!

What is Node.js?

Node.js is an open-source, cross-platform JavaScript runtime environment that executes JavaScript code outside of a web browser. It allows developers to run JavaScript on the server side, creating backend applications with JavaScript.

What is the Express framework?

Express is a minimal and flexible Node.js web application framework that provides a set of features for web and mobile applications. It is an easy-to-use library that allows you to create routes and handle HTTP requests and responses.

Setting up a Node.js and Express project

We will use a package called express-generator to quickly set up a Node.js and Express project.

The express-generator is a package that quickly sets up a new Express project with a directory structure and a set of default dependencies.

To use express-generator, you'll need to have Node.js and npm installed on your machine. Then, run the following command to install the express-generator package globally: npm install -g express-generator

Now, navigate to the directory where you want to create your new Express project and run the following command: express my-project

This will create a new directory called my-project with the Express project structure and a set of default dependencies. To install the dependencies, navigate to the project directory and run the following command: cd my-project && npm install.

You can now start the server running npm start

The server will be running at http://localhost:3000, and you can visit this address in your web browser to see the default Express welcome page.

Connecting to OpenAI

Now that you have your express project up and running, it's time to connect to Open AI's API.

First, you need to sign up for OpenAI by heading here. Upon signing up, you will be able to go to your account and create a new API key. Create a new API key here.

Once you have your API key, head back to your express project and add it to your environment variables by creating a new file called .env with the line

OPENAI_API_KEY=sk-*********

Now that we are signed up with OpenAI and we have an API key, we need to install openai by running npm install openai from the directory where your package.json lives.

At the top of index.js add the following:

import { Configuration, OpenAIApi } from "openai";

const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

As you can see, we need to add our API key from OpenAI that is stored in our .env file.

Now, set up an endpoint in index.js called "api/generate" like this:

router.post('/api/generate', (req, res) => {
  /.../
});

Within this endpoint, you can add the following:

if (!configuration.apiKey) {
    res.status(500).json({
      error: {
        message: "OpenAI API key not configured.",
      }
    });
    return;
  }

  const message = req.body.message || '';
  if (message.trim().length === 0) {
    res.status(400).json({
      error: {
        message: "Please enter a valid message",
      }
    });
    return;
  }

  try {
    const response = await openai.createCompletion({
      model: "text-davinci-003",
      prompt: message,
      temperature: 0.9,
      max_tokens: 150,
      top_p: 1,
      frequency_penalty: 0,
      presence_penalty: 0.6,
    });

    console.log("response: " + JSON.stringify(response.data));

    res.status(200).json({ result: response.data.choices[0].text });
  } catch(error) {
    // Consider adjusting the error handling logic for your use case
    if (error.response) {
      console.error(error.response.status, error.response.data);
      res.status(error.response.status).json(error.response.data);
    } else {
      console.error(`Error with OpenAI API request: ${error.message}`);
      res.status(500).json({
        error: {
          message: 'An error occurred during your request.',
        }
      });
    }
  }

When the /api/generate endpoint is called, this code will be run that grabs the message sent via the req.body.message and calls OpenAI's createCompletion method. See this link for more information about the parameters that you can pass in to the createCompletion.

Connecting frontend to backend

If you followed the instructions from my last post, you will have already set up the React frontend application. With both applications running using npm start, Clicking the send button in the React application will trigger this endpoint to be called!

Conclusion

We have just walked through the process of setting up a Node.js and Express backend application, connecting it to a React frontend, and using Node.js to call OpenAI's API.

We began by installing Node.js and the Express framework, and setting up a basic server with routes to handle HTTP requests and responses. We then connected the backend to a React frontend using the axios library to make HTTP requests. We also covered how to communicate between the frontend and backend, and how to use Node.js to make calls to OpenAI's API.

If you enjoyed learning about building a full-stack JavaScript application with Node.js, Express, and React, be sure to sign up for my newsletter and follow me on Twitter @TheDevInnovator for more tutorials and updates. Thanks for reading!