OpenAI API 拒绝设置不安全的标头“User-Agent”

问题描述 投票:0回答:2

我不明白为什么会收到此错误。

拒绝设置不安全的标头“User-Agent”

我正在尝试将 OpenAI 的 API 用于个人项目。我不明白为什么它拒绝设置这个“不安全的标头”以及我如何或是否可以使其安全。我试过用谷歌搜索这个问题,顶部链接是一个 GitHub 论坛,它解释了 Chrome 可能会做些什么,但是,我试图在 Safari 中使用该应用程序,但它也不起作用。

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}`
  });
})

}

reactjs forms api submit openai-api
2个回答
8
投票

如您所述,您收到错误是因为 openai API 客户端“拒绝设置不安全的标头”User-Agent”。由于使用它需要访问敏感信息(API 密钥),因此 nodejs 客户端有意限制跨源请求以防止意外泄露秘密。

有关解决方法,请参阅 https://github.com/openai/openai-node/issues/6,其中 AmanKishore 手动请求完成。

我最终像这样编写了自己的完成函数:

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;
}

0
投票

使用 Jacobs 答案作为参考,这里是 GPT 3.5 Turbo API 的解决方法。

 async function createCompletion(params = {}) {
        const DEFAULT_PARAMS = {
            model: "gpt-3.5-turbo",
            messages: [{ role: "user", content: "Hello World" }],
            // max_tokens: 4096,
            temperature: 0,
            // frequency_penalty: 1.0,
            // stream: true,
        };
        const params_ = { ...DEFAULT_PARAMS, ...params };
        const result = await fetch('https://api.openai.com/v1/chat/completions', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + String(your_api_key)
            },
            body: JSON.stringify(params_)
        });
        const stream = result.body
        const output = await fetchStream(stream);
        setChatList(previousInputs => (previousInputs.concat(output.choices[0].message)));
    }

需要包含函数 fetchStream(),因为 openapi 响应返回一个 readableStream,需要通过递归函数处理。

 async function fetchStream(stream) {
    const reader = stream.getReader();
    let charsReceived = 0;
    const li = document.createElement("li");

    // read() returns a promise that resolves
    // when a value has been received
    const result = await reader.read().then(
        function processText({ done, value }) {
            // Result objects contain two properties:
            // done  - true if the stream has already given you all its data.
            // value - some data. Always undefined when done is true.
            if (done) {
                console.log("Stream complete");
                return li.innerText;
            }
            // value for fetch streams is a Uint8Array
            charsReceived += value.length;
            const chunk = value;
            console.log(`Received ${charsReceived} characters so far. Current chunk = ${chunk}`);
            li.appendChild(document.createTextNode(chunk));
            return reader.read().then(processText);
        });
    const list = result.split(",")
    const numList = list.map((item) => {
        return parseInt(item)
    })
    const text = String.fromCharCode(...numList);
    const response = JSON.parse(text)
    return response
}
© www.soinside.com 2019 - 2024. All rights reserved.