使用 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

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

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