-2

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.

Rubén
  • 34,714
  • 9
  • 70
  • 166
udenx10
  • 11
  • 2
  • Can you link to the library providing `OpenAIApi` and `Configuration`? – Phil Feb 10 '23 at 00:55
  • I imported it with this line: 'import { Configuration, OpenAIApi } from "openai";' And included it in the funcion with this line: 'const { Configuration, OpenAIApi } = require("openai");' – udenx10 Feb 10 '23 at 00:57
  • 2
    So you're trying to use [openai-node](https://github.com/openai/openai-node) in a React (client-side) app? The library that specifically says _"Important note: this library is meant for server-side usage only, as using it in client-side browser code will expose your secret API key"_ – Phil Feb 10 '23 at 00:58
  • I was just testing it out first and trying to learn. It is not an app being made public for now which was why I wasn't trying to seperate it into a frontend or backend. Is this the reason why it returns that prompt? Because it is a client-side react app? – udenx10 Feb 10 '23 at 01:01
  • 1
    Yes, the library and API are not intended for client-side usage. The API is actively blocking you for your own safety – Phil Feb 10 '23 at 01:02

1 Answers1

0

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.

Wesley LeMahieu
  • 2,296
  • 1
  • 12
  • 8
  • For the record so you aren't shocked - components inside `app` folder are all by default `Server Components`. This means there are some limitations - like no `useEffect`, `useContext`, etc. Next.js forces you to think about things in terms of `Client` and `Server` components. I recommend reading through it if you enjoy React! https://beta.nextjs.org/docs --- Good luck – Wesley LeMahieu Feb 10 '23 at 01:23