OpenAI API拒绝设置不安全的标头"User-Agent"。

12

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

拒绝设置不安全的标头 "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}`
      });
    })
  }

请注意,OpenAI在API密钥部分包含以下声明:“OpenAI还可能自动轮换我们发现已经公开泄露的任何API密钥。”提交了六次后,我意识到只要我将代码推送到github,OpenAI就会回收密钥。 - Jacob Valdez
5个回答

9

根据您的说明,您之所以收到此错误是因为openai API客户端“拒绝设置不安全的标头”用户代理“。由于使用它需要访问敏感信息(API密钥),Node.js客户端有意限制跨源请求以防止意外泄露机密。

要解决此问题,请参见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;
}

我的回答可能已经过时了。 - Jacob Valdez
requestOptions已被弃用 - Diego Venâncio

3

这对我有用,但它取决于 Configuration 类的实现细节:

// This hardcodes insertion of 'User-Agent'
let config = new Configuration({ apiKey: key,});

// Delete it
delete config.baseOptions.headers['User-Agent'];

let api = new OpenAIApi(config);


1

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

const [chatList, setChatList] = ([]) // ur chat history
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)));
    }

由于OpenAPI响应返回了一个需要通过递归函数处理的可读流,因此有必要包含一个fetchStream()函数。

 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
}

1

我有一些问题。而且这段代码对我有效!

const configuration = new Configuration({
  apiKey: "YOURE_OPENAI_KEY",
  organization: "YOURE_OPENAI_OGRANIZATION",
});

configuration.baseOptions.headers = {
  Authorization: "Bearer " + "YOURE_OPENAI_KEY",
};

1
你的回答可以通过提供更多支持性信息来改进。请[编辑]以添加进一步的细节,例如引用或文档,以便他人确认你的回答是否正确。你可以在帮助中心找到关于如何撰写良好回答的更多信息。 - Community
对我有用。谢谢! - undefined

-2

如果我们从前端/客户端调用OpenAI而不是安全的后端/服务器端,则会出现此错误。


不要在意负评,我确实遇到了这个错误,并且我创建了一个API来解决我的问题。我还在某处读到,在前端,你的密钥可能会泄露出去。 - Muhammad Bilal
不要在意负评,我确实遇到了这个错误,并且我创建了一个API来解决我的问题。我还在某个地方读到过,在前端,你的密钥可能会泄露出去。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接