DEV Community

Cover image for Build a Text Summarization App in React with ChatGPT
Femi Akinyemi
Femi Akinyemi

Posted on • Updated on

Build a Text Summarization App in React with ChatGPT

Introduction

In today's digital age, the abundance of information can be overwhelming. With the constant stream of news, research papers, social media updates, and online content, it can be tough to keep up and make sense of it all.

Hence, this is where a text summarization app comes in. With a text summarization app, users can quickly and easily condense large amounts of text into a shorter, easier-to-digest format. It can also improve comprehension by highlighting the main points and key takeaways from a piece of content, making it easier to retain information.

Also, Text summarization offers a solution by automating the condensation of lengthy texts into shorter, more manageable versions.

You can find the code for this tutorial here.

Project Demo

Click here to see the project demo.

Prerequisites

To follow this tutorial, you must have prior knowledge of React and Node.JS version 18+.

The Plan

In this tutorial, you will build a text summarization app in React using OpenAI's ChatGPT model.
You will learn how to:

  • Set up a React project
  • Install necessary dependencies,
  • Send a text to the ChatGPT model, and
  • Extract the summarized text from the model's response.

Additionally, you will discover ways to enhance the text summarization feature.

Getting started with ChatGPT

To get started with ChatGPT and also get your OpenAI API key, follow these steps:

  • Log in or create a new account on OpenAI for a free account. By following the instructions, you'll get to your Dashboard. Click on your profile picture to view the menu bar, and then click View API Keys to proceed to the API Keys page.

View API Keys

  • Click on Create new secret key to create a new API Key.
    Create new secret key

  • Copy the API Key and store it safely to use later in the tutorial.
    API Key

Installing dependencies such as the OpenAI API client library

The next step is to Install the official OpenAI library, then navigate into the project directory and run the following command:

npm install openai
Enter fullscreen mode Exit fullscreen mode

Add the OPENAI_API_KEY in the .env file.
In the project root directory, create a .env file and add the code below:

REACT_APP_OPENAI_API_KEY = your-api-key-here
Enter fullscreen mode Exit fullscreen mode

Make sure you use a valid API key you obtained from OpenAI earlier in the tutorial instead of your-API-key-here.

Overview of ChatGPT and its capabilities

Developed by OpenAI, ChatGPT is a large-scale language generation model. It utilizes the GPT-2 architecture and works on diverse datasets of web pages. Using ChatGPT, you can complete text, translate, summarize, and translate human-like text.

ChatGPT can answer complex questions conversationally. Its ability to understand the intended meaning behind human questions makes it groundbreaking.

Among the characteristics of ChatGPT is its ability to generate coherent and contextually appropriate text. Due to the wide variety of input styles and formats the model has learned, it can adapt to different input style formats and generate text that matches the context.

Another important capability of ChatGPT is that it generates grammatically correct and semantically meaningful text. Using the model to summarize a text is the perfect way to ensure it understands its meaning.

Aside from handling massive inputs, ChatGPT can also generate long-form text. Writing essays, articles, and even books is possible with it.

The Frontend

Bootstrapping React Application

Using Create React App, let's create a react project by running the following command in your terminal:

npx create-react-app text-summarization


cd text-summarization


npm start
Enter fullscreen mode Exit fullscreen mode

The command above creates a new React application called text-summarization using the create-react-app tool, navigates into the application, and starts a development server to see the changes you will make to the application in real-time on the browser.

Implementing the Text Summarization Feature

