Search code examples
javascriptreactjsopenai-apigpt-3

I do not know why I can't access open ai's api for use in a react app


I am trying to access openai's api for a react application. I am getting an "unsafe header" error, an error 400, and at the same time "https://api.openai.com/v1/completions" is sending me a prompt about not providing my api key, even though I am providing the api key through a .env file. I do not know what to do, and I'm wondering what exactly I did wrong.

This is the react function I am using:

const configuration = new Configuration({
    apiKey: process.env.REACT_APP_OPENAI_API_KEY,
    organization: "org-xut9Kn1LqNLyDiHEMAQlnJ0k"
});

const openai = new OpenAIApi(configuration);

const handleSuggestions = async (text) => {
  const response = await openai.createCompletion({
      model: "text-davinci-001",
      prompt: "autocomplete this word, letter or sentence: " + text,
      max_tokens: 100,
      n: 1,
      stop: text.length - 1,
      temperature: 0.15,
  });
  console.log(response);
  const data = await response.json();
  setSuggestions(response.choices[0].text.split(' ').slice(text.split(' ').length - 1).join(' ').split(' '));
};

``

I am getting a "unsafe header "User-Agent"" error as well as an error 400 from "https://api.openai.com/v1/completions" in my browser console while running the react app. This is the full prompt I am getting back from "https://api.openai.com/v1/completions":

{
    "error": {
        "message": "You didn't provide an API key. You need to provide your API key in an Authorization header using Bearer auth (i.e. Authorization: Bearer YOUR_KEY), or as the password field (with blank username) if you're accessing the API from your browser and are prompted for a username and password. You can obtain an API key from https://platform.openai.com/account/api-keys.",
        "type": "invalid_request_error",
        "param": null,
        "code": null
    }
}

Please what can I do, and what exactly is wrong with the code? Also, hoping this counts as a "Minimal, Reproducible Example", as I am pretty new to stack overflow.


Solution

  • You should be making the request from a server not your client.

    Ajax request: Refused to set unsafe header

    I highly recommend checking out Next.js 13 as it uses React under-the-hood and let's you create "Server" components that are essentially isomorphic.

    Here's an example Next.js 13 app/pages.tsx file:

    const App = async () => {
      console.log("App.js");
    
      const results = await fetch(
        `http://api.weatherapi.com/v1/forecast.json?key=<API_KEY>&q=Stockholm&days=6&aqi=no&alerts=no`
      );
    
      const json = await results.json();
      console.log("json", json);
    
      return (
        <>
          <h3>{json.location.name}</h3>
          <p>{json.location.temp_c}</p>
          <p>{json.location.localtime}</p>
        </>
      );
    };
    
    export default App;
    

    Check out this working Next.js 13 / React18 sandbox which hits the Weather API - If you'd like fork it and see if your API calls work on the server inside this app.pages.tsx file. Otherwise you will need to use a Firebase Function or some backend server.