skip to Main Content

Here is my code:

export async function getStructuredMessage(messageText) {
    const response = await fetch('https://api.openai.com/v1/chat/completions', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${API_KEY}`,
        },
        body: JSON.stringify({
            messages: [{ role: 'system', content: messageText }],
        }),
    });

    const data = await response.json();
    return data.choices[0].message.content;
}

Why I got this error: POST https://api.openai.com/v1/chat/completions 400?

here I use the function

async function fetchStructuredMessage() {
    const response = await getStructuredMessage(message.text);
    setStructuredMessage(response);
}

2

Answers


  1. Stephan Cleary is correct, you need supply the requried model.
    You can find the requriements here.

    So you should be able to change your body:

    JSON.stringify({
                model: 'gpt-3.5-turbo',
                messages: [{ role: 'system', content: messageText }],
            })
    

    Although I would not use the role ‘system’, but ‘user’ for a single message. ‘system’ is meant more for system messages / instructions to the model.

    Login or Signup to reply.
  2. There are 4 required parameters for the /v1/chat/completions endpoint, as stated in the official OpenAI documentation:

    • model
    • messages
      • role
      • content

    Screenshot

    You didn’t provide the model parameter.

    Try this:

    export async function getStructuredMessage(messageText) {
        const response = await fetch('https://api.openai.com/v1/chat/completions', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                Authorization: `Bearer ${API_KEY}`,
            },
            body: JSON.stringify({
                model: 'gpt-3.5-turbo', /* Add this */
                messages: [{ role: 'system', content: messageText }],
            }),
        });
    
        const data = await response.json();
        return data.choices[0].message.content;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search