In the src/App.js file, replace its content with this:


    import "./App.css";
    import { Configuration, OpenAIApi } from "openai";
    import { useState } from "react";

    function App() {
      const [text, setText] = useState("");
      const [summarizedtext, setsummarizedtext] = useState("");
      const [loading, setLoading] = useState(false);

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

      const HandleSubmit = (e) => {
        setLoading(true);
        e.preventDefault();
        openai
          .createCompletion({
            model: "text-davinci-003",
            prompt: generatePrompt(text),
            temperature: 0.6,
            max_tokens: 100,
          })
          .then((res) => {
            if (res.status === 200) {
              setLoading(false);
              setsummarizedtext(res?.data?.choices[0]?.text);
            }
          })
          .catch((err) => {
            console.log(err, "An error occured");
          });
      };

      function generatePrompt(text) {
        return `Summarize this ${text}. and break them into seperate lines`;
      }

      return (
        <div className="App_">
          <div className="header">
            <h1 className="header_text">
              Text <span className="text_active">Summarizer</span>
            </h1>
            <h2 className="header_summary">
              {" "}
              Summarise your text into a shorter length.
            </h2>
          </div>
          <div className="container">
            <div className="text_form">
              <form>
                <label>Enter your text</label>
                <textarea
                  rows={14}
                  cols={80}
                  placeholder="Put your text"
                  value={text}
                  onChange={(e) => setText(e.target.value)}
                />
              </form>
            </div>
            <div>
              <button type="button" onClick={HandleSubmit}>
                {loading ? "loading..." : "Summarize"}
              </button>
            </div>
            <div className="summarized_text">
              <label>Summarized text</label>
              <textarea
                placeholder="Summarized text"
                cols={80}
                rows={14}
                value={summarizedtext}
                onChange={(e) => setText(e.target.value)}
              />
            </div>
          </div>
        </div>
      );
    }

    export default App;

Enter fullscreen mode Exit fullscreen mode

The code above creates a form for the user to enter text and displays a summarized version of that text.

import {Configuration, OpenAIApi } from openai

is a statement that imports two modules, Configuration, and OpenAIApi, from the openai library.
Configuration is a class that allows you to configure the Openai API. You can do this by setting the API key.

OpenAIApi is a class that enables you to interact with the Openai API, such as sending a text for summarization and receiving the summarized text in response. As part of the code, these classes interact with the Openai API to summarize the user's input.
The user's input is tracked using the useState hook and passed to the Openai API for summarization.

The summarized text appears in a separate text area. The function uses the Openai library to interact with the API, and the React Hooks useState() to keep track of the text input, summarized text, and loading state.

The code uses the generatePrompt() function to format the text input for the API. Upon clicking the "Summarize" button, the HandleSubmit is invoked, which sends the text to the API, sets the loading state to true, and displays "loading...". Upon receiving the summarized text, the loading state changed to false, and the summarization was displayed.

Adding Style

To style the project, replace the custom CSS style in the src/App.css file with the content below:

    * {
      margin: 0;
      padding: 0;
    }

    #root {
      background: #61dafb;
    }

    .App_ {
      margin: 0 auto;
      width: 100%;
      max-width: 70%;
      background: #61dafb;
      height: auto;
    }


    .container {
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      gap: 20px;

    }

    textarea {
      width: 100%;
      margin-top: 10px;
    }


    .summarized_text {
      margin-bottom: 30px;
    }


    .header {
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      margin-bottom: 20px;
    }

    .header_text {
      font-size: 3.75rem;
      line-height: 1;
      color: #ffffff;
    }

    .text_active {
      color: tomato;
    }

    .header_summary {
      font-size: 1.5rem;
      line-height: 2rem;
      color: #ffffff;
    }

    button {
      padding: 0.75rem 2.5rem;
      border-radius: 0.5rem;
      border: #ffffff;
      background: tomato;
      color: #ffffff;
    }

    label {
      color: #ffffff;
      font-size: 1.2rem;
      line-height: 1.25rem;
      font-weight: 500;

    }

Enter fullscreen mode Exit fullscreen mode

Result

Testing the App

To test the project, navigate into your text-summarization directory and run:

npm start
Enter fullscreen mode Exit fullscreen mode

Visit localhost:3000 in your browser to view your Test Summarization App.

Below is an example of what you should see on the screen:

Conclusion

In conclusion, this article has shown how to build a text summarization app in React using OpenAI's ChatGPT model.

The app allows users to condense large amounts of text into a shorter, more manageable format, improving comprehension and retention of information. As a result of the step-by-step tutorial, readers learned how to set up a React project, install necessary dependencies, send text to the ChatGPT model, and extract summarized text from the model's response.

