fervor [>]CODING & CURIOSITY
FERVOR LEARNING SYSTEMTUTORIALS
← React

React / 10 MIN READ

OpenAI API

Integrating OpenAI API with React

From the original Fervor library. Examples may use older package versions.

Alright, let’s dive into creating a React component that taps into the magic of ChatGPT 3.5 via the OpenAI API! Picture yourself as a digital wizard, summoning the power of AI to converse with users through a sleek, magical interface. Here’s a step-by-step guide to bring this vision to life:

Step 1: Gather Your Magical Ingredients

Before we start, make sure you have these ingredients ready in your cauldron:

  • Node.js and npm: Ensure you have Node.js and npm installed. They’re your spellbook and wand, respectively.
  • React App: Have a React app ready. If you don’t, you can create one with create-react-app.
  • OpenAI API Key: Secure an API key from OpenAI. It’s like a secret password that grants you access to the power of ChatGPT.

Step 2: Setting Up Your React Cauldron

If you need to create a new React app, run this incantation in your terminal:

npx create-react-app chatgpt-magic
cd chatgpt-magic

Step 3: Summoning the OpenAI API

First, you need a way to communicate with OpenAI. Create a .env file in your project root and safely store your API key like this (but replace Your_OpenAI_API_Key with your actual key):

REACT_APP_OPENAI_API_KEY=Your_OpenAI_API_Key

Step 4: Crafting the Chat Component

Create a new file named ChatGPT.js in your src folder. This is where you’ll craft your component.

import React, { useState } from 'react';
import axios from 'axios';

