Home > Mobile >  Using fetch to call the OpenAi API throws error 400 "you must provide a model parameter"
Using fetch to call the OpenAi API throws error 400 "you must provide a model parameter"

Time:12-29

Followed the OpenAI API docs and but there is something wrong with this POST request... I get an "you must provide a model parameter" error ... what is wrong with the request body?

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

CodePudding user response:

As per API Reference a valid request looks like this:

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

We can see that model is passed as a property in the request body. The request body has to be a JSON string. Additionally, the API requires two request headers: content-type and authorization.

The request body shared in your example is correct. The authorization request header is also there. However, the content-type header is missing in your example as it was - apparently and probably mistakenly - replaced by the accept header.

Due to the missing content-type header, the API does not know what content type the request body body has (could be json, yaml, xml, etc..). The API therefore, cannot process the request body and responds with the fact that the model parameter is missing.

The following example works in 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