ReactJs application using ChatGpt Api

ReactJs application using ChatGpt Api

ยท

2 min read

ChatGPT is a cutting-edge natural language processing technology developed by OpenAI that allows developers to build intelligent chatbots and conversational agents capable of understanding and generating human-like text. With the rise of messaging apps, virtual assistants, and voice-enabled devices, ChatGPT offers an unprecedented opportunity to create more engaging and personalized user experiences.๐Ÿ’ป๐Ÿค–๐Ÿ“ฑ

In this blog, we will introduce to you how to create a ReactJs Application using ChatGpt Api. ๐ŸŽ“๐Ÿ’ก๐Ÿค

Step 1: Create a react App

npx create-react-app my-app
cd my-app
npm start

Step 2: Install OpenAi and dotEnv

npm install openai
npm install dotenv

"dotenv" is used to allow you access to the environment variables defined in the ".env" files

Step 3: Collect your Api Key from OpenAi

visite the link openai.com/api and login, then on the top right click on "Personal" then View API keys

Create your Key and copy it

Step 4: Create .env file and initiate the key inside it

The first thing you need to do is create a file called 'openai.env' in your root directory and add the following line to it :

REACT_APP_OPENAI_API_KEY="Your Api Key"

You can use the environment variables like this :

process.env.REACT_APP_OPENAI_API_KEY

Step 5: App.js Code

import React from 'react';
import { Configuration, OpenAIApi } from 'openai';

function App() {
    const configuration = new Configuration({
        apiKey: process.env.REACT_APP_OPENAI_API_KEY,
    });
    const openai = new OpenAIApi(configuration);

    const [prompt, setPrompt] = useState('');
    const [result, setResult] = useState('');
    const [loading, setLoading] = useState(false);

    const handleClick = async () => {
      setLoading(true);
      try {
        const response = await openai.createCompletion({
        model: 'text-davinci-002',
        prompt: prompt,
        temperature: 0.5,
        max_tokens: 100,
      });
      setResult(response.data.choices[0].text);
      } catch (error) {
      console.log(error);
      }
      setLoading(false);
  };
  return (
    <main>
      <div>
        <textarea
          value={prompt}
          onChange={(e) => setPrompt(e.target.value)}
          placeholder="Enter a prompt here"
          className='font-black text-blacks'
        />
        <button onClick={handleClick} disabled={loading || prompt.length ===          0}>
          {loading ? 'Generating...' : 'Generate'}
        </button>
        <pre>Result : {result}</pre>
      </div>
    </main>
  );
}

export default App;

Step 6: Customise the style and Congratulations ๐Ÿฅณ๐Ÿ˜

Live Preview: chat.tedora.info

Github Repository: github/reactjs_chatgpt_api

Visite Us: Tedora.info

Anass Nebdaoui

ย