const ChatGPT = () => {
  const [input, setInput] = useState('');
  const [responses, setResponses] = useState([]);

  const handleInputChange = (e) => {
    setInput(e.target.value);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!input.trim()) return;

    const response = await axios.post(
      'https://api.openai.com/v1/completions',
      {
        model: 'text-davinci-003', // Or use the latest available model
        prompt: input,
        max_tokens: 100,
      },
      {
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${process.env.REACT_APP_OPENAI_API_KEY}`,
        },
      }
    );

    setResponses([...responses, { prompt: input, response: response.data.choices[0].text }]);
    setInput(''); // Clear input after sending
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={input}
          onChange={handleInputChange}
          placeholder="Ask ChatGPT anything..."
        />
        <button type="submit">Send</button>
      </form>
      <div>
        {responses.map((item, index) => (
          <div key={index}>
            <p><strong>Prompt:</strong> {item.prompt}</p>
            <p><strong>Response:</strong> {item.response}</p>
          </div>
        ))}
      </div>
    </div>
  );
};

export default ChatGPT;

Step 5: Enabling Conversations with the AI

Now, integrate your ChatGPT component into your app. Open src/App.js and modify it like this:

import React from 'react';
import ChatGPT from './ChatGPT';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <h1>Chat with GPT-3</h1>
      </header>
      <ChatGPT />
    </div>
  );
}

export default App;

Step 6: Styling Your Magical Interface

Feel free to sprinkle some CSS magic in App.css to make your chat interface look enchanting.

Step 7: Launching Your Spell

Run your React app with:

npm start

And voilà! You’ve successfully conjured a chat interface powered by ChatGPT 3.5. Users can now ask questions, and the AI will respond, making your site not just interactive, but intelligently responsive.

Remember, this is but a basic spell. The true magic comes when you customize and expand this component to suit your needs. Experiment with prompts, model parameters, and UI designs to make your chat experience uniquely magical. Happy coding, digital wizard!

Part II creating a netlify ENV

Deploying your React app to Netlify with environment variables (like your OpenAI API key) involves a mix of secrecy and magic. Netlify, the enchanted realm where web projects thrive, allows you to set environment variables directly in its UI, ensuring your secrets remain hidden from prying eyes. Let’s walk through this process step by step:

Step 1: Prepare Your App for Deployment

Before you embark on this journey, ensure your React app is ready and tested locally. Double-check that everything works as expected, especially the parts that use your environment variables.

Step 2: Push Your Code to a Git Repository

If you haven’t already, initialize a Git repository in your project folder, commit your code, and push it to a remote repository on GitHub, GitLab, or Bitbucket. Netlify works hand-in-hand with these services, allowing for a seamless deployment process. Remember to exclude your .env file by adding it to your .gitignore. Your secrets should never wander off into remote repositories.

Step 3: Create a Netlify Account and Start a New Project

  • Navigate to Netlify and sign in or create an account if you haven’t got one.
  • Once logged in, you’ll find an option to “New site from Git” on the dashboard. Click on this to start the deployment process.

Step 4: Connect Your Git Repository

  • Follow the prompts to connect your Git provider (GitHub, GitLab, or Bitbucket) and authorize Netlify to access your account.
  • Select the repository where your React app lives.

Step 5: Configure Your Build Settings

Netlify will ask you for build commands and publish directory. For a standard React app created with create-react-app, you can use these settings:

  • Build command: npm run build
  • Publish directory: build/

Before you click on the Deploy site button, let’s add those magical environment variables.

Step 6: Adding Environment Variables to Netlify

  • Look for the Environment Variables section in the site settings. It’s usually found under Settings > Build & deploy > Environment.
  • Click on the Edit variables button or New variable if you’re setting them for the first time.
  • Enter the name and value for each of your environment variables. For example, you’d add REACT_APP_OPENAI_API_KEY as the name and paste your actual OpenAI API key as the value.
  • Save your changes.

Step 7: Deploy Your App

With your environment variables now securely in place, go back to the Deploy tab and hit Deploy site. Netlify will now build your app using the settings and variables you’ve provided. Once the build completes, your site will be live on a unique Netlify URL.

Step 8: Celebrate and Share

Congratulations! You’ve just deployed your React app with its environment variables safely to Netlify. Share your unique Netlify URL with friends, family, or colleagues and let them marvel at your creation.

By using Netlify’s environment variables, you’ve ensured that your OpenAI API key remains a closely guarded secret, visible only to you and Netlify’s trusted build environment. This is essential for keeping your app secure and your API usage under control.

Bonus Coolness

By weaving some enchantment into your React app with components that give ChatGPT a personality can create a captivating user experience. Here’s an idea for a component that channels ChatGPT’s advice-giving abilities, styled with a specific personality in mind—let’s say, a wise sage who imparts wisdom with a mix of ancient proverbs and modern-day savvy.

SageAdviceGPT Component

Imagine a component where users come seeking wisdom on life’s various quandaries, from the profound to the mundane. ChatGPT, embodying the personality of a wise sage, dispenses advice, anecdotes, and occasionally, a proverb or two. This component would not only provide users with insights but also entertain them with its sage-like persona.

Component Structure

  • SageAdviceGPT.js: The main component where users submit their questions.
  • AdviceDisplay.js: A sub-component that displays the sage’s advice.
  • useSageWit.js: A custom React hook that manages the interaction with the OpenAI API, encapsulating the logic for sending queries and receiving advice.

Implementing SageAdviceGPT

SageAdviceGPT.js

import React, { useState } from 'react';
import { useSageWit } from './useSageWit';
import AdviceDisplay from './AdviceDisplay';

const SageAdviceGPT = () => {
  const [query, setQuery] = useState('');
  const { advice, isLoading, getAdvice } = useSageWit();

  const handleInputChange = (e) => {
    setQuery(e.target.value);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    getAdvice(query);
  };

  return (
    <div className="sage-advice-container">
      <h2>Seek Wisdom from the Sage</h2>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={query}
          onChange={handleInputChange}
          placeholder="What wisdom do you seek?"
        />
        <button type="submit">Ask the Sage</button>
      </form>
      {isLoading ? <p>Consulting the stars...</p> : <AdviceDisplay advice={advice} />}
    </div>
  );
};

export default SageAdviceGPT;

AdviceDisplay.js

import React from 'react';

const AdviceDisplay = ({ advice }) => {
  return (
    <div className="advice-display">
      <p>{advice}</p>
    </div>
  );
};

export default AdviceDisplay;

useSageWit.js

import { useState } from 'react';
import axios from 'axios';

export const useSageWit = () => {
  const [advice, setAdvice] = useState('');
  const [isLoading, setIsLoading] = useState(false);

  const getAdvice = async (query) => {
    setIsLoading(true);
    const response = await axios.post(
      'https://api.openai.com/v1/completions',
      {
        model: 'text-davinci-003', // Adjust model as necessary
        prompt: `You are a wise sage. Give thoughtful advice on the following: ${query}`,
        max_tokens: 150,
      },
      {
        headers: {
          Authorization: `Bearer ${process.env.REACT_APP_OPENAI_API_KEY}`,
        },
      }
    );

    setAdvice(response.data.choices[0].text.trim());
    setIsLoading(false);
  };

  return { advice, isLoading, getAdvice };
};

Bringing It to Life

To make the SageAdviceGPT component come alive:

  • Style It: Use CSS to give your component an “ancient wisdom” feel. Think parchment backgrounds, cursive fonts, and mystical icons.
  • Enhance Interactivity: Consider implementing a “history of wisdom” feature that saves past queries and advice, allowing users to revisit the sage’s wisdom.
  • Expand the Sage’s Personality: Integrate more detailed prompts that play up the sage’s personality. For example, you could have the sage reference historical figures, philosophical concepts, or famous proverbs in its advice.

This example illustrates how you can craft a component with a unique twist, leveraging the capabilities of ChatGPT to create an engaging and interactive user experience. Feel free to adapt and expand upon this idea, infusing your own creativity and vision to develop something truly magical.

Bonus KISS method with the component

Let’s simplify the approach by creating a component where you can pass the context (or personality) as a prop. This way, you can reuse the component for different personalities or contexts by merely changing the prop, without altering the component’s internal logic. This approach is great for maintaining a clean and flexible codebase. Here’s how you could do it:

Step 1: Create the ChatWithGPT Component

This component will handle the input from the user, communicate with the OpenAI API, and display the response. The context or personality is passed as a prop to this component, which it then includes in the prompt sent to the API.

ChatWithGPT.js

import React, { useState } from 'react';
import axios from 'axios';

const ChatWithGPT = ({ context }) => {
  const [query, setQuery] = useState('');
  const [response, setResponse] = useState('');

  const handleChange = (event) => {
    setQuery(event.target.value);
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    if (!query) return;

    try {
      const { data } = await axios.post(
        'https://api.openai.com/v1/completions',
        {
          model: 'text-davinci-003', // Adjust based on the latest model or specific needs
          prompt: `${context}\n\n${query}`,
          max_tokens: 100,
        },
        {
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${process.env.REACT_APP_OPENAI_API_KEY}`,
          },
        }
      );

      setResponse(data.choices[0].text.trim());
      setQuery(''); // Optional: Clear the query after receiving the response
    } catch (error) {
      console.error('Failed to fetch the response:', error);
      setResponse('Sorry, something went wrong.');
    }
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={query}
          onChange={handleChange}
          placeholder="Ask me anything..."
        />
        <button type="submit">Submit</button>
      </form>
      {response && <p>{response}</p>}
    </div>
  );
};

export default ChatWithGPT;

Step 2: Use the Component with Different Contexts

Now, you can use the ChatWithGPT component in your application and pass different contexts as props. This way, the same component can act as a versatile tool for various interactions, whether it’s giving advice, answering questions, or even telling stories.

App.js Example

import React from 'react';
import ChatWithGPT from './ChatWithGPT';

const App = () => {
  return (
    <div>
      <h1>Chat with GPT-3</h1>
      <ChatWithGPT context="You are a wise sage. Provide thoughtful advice." />
      <ChatWithGPT context="You are a travel guide. Give travel tips and information." />
    </div>
  );
};

export default App;

Simplifying and Extending Functionality

This setup offers simplicity and flexibility, allowing you to:

  • Easily swap contexts to change the interaction without modifying the component’s core logic.
  • Scale your app by adding more instances of the component with different contexts to serve various purposes or user needs.
  • Maintain a clean and understandable codebase, making it easier to update contexts or adjust the component’s behavior.

By passing context as a prop, you create a reusable and versatile component that can adapt to different scenarios, making your application more dynamic and engaging.

Keep your curiosity going.Explore more React →
287 TUTORIALS · 22 TOPICSREADY