Integrate OpenAI ChatGPT API in React JS
Table of Contents
- Introduction
- Setting Up the Server
- Creating the Frontend UI
- Handling User Input and Sending Requests
- Displaying the Chatbot Responses
- Conclusion
Introduction
In this tutorial, I will Show You how to use the Opening Eyes API to integrate ChatGPT or Create your own chatbot in a React application. We will be using Express as a dedicated server in Node.js. You will need to have Node.js installed, along with the latest version. We will also need an OpenAI account and API key. Please make sure you have these before proceeding.
Setting Up the Server
To create our server, we will use the Express framework along with other dependencies such as cors, body-parser, and axios. First, make sure you have the required packages installed by running the following command in your terminal:
npm install express openai body-parser cors axios
Once the installations are complete, we can start setting up our server. We will require the necessary modules and define our OpenAI API Key. Please make sure to keep your API key secure and consider using a .env file in a production environment.
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const openai = require('openai');
const config = {
apiKey: 'YOUR_API_KEY',
};
const openaiInstance = new openai.OpenAI(config);
Next, we can create our Express app and configure Middleware for handling JSON and enabling CORS.
const app = express();
app.use(bodyParser.json());
app.use(cors());
Now, let's define an endpoint for handling chatbot requests. We will use the /chat
route and handle POST requests.
app.post('/chat', async (req, res) => {
const { prompt } = req.body;
try {
const completion = await openaiInstance.complete({
model: 'davinci',
maxTokens: 512,
temperature: 0,
prompt,
});
const response = completion.data.choices[0].text;
res.send(response);
} catch (error) {
console.log(error);
res.status(500).json({ error: 'Failed to generate response' });
}
});
Finally, we can start our server and listen on a specified port.
const port = 3000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
Creating the Frontend UI
Now that our server is set up, we can move on to creating the frontend UI. In this example, we will be using React. First, let's create a new component called ChatGPT
in the src/components
directory.
import React, { useState } from 'react';
import axios from 'axios';
const ChatGPT = () => {
const [prompt, setPrompt] = useState('');
const [response, setResponse] = useState('');
const handleSubmit = async (event) => {
event.preventDefault();
try {
const url = 'http://localhost:3000/chat';
const { data } = await axios.post(url, { prompt });
setResponse(data);
} catch (error) {
console.log(error);
}
};
return (
<div className="container">
<h1 className="title text-center">ChatGPT</h1>
<form className="form-group" onSubmit={handleSubmit}>
<label htmlFor="question">Ask a question:</label>
<input
type="text"
id="question"
className="shadow-sm"
placeholder="Enter your question"
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
/>
<button type="submit" className="btn btn-primary">
Submit
</button>
</form>
<div className="response">
{response ? (
<p className="text-light">{response}</p>
) : (
<p className="text-light">Ask me anything!</p>
)}
</div>
</div>
);
};
export default ChatGPT;
In this component, we use the useState
hook to manage the prompt and response states. When the form is submitted, we make a POST request to our server's /chat
route with the user's input. The response is then displayed on the screen.
Handling User Input and Sending Requests
To handle user input and send requests to the server, we use the handleSubmit
function. This function is triggered when the form is submitted. We prevent the default form behavior and make an asynchronous POST request to our server using Axios.
const handleSubmit = async (event) => {
event.preventDefault();
try {
const url = 'http://localhost:3000/chat';
const { data } = await axios.post(url, { prompt });
setResponse(data);
} catch (error) {
console.log(error);
}
};
Displaying the Chatbot Responses
The chatbot response is displayed in the response
state. We conditionally render the response Based on its availability. If there is a response, we display it in a <p>
tag with the text-light
class, and if there is no response, we display a message to ask the user to input a question.
<div className="response">
{response ? (
<p className="text-light">{response}</p>
) : (
<p className="text-light">Ask me anything!</p>
)}
</div>
Conclusion
In this tutorial, we learned how to integrate ChatGPT into a React application using the Opening Eyes API. We set up a server using Express, handled user input, sent requests to the server, and displayed the chatbot responses in the frontend UI. You can now enhance this application by adding more features and improving the user experience.
资源:React, Express, OpenAI