使用 fetch 调用 OpenAi API 时抛出错误 400 “你必须提供模型参数”

按照 OpenAI API 文档的指示操作,但这个 POST 请求似乎出了问题… 我收到了“必须提供模型参数”的错误… 请求体有什么问题吗?

try {        const response = await fetch(            `https://api.openai.com/v1/completions`,            {                body: JSON.stringify({"model": "text-davinci-003", "prompt": "Say this is a test", "temperature": 0, "max_tokens": 7}),                method: "POST",                headers: {                    Accept: "application/json",                    Authorization: "Bearer [API-KEY]",                },                    }        ).then((response) => {            if (response.ok) {                response.json().then((json) => {                    terminal.echo(json);                });            }        });              console.log("Completed!");    } catch (err) { console.error(`Error: ${err}`) }}```

回答:

根据API 参考,有效的请求看起来像这样:

curl https://api.openai.com/v1/completions \  -H 'Content-Type: application/json' \  -H 'Authorization: Bearer YOUR_API_KEY' \  -d '{  "model": "text-davinci-003",  "prompt": "Say this is a test",  "max_tokens": 7,  "temperature": 0}'

我们可以看到model作为请求体中的一个属性传递。请求体必须是一个 JSON 字符串。此外,API 需要两个请求头:content-typeauthorization

您示例中共享的请求体是正确的。authorization请求头也在其中。然而,您的示例中缺少content-type头 – 显然可能是错误地被accept头替换了。

由于缺少content-type头,API 无法识别请求体的内容类型(可能是 json、yaml、xml 等)。因此,API 无法处理请求体,并响应说缺少模型参数。

以下示例在 Chrome 中可以工作:

    await fetch(        `https://api.openai.com/v1/completions`,        {            body: JSON.stringify({"model": "text-davinci-003", "prompt": "Say this is a test", "temperature": 0, "max_tokens": 7}),            method: "POST",            headers: {                "content-type": "application/json",                Authorization: "Bearer  API_KEY_HERE",            },                }    ).then((response) => {        if (response.ok) {            response.json().then((json) => {                terminal.echo(json);            });        }    });

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注