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.
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 axios.post( 'https://api.openai.com/v1/chat/completions', { 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 (response.data) { setResponse(response.data.choices[0].message.content); } } catch (error) { console.error(error); } } const handleTextChange = (event) => { setText(event.target.value) } 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.
const response = await axios.post( 'https://api.openai.com/v1/chat/completions', { 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.
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.