Open AI 返回错误代码 429 和不安全的标头。

huangapple go评论78阅读模式
英文:

Open AI error its returning 429 and unsafe header

问题

以下是您要翻译的代码部分:

import PropTypes from 'prop-types'
import React, { useState } from 'react'
const { Configuration, OpenAIApi } = require("openai");

function TextForm(props) {
    const key = //key 
    const configuration = new Configuration({
        apiKey: key,
    });
    const openai = new OpenAIApi(configuration);

    const [text, setText] = useState("Enter text here");
    const [wordCount, setWordCount] = useState(text.length);
    const [responseText, setResponseText] = useState("");

    const header = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer //key',//also not sure what Bearer is
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36',
    }

    const previewCase = async (event) => {
        event.preventDefault();
        const response = await openai.createCompletion({
            model: "text-davinci-003",
            prompt: "Say this is a test",
            temperature: 0,
            max_tokens: 7,
            headers: header,
        }).then((response) => { console.log(response.data); }).catch((error) => { console.log(error); });
        setResponseText(response.data);
    }

    const convertToUpperCase = (event) => {
        event.preventDefault()
        console.log("Converting to upper case...");
        setText(text.toUpperCase());
    };

    const convertToLowerCase = (event) => {
        event.preventDefault()
        console.log("Converting to lower case...");
        setText(text.toLowerCase());
    };

    const handleManageCount = (event) => {
        setText(event.target.value)
        const Array = text.split(" ");
        setWordCount(Array.length);
        if (text.length === 0) {
            setWordCount(0);
        }
    }
    return (
        <>
            <form>
                <div className="row d-flex justify-content-center">
                    <div className="form-group col-lg-8 mt-3">
                        <label htmlFor="exampleFormControlTextarea1 row"><h3>{props.title}</h3></label>
                        <textarea className="form-control mt-3" id="exampleFormControlTextarea1" rows="20" value={text} onChange={handleManageCount}></textarea>
                        <h6 className='mt-3'><span>Word:</span>{wordCount}</h6>
                        <div className=''>
                            <button className='btn btn-secondary mt-3 mx-2' onClick={convertToUpperCase}>Convert to Upper case</button>
                            <button className='btn btn-secondary mt-3 mx-2' onClick={convertToLowerCase}>Convert to Lower case</button>
                            <button className='btn btn-secondary mt-3 mx-2' onClick={previewCase}>Preview Summary</button>
                        </div>
                    </div>
                </div>
            </form>
            <div className="container">
                <p><h1>Preview Summary</h1>
                    {responseText}
                </p>
            </div>
        </>
    )
    TextForm.propTypes = { title: PropTypes.string.isRequired };
    TextForm.defaultProps = { title: "Write Here!" };
}

export default TextForm;

希望这能帮助到您。

英文:

So this is the code not sure why isn't the open AI not working. Please do let me know thanks below is the code.

import PropTypes from &#39;prop-types&#39;
import React , {useState}   from &#39;react&#39;
const { Configuration, OpenAIApi } = require(&quot;openai&quot;);
function TextForm(props){
const key = //key 
const configuration = new Configuration({
apiKey: key,
});
const openai = new OpenAIApi(configuration);
const [text,setText] = useState(&quot;Enter text here&quot;);
const [wordCount,setWordCount] = useState(text.length);
const [responseText,setResponseText] = useState(&quot;&quot;);
const header = {
&#39;Content-Type&#39;: &#39;application/json&#39;,
&#39;Authorization&#39;: &#39;Bearer //key&#39;,//also not sure what Bearer is
&#39;User-Agent&#39;: &#39;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36&#39;,
}
const previewCase = async (event) =&gt; {
event.preventDefault();
const response = await openai.createCompletion({
model: &quot;text-davinci-003&quot;,
prompt: &quot;Say this is a test&quot;,
temperature: 0,
max_tokens: 7,
headers: header,
}).then((response) =&gt; {console.log(response.data);}).catch((error) =&gt; {console.log(error);});
setResponseText(response.data);
}
const convertToUpperCase = (event) =&gt; {
event.preventDefault()
console.log(&quot;Converting to upper case...&quot;);
setText(text.toUpperCase());
};
const convertToLowerCase = (event) =&gt; {
event.preventDefault()
console.log(&quot;Converting to lower case...&quot;);
setText(text.toLowerCase());
};
const handleManageCount = (event) =&gt; {
setText(event.target.value)
const Array = text.split(&quot; &quot;);
setWordCount(Array.length);
if (text.length === 0){
setWordCount(0);
}
}
return (
&lt;&gt;
&lt;form&gt;
&lt;div className=&quot;row d-flex justify-content-center&quot;&gt;
&lt;div className=&quot;form-group col-lg-8 mt-3&quot; &gt;
&lt;label htmlFor=&quot;exampleFormControlTextarea1 row&quot;&gt;&lt;h3&gt;{props.title}&lt;/h3&gt;&lt;/label&gt;
&lt;textarea className=&quot;form-control mt-3&quot; id=&quot;exampleFormControlTextarea1&quot; rows=&quot;20&quot; value={text} onChange={handleManageCount}&gt;&lt;/textarea&gt;
&lt;h6 className=&#39;mt-3&#39;&gt;&lt;span&gt;Word:&lt;/span&gt;{wordCount}&lt;/h6&gt;
&lt;div className=&#39;&#39;&gt;
&lt;button className=&#39;btn btn-secondary mt-3 mx-2&#39; onClick={convertToUpperCase} &gt;Convert to Upper case&lt;/button&gt;
&lt;button className=&#39;btn btn-secondary mt-3 mx-2&#39;  onClick={convertToLowerCase}&gt;Convert to Lower case&lt;/button&gt;
&lt;button className=&#39;btn btn-secondary mt-3 mx-2&#39;  onClick={previewCase}&gt;Preview Sumarry&lt;/button&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/form&gt;
&lt;div className=&quot;container&quot;&gt;
&lt;p&gt;&lt;h1&gt;
Preview Summary
&lt;/h1&gt;
{responseText}
&lt;/p&gt;
&lt;/div&gt;
&lt;/&gt;
)
TextForm.propTypes = {title:PropTypes.string.isRequired};
TextForm.defaultProps = {title : &quot;Write Here!&quot;};
}
export default TextForm; 

