How to Build a Paraphrasing Tool with ReactJS & ChatGPT Turbo

Paraphrasing, or restating something using different words, is a valuable skill for writers, students, and professionals in many fields. It allows you to express ideas in your own voice, avoid plagiarism, and tailor content to different audiences and contexts. While paraphrasing well takes practice, AI language models like ChatGPT can assist in generating alternative phrasings quickly.

In this tutorial, we‘ll walkthrough building an interactive web app that leverages the ChatGPT Turbo API to provide paraphrasing suggestions. Users will be able to input text, configure paraphrasing options, and view alternative versions generated by the AI. We‘ll be using ReactJS to create the frontend UI and make requests to the API.

By the end, you‘ll have a functional paraphrasing tool that harnesses the power of ChatGPT to accelerate your writing workflow. Let‘s get started!

Technologies Used

Here‘s an overview of the main technologies we‘ll be using:

  • ReactJS: A popular JavaScript framework for building interactive UIs
  • ChatGPT Turbo API: The latest and fastest version of OpenAI‘s ChatGPT language model, accessible via an HTTP API
  • Vite: A fast build tool for modern web apps that we‘ll use to bootstrap our React project
  • TailwindCSS (optional): A utility-first CSS framework for rapidly styling the app

Prerequisites

Before we begin, make sure you have the following set up:

  • Node.js and npm installed on your machine
  • A code editor like VS Code
  • An OpenAI API key (sign up at https://platform.openai.com/)
  • Basic familiarity with HTML, CSS, JavaScript and React

Project Setup

First, let‘s create a new React project using Vite. Run the following commands in your terminal:

npm create vite@latest paraphraser 
cd paraphraser
npm install

Select "React" as the framework and "JavaScript" as the variant. Once the project is created and dependencies installed, start the development server with:

npm run dev

Navigate to the URL shown (usually http://localhost:5173/) and you should see the default React page.

Next, let‘s install a few additional dependencies:

npm install openai react-loading react-markdown

Here‘s what each one does:

  • openai: The official Node.js library for the OpenAI API
  • react-loading: A simple loading indicator component
  • react-markdown: Renders Markdown content as React components (we‘ll use this to format the ChatGPT responses)

Designing the UI

Let‘s plan out the main UI components we‘ll need:

  • Header with title
  • TextInput for the user to enter text to paraphrase
  • ParaphraseOptions to configure the tone, length, etc.
  • GenerateButton to trigger a request to ChatGPT
  • LoadingIndicator while waiting for a response
  • ParaphrasedOutput to display ChatGPT‘s suggestions
  • Footer with links and attribution

Here‘s a simple mockup of how it might look:

[Mockup showing a header, text input box, options, button, and output area]

We can implement these components in the src/App.jsx file. Here‘s a skeleton to get us started:

import { useState } from ‘react‘;
import { Configuration, OpenAIApi } from ‘openai‘;
import ReactMarkdown from ‘react-markdown‘;
import Loading from ‘react-loading‘;

function TextInput({ value, onChange }) {
  return (
    <textarea className="textarea" value={value} onChange={onChange} 
      placeholder="Enter text to paraphrase..." />
  )
}

function ParaphraseOptions() {
  return (
    <div className="options">
      {/* TODO: Add dropdowns/checkboxes for tone, length, etc. */}
    </div>
  );  
}

function GenerateButton({ onClick, disabled }) {
  return (
    <button className="btn" onClick={onClick} disabled={disabled}>
      Generate Paraphrase
    </button>
  );
}

function ParaphrasedOutput({ text }) {
  return (
    <div className="output">
      <ReactMarkdown>{text}</ReactMarkdown>
    </div>
  );
}

function App() {
  const [inputText, setInputText] = useState(‘‘);
  const [outputText, setOutputText] = useState(‘‘);
  const [isGenerating, setIsGenerating] = useState(false);

  async function generateParaphrase() {
    setIsGenerating(true);
    // TODO: Make API request 
    // TODO: Set outputText
    setIsGenerating(false);
  }

  return (
    <div className="app">
      <header>

      </header>
      <main>
        <TextInput 
          value={inputText} 
          onChange={e => setInputText(e.target.value)} 
        />
        <ParaphraseOptions />
        <GenerateButton 
          onClick={generateParaphrase} 
          disabled={isGenerating}
        />
        {isGenerating && (
          <Loading type="bubbles" color="#000" />  
        )}
        <ParaphrasedOutput text={outputText} />
      </main>
      <footer>
        {/* TODO: Add footer content */}
      </footer>
    </div>
  );
}

export default App;

This sets up the basic structure of our app. The key pieces are:

  • The central App component contains the page layout and main state (inputText, outputText, isGenerating)
  • Child components for the input, options, button, loading, and output
  • A generateParaphrase function that will call the API (not yet implemented)

For brevity, we‘re using some unstyled classNames. Let‘s add some basic CSS to the src/index.css file to make things look nicer:

@tailwind base;
@tailwind components;
@tailwind utilities;

.app {
  max-width: 800px;
  margin: 0 auto;
  padding: 2rem;
}

.textarea {
  width: 100%;
  height: 200px; 
  padding: 1rem;
  font: inherit;
}

.options {
  display: flex;
  gap: 1rem;
  margin: 1rem 0;
}

.btn {
  padding: 0.5rem 1rem;
  background: #2563eb;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.output {
  margin-top: 2rem;
  border-top: 1px solid #ccc;
  padding-top: 2rem;
}

Feel free to customize these styles to your liking. We‘re also importing TailwindCSS here (totally optional, just my preferred CSS approach).

Integrating ChatGPT

Now for the exciting part – calling the ChatGPT Turbo API to actually generate the paraphrased text!

First, create a .env file in the project root and add your OpenAI API key:

VITE_OPENAI_API_KEY=your_key_here

Make sure to prefix the variable name with VITE_ so that it gets loaded into environment variables by Vite.

Back in src/App.jsx, let‘s flesh out that generateParaphrase function:

const configuration = new Configuration({
  apiKey: import.meta.env.VITE_OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

// ...

async function generateParaphrase() {
  setIsGenerating(true);

  const completion = await openai.createChatCompletion({
    model: "gpt-3.5-turbo",
    messages: [
      {
        role: "system", 
        content: "You are a paraphrasing assistant. Rewrite the user‘s input using different words and phrasing."
      },
      {
        role: "user",
        content: inputText
      }
    ],
    temperature: 0.7
  });

  setOutputText(completion.data.choices[0].message.content);
  setIsGenerating(false);
}

This does a few key things:

  1. Initializes the OpenAI configuration with our API key
  2. Calls the createChatCompletion endpoint with the gpt-3.5-turbo model
  3. Provides a system message to prime ChatGPT to act as a paraphrasing assistant
  4. Sends the user‘s inputText as the user message
  5. Sets the outputText state to the generated response
  6. Controls the isGenerating state before/after the request

The temperature parameter controls how "creative" the model will be (higher = more random, lower = more focused). Feel free to experiment with different values to see how it affects the outputs.

Congrats, you should now have a working paraphrasing tool! Try inputting some text, hit "Generate Paraphrase" and marvel at ChatGPT‘s rephrasings.

Paraphrasing Options

To make our tool more powerful and flexible, let‘s add some options that the user can set to customize the paraphrasing. Some ideas:

  • Writing tone (e.g. formal, casual, persuasive)
  • Length relative to input (e.g. shorter, same, longer)
  • Degree of word changes (e.g. minor, moderate, substantial)

We can capture these in state variables and pass them to ChatGPT in the system message to steer the outputs. Here‘s how we might extend the ParaphraseOptions component:

function ParaphraseOptions({ options, setOptions }) {
  return (
    <div className="options">
      <label>
        Tone:
        <select 
          value={options.tone}
          onChange={e => setOptions({...options, tone: e.target.value})}
        >
          <option value="default">Default</option>  
          <option value="formal">Formal</option>
          <option value="casual">Casual</option>
          <option value="persuasive">Persuasive</option>
        </select>
      </label>

      <label>
        Length:
        <select
          value={options.length}  
          onChange={e => setOptions({...options, length: e.target.value})}
        >
          <option value="default">Default</option>
          <option value="shorter">Shorter</option>
          <option value="longer">Longer</option>
        </select>  
      </label>

      <label>
        Word Changes:  
        <select
          value={options.wordiness}
          onChange={e => setOptions({...options, wordiness: e.target.value})}  
        >
          <option value="default">Default</option>
          <option value="minor">Minor</option>
          <option value="moderate">Moderate</option> 
          <option value="substantial">Substantial</option>
        </select>
      </label>
    </div>
  );
}

And in the App component:

const [options, setOptions] = useState({
  tone: ‘default‘,
  length: ‘default‘, 
  wordiness: ‘default‘
});

// ...

async function generateParaphrase() {
  setIsGenerating(true);

  const prompt = `Paraphrase the following text:

${inputText}

Use a ${options.tone} tone, ${options.length} length, and ${options.wordiness} word changes compared to the original.`; 

  const completion = await openai.createChatCompletion({
    model: ‘gpt-3.5-turbo‘,
    messages: [
      {
        role: ‘system‘,
        content: prompt 
      }
    ],
    temperature: 0.7
  });

  setOutputText(completion.data.choices[0].message.content);
  setIsGenerating(false);
}

// ...

<ParaphraseOptions options={options} setOptions={setOptions} />

Now the prompt that gets sent to ChatGPT incorporates the user‘s selected options. Try inputting some text and playing around with the dropdowns to see how it affects ChatGPT‘s paraphrases.

Styling & Polish

Our paraphrasing tool is looking pretty good! The final touches are to style it a bit more and add any "nice-to-have" features. Some ideas:

  • Additional error handling (e.g. if API key is missing or request fails)
  • Word count of input vs. output
  • Button to copy output to clipboard
  • Ability to save/load input text
  • Explanations of what each option does
  • Different visual themes

I‘ll leave those as exercises for the reader. Feel free to go wild and really make it your own!

Tips for Great Paraphrasing with ChatGPT

While ChatGPT is great at coming up with alternative phrasings, it‘s not perfect. The outputs can sometimes change the meaning in unwanted ways or sacrifice clarity for novelty. Some tips for getting the best results:

  • Be as specific as possible in your prompts. The more context and guidance you can give, the better.
  • Experiment with the temperature setting. Lower values will produce more conservative, on-topic paraphrases.
  • If a paraphrase isn‘t quite right, try regenerating or adjusting the options. ChatGPT can produce surprisingly different outputs from the same prompt.
  • Always proofread and manually touch up ChatGPT‘s suggestions as needed. Use it as an assistant, not a replacement for your own writing and editing skills.

With a little trial and error, ChatGPT can become a powerful partner in your paraphrasing workflows.

Conclusion

In this tutorial, we built an interactive paraphrasing tool powered by ChatGPT. We used ReactJS to create the frontend UI, the ChatGPT Turbo API to generate rephrasings, and TailwindCSS to style everything.

Along the way, we learned how to:

  • Scaffold a React project with Vite
  • Design and implement UI components in React
  • Manage state for user inputs and API responses
  • Integrate with the OpenAI API to generate completions
  • Prompt ChatGPT to get desired paraphrasing behaviors
  • Style a web app using TailwindCSS utility classes

I hope this inspires you to build your own AI-powered writing tools! With the building blocks we covered, you can extend this in countless ways – tone/style transfer, text summarization, creative story generation, and more. The possibilities are endless.

So what will you create? Happy building!

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *