Ask Your Question
4

What is the process for adding the openai apikey into a .env file for a react application?

asked 2021-10-25 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-03-24 11:00:00 +0000

woof gravatar image

To add the OpenAI API key into a .env file for a React application, follow these steps:

  1. Create a new file called .env in the root directory of your React application.

  2. Open the .env file and add the following line:

    REACT_APP_OPENAI_API_KEY=your_api_key_here
    

    Replace your_api_key_here with your actual API key.

  3. Save the .env file.

  4. In your React application code, use the API key by referencing the process.env.REACT_APP_OPENAI_API_KEY variable.

    For example, in a component that uses the OpenAI API, you could do something like this:

    const response = await fetch('https://api.openai.com/v1/engines/davinci-codex/completions', {
     method: 'POST',
     headers: {
       'Content-Type': 'application/json',
       'Authorization': `Bearer ${process.env.REACT_APP_OPENAI_API_KEY}`,
     },
     body: JSON.stringify({
       prompt: '...',
       temperature: 0.5,
       max_tokens: 50,
       n: 1,
     }),
    });
    

    This will use the API key stored in the .env file to authenticate with the OpenAI API.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-10-25 11:00:00 +0000

Seen: 14 times

Last updated: Mar 24 '22