[enter image description here](https://i.stack.imgur.com/PvMb1.png)

So I am trying to provide it with a prompt that user will type on the text form and upon clicking the preview button he will recieve the sumarry backk

答案1

得分: 0

你正在使用 openai 的 npm 包。在这种情况下,你不需要在请求中发送头信息。你会注意到,在你的头信息中,你尝试设置 API 密钥。

除非你已经使用配置变量设置了 API 密钥。

我已经重写了你的代码的开头,对我来说可以正常工作。

function TextForm(props) {
  const key = //key 
  const configuration = new Configuration({
    apiKey: key,
  });
  const openai = new OpenAIApi(configuration);

  const [text, setText] = useState("在这里输入文本");
  const [wordCount, setWordCount] = useState(text.length);
  const [responseText, setResponseText] = useState("");

  const previewCase = async (event) => {
    event.preventDefault();
    const response = await openai.createCompletion({
      model: "text-davinci-003",
      prompt: "说这是一个测试",
      temperature: 0,
      max_tokens: 7
    }).then((response) => {
      console.log(response.data.choices[0].text);
    }).catch((error) => {
      console.log(error);
    });
    setResponseText(response.data.choices[0].text);
  }
}

只有在直接与 API 端点一起工作时才需要使用头信息,但因为你正在使用 NPM 包,它会为你直接设置头信息。

通过从你的代码中移除头信息,你不应该会收到不安全头信息的警告。

请注意,我还修复了你的响应的控制台日志。为了获得实际的响应文本,你需要深入响应对象的几层:

response.data.choices[0].text
英文:

You are using the openai npm package. In this case you don't need to send headers with the request. You will notice in your headers you are trying to set the API key.

Except you already set the API key with the configuration variable.

I have rewritten the start of your code and it works for me.

function TextForm(props){
const key = //key 
const configuration = new Configuration({
apiKey: key,
});
const openai = new OpenAIApi(configuration);
const [text,setText] = useState(&quot;Enter text here&quot;);
const [wordCount,setWordCount] = useState(text.length);
const [responseText,setResponseText] = useState(&quot;&quot;);
const previewCase = async (event) =&gt; {
event.preventDefault();
const response = await openai.createCompletion({
model: &quot;text-davinci-003&quot;,
prompt: &quot;Say this is a test&quot;,
temperature: 0,
max_tokens: 7
}).then((response) =&gt; {console.log(response.data.choices[0].text);}).catch((error) =&gt; {console.log(error);});
setResponseText(response.data.choices[0].text);
}

You would only use headers if you were working directly with the API endpoints but because you are using the NPM package it is setting the headers for you directly.

By removing the headers from your code you shouldn't get the unsafe headers alert.

Notice I also fixed up the console log of your response. In order to get the actual response text you have to go several layers into the response object:

response.data.choices[0].text

huangapple
  • 本文由 发表于 2023年2月16日 04:40:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75465228.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定