How to use OpenAI with React

Ravi Sharma
3 min readFeb 12, 2023

--

I hope you heard about OpenAI, and ChatGPT and that’s why you came here to understand, how to use OpenAI with React.

OpenAI is a cutting-edge platform that provides powerful language models and other artificial intelligence tools. ReactJS, on the other hand, is a popular JavaScript library for building user interfaces. When combined, these two technologies can help you build truly impressive applications with advanced capabilities.

In this article, we’ll explore how you can use OpenAI with ReactJS to build a simple chatbot. The chatbot will use OpenAI’s GPT-3 language model to generate responses based on user inputs. Let’s get started!

Setting up the environment

Sign up by visiting openai.com/api and collect your API key

Before we start building our chatbot, we need to set up our development environment. This involves installing ReactJS and the OpenAI SDK.

To install ReactJS, you’ll need to have Node.js and npm (Node Package Manager) installed on your computer. Once you have Node.js and npm installed, you can use the following command to create a new ReactJS application:

npx create-react-app chatbot-app

Next, we’ll install the OpenAI SDK. This can be done by running the following command:

npm install openai

With our environment set up, we can now start building our chatbot!

Building The Chatbot App

The first thing we need to do is create a .env file in the root of your application and store your API key like:

REACT_APP_OPENAI_API_KEY = "Your API Key here"

Next, you will need to install “dotenv” npm package, which will allow you to access the environment variables defined in the .env file.

npm install dotenv

Now you can use the environment variable like:

process.env.REACT_APP_OPENAI_API_KEY

Now to create a component in ReactJS, use the following code:

import { useState } from "react"
const { Configuration, OpenAIApi } = require("openai");

const ChatbotApp = () => {
const configuration = new Configuration({
apiKey: process.env.REACT_APP_OPENAI_API_KEY,
});

const openai = new OpenAIApi(configuration);
const [prompt, setPrompt] = useState("");
const [apiResponse, setApiResponse] = useState("");
const [loading, setLoading] = useState(false);

const handleSubmit = async (e) => {
e.preventDefault();
setLoading(true);
try {
const result = await openai.createCompletion({
model: "text-davinci-003",
prompt: prompt,
temperature: 0.5,
max_tokens: 4000,
});
//console.log("response", result.data.choices[0].text);
setApiResponse(result.data.choices[0].text);
} catch (e) {
//console.log(e);
setApiResponse("Something is going wrong, Please try again.");
}
setLoading(false);
};


return (
<>
<div
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
height: '100vh',
}}
>
<form onSubmit={handleSubmit}>
<textarea
type="text"
value={prompt}
placeholder="Please ask to openai"
onChange={(e) => setPrompt(e.target.value)}
></textarea>
<button
disabled={loading || prompt.length === 0}
type="submit"
>
{loading ? "Generating..." : "Generate"}
</button>
</form>
</div>
{apiResponse && (
<div
style={{
display: "flex",
justifyContent: "center",
}}
>
<pre>
<strong>API response:</strong>
{apiResponse}
</pre>
</div>
)}
</>
);
};


export default ChatbotApp;

That’s it.

Once your setup is done and working, you can continue to customize and improve your chatbot app by adding additional functionality or you can use it in your existing project also.

🙏🏻 Thanks for reading 🧑💻 !!

--

--

Responses (4)