With the knowledge gained from this article, readers can now create their text summarization app using the powerful ChatGPT model.

Resources

OpenAI Documentation
Using ChatGPT with React Native and NextJS to build a cross platform AI app
How to Build a Text Summarizer App in Next.js using an API

Top comments (24)

Collapse
 
kakauandme profile image
Kirill Kliavin

Good work. You are exposing your API key in JS, tho. Meaning anyone can abuse it and your billing will go through the roof. FYI

Collapse
 
femi_akinyemi profile image
Femi Akinyemi

What is the best way to handle the API key on the front end? @kakauandme

Collapse
 
pengeszikra profile image
Peter Vivo

If you use Nextjs instead of react and store your key in .env file ( gitignored ), and chatGPT api call maded on server side. pages/api/chatGPT.ts then your key will safe.

Thread Thread
 
femi_akinyemi profile image
Femi Akinyemi

Yes! This works for Nextjs. But How do you handle it in React ? @pengeszikra

Thread Thread
 
pengeszikra profile image
Peter Vivo

You can either ask for a key as user input or use .env in React. When using .env, anyone who downloads your repository can fill in the environment values. However, front-end solutions are never secure as the key can be seen when monitoring the API request.

Thread Thread
 
femi_akinyemi profile image
Femi Akinyemi

thanks @pengeszikra env file was created and that was where the key was stored

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
femi_akinyemi profile image
Femi Akinyemi

Thank you for finding this Article helpful @abhaysinghr1 . I appreciate it. OpenAI is awesome. Please give it a try

Collapse
 
nayanika12 profile image
Nayanika-12

Once I entered the text to be summarised, and clicked on the summarise button its just loading for a long time and summarised text is being shown. What do I do?

Collapse
 
femi_akinyemi profile image
Femi Akinyemi

did you use your API KEY ?

Collapse
 
nayanika12 profile image
Nayanika-12 • Edited

Yes I did. Is it okay?
Image description

Thread Thread
 
femi_akinyemi profile image
Femi Akinyemi

can you reach out to me via akinfemi46@gmail.com so we can look at it together and see what you're not doing right

Thread Thread
 
nayanika12 profile image
Nayanika-12 • Edited

yes yes sure. Thank u so much. Mailed u!

Thread Thread
 
nayanika12 profile image
Nayanika-12

Thank u so much Femi, its working now.

Thread Thread
 
hady68 profile image
Hardikk Kamboj

what was the issue? I am facing something similar

Thread Thread
 
femi_akinyemi profile image
Femi Akinyemi

Did you check the console to see the error you're getting? Also, check your API Usage to be sure you have not exceeded your normal Quotal @hady68

Thread Thread
 
hady68 profile image
Hardikk Kamboj

Hey yes, that was the case, figured it out and built some fun projects following this during my internship!

Thread Thread
 
femi_akinyemi profile image
Femi Akinyemi

Interesting! Glad it helped

Collapse
 
chrisgreening profile image
Chris Greening

Wow, fantastic article Femi!

Loving how detailed this tutorial is - ChatGPT is really exciting and I love seeing what everyone's building with it :~) I've only used the ChatGPT interface on OpenAI but I'd love to mess around with the API next time I'm building a side project to incorporate it into my own apps. Thank you for the tutorial!

Collapse
 
femi_akinyemi profile image
Femi Akinyemi

Glad you found the article Interesting and well detailed😊. Yeah! ChatGPT is really exciting😀 Go ahead and build with the Api✌🏽@chrisgreening

Collapse
 
kawacarp307 profile image
John Doe

this is gold! Thanks for sharing. 😊

Collapse
 
femi_akinyemi profile image
Femi Akinyemi

Thanks for finding it helpful. @kawazackie307

Collapse
 
divyanshukatiyar profile image
Divyanshu Katiyar

A really nice tutorial, could really use this step by step to enhance my learning :)

Collapse
 
femi_akinyemi profile image
Femi Akinyemi

Definitely👌 @divyanshukatiyar