OpenAI API Refused to set unsafe header "User-Agent"

Viewed 190

I don't understand why I am receiving this error.

Refused to set unsafe header "User-Agent"

I am trying to use OpenAI's API for a personal project. I don't understand why it's refusing to set this "unsafe header" and how, or if, I can make it safe. I've tried googling this issue and the top link is for a GitHub forum that explains how it might be something that Chrome does but, I tried to use the app in Safari and it wouldn't work either.

const onFormSubmit = (e) => {
e.preventDefault();

const formData = new FormData(e.target),
  formDataObj = Object.fromEntries(formData.entries())
console.log(formDataObj.foodDescription);

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

openai.createCompletion("text-curie-001", {
  prompt: `generate food suggestions from the following flavor cravings: ${formDataObj.foodDescription}`,
  temperature: 0.8,
  max_tokens: 256,
  top_p: 1,
  frequency_penalty: 0,
  presence_penalty: 0,
})
.then((response) => {
  setState({
    heading: `AI Food Suggestions for: ${formDataObj.foodDescription}`,
    response: `${response.data.choices[0].text}`
  });
})

}

1 Answers

As you stated, you're recieving the error because the openai API client "Refused to set unsafe header "User-Agent". Since using it requires access to sensitive information (the API key), the nodejs client intentionally restricts cross origin requests to prevent accidentally revealing secrets.

For a workaround, see https://github.com/openai/openai-node/issues/6 where AmanKishore manually requests completions.

I ended up writing my own completion function like so:

const DEFAULT_PARAMS = {
  "model": "text-davinci-002",
  "temperature": 0.7,
  "max_tokens": 256,
  "top_p": 1,
  "frequency_penalty": 0,
  "presence_penalty": 0
}

export async function query(params = {}) {
  const params_ = { ...DEFAULT_PARAMS, ...params };
  const requestOptions = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + String(openai_api_key)
    },
    body: JSON.stringify(params_)
  };
  const response = await fetch('https://api.openai.com/v1/completions', requestOptions);
  const data = await response.json();
  return data.choices[0].text;
}
Related