How to use OpenAI’s GPT Model to generate responses in a React JS project

by Nano Metitiere

27 jul 2023


Firstly, make sure you have React JS installed and your project set up. You will also need an API key from OpenAI, which you can get by signing up on their website.

Building the Interface

First, let’s set up the interface for our application. We’ll need a form where users can input their text, and a section to display the generated response. We’ll also have a button to submit the text to GPT for processing. For this example, we’ll use React Bootstrap for the UI components.

import React, { useState } from 'react'import { Button, Form } from 'react-bootstrap'import axios from 'axios'function GptResponse() {  // Initialize state variables  const [text, setText] = useState("")  const [response, setResponse] = useState("")  // Function to submit the user's text to GPT  const handleSubmit = async (event) => {    event.preventDefault();    try {      const response = await        '',        {          model: 'text-davinci-002',          messages: [            {              role: 'system',              content: 'You are a helpful assistant.',            },            {              role: 'user',              content: text,            },          ],        },        {          headers: {            'Authorization': 'Bearer ' + 'YOUR_OPENAI_API_KEY',            'Content-Type': 'application/json',          },        }      )      if ( {        setResponse([0].message.content);      }    } catch (error) {      console.error(error);    }  }  const handleTextChange = (event) => {    setText(  }  return (    <Form onSubmit={handleSubmit}>      <Form.Group controlId="text">        <Form.Label>Enter your text</Form.Label>        <Form.Control          as="textarea"          rows={3}          onChange={handleTextChange}          value={text}        />      </Form.Group>      <Button variant="primary" type="submit">        Submit      </Button>      <Form.Group controlId="response">        <Form.Label>Generated Response</Form.Label>        <Form.Control          as="textarea"          rows={3}          readOnly          value={response}        />      </Form.Group>    </Form>  )}export default GptResponse

Remember to replace 'YOUR_OPENAI_API_KEY' with your actual OpenAI API key.

Let’s break down the call:

const response = await  '',  {    model: 'text-davinci-002',    messages: [      {        role: 'system',        content: 'You are a helpful assistant.',      },      {        role: 'user',        content: text,      },    ],  },  {    headers: {      'Authorization': 'Bearer ' + 'YOUR_OPENAI_API_KEY',      'Content-Type': 'application/json',    },  })

This is a call to OpenAI’s API, specifically to the endpoint that allows us to chat with the GPT model.

  • This is the URL of the API endpoint. It's responsible for receiving our request and returning the model's response.
  • model: 'text-davinci-002': This specifies the model we want to use for generating text. In this case, we're using the 'text-davinci-002' model.
  • messages: This is an array of message objects. Each message object has two properties: 'role' and 'content'. The 'role' can be 'system', 'user', or 'assistant', and 'content' is the text of the message.
  • The first message, with ‘role’ set to ‘system’, is used to set up the behavior of the ‘assistant’ — which is how GPT perceives its own role in the conversation. In this case, it’s told “You are a helpful assistant.”
  • The second message, with ‘role’ set to ‘user’, is the input from the user — the text we want the model to respond to.
  • headers: This includes authorization and content type information required by the API. 'Authorization' is your OpenAI API key, prefixed with 'Bearer '. 'Content-Type' should be set to 'application/json' to indicate that we're sending JSON data.
  • await The await keyword is used with to make the HTTP POST request to the OpenAI API. This is an asynchronous operation, meaning that it might take some time to complete and receive a response. The await keyword ensures that JavaScript waits until it receives the response before moving on to the next line of code.

Finally, the response from the API is stored in the response variable, ready to be used in your application.

That’s all for the basic integration of OpenAI’s GPT into a React JS project! You can now take the user’s text, send it to GPT for processing, and display the generated response in your application.