Error 400 while connecting to chatgpt-3.5-turbo API

Hi everyone,

I’m currently trying to integrate ChatGPT-3.5-Turbo into my project, but I’m encountering a persistent error during the connection process. Could anyone with experience in this area offer some guidance?

image

document.getElementById('send').addEventListener('click', function() {
    const prompt = document.getElementById('input').value;
    const apiKey = '';

    fetch('https://api.openai.com/v1/chat/completions', {
        method: 'POST',
        headers: {
            'Authorization': `Bearer ${apiKey}`,
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            prompt: prompt,
            max_tokens: 100
        })
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`API request failed with status ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        if (data.choices && data.choices.length > 0) {
            document.getElementById('response').innerText = data.choices[0].text;
        } else {
            console.error('Unexpected response format:', data);
        }
    })
    .catch(error => {
        if (error.message.includes('429')) {
            console.error('Rate limit exceeded. Please try again later.');
        } else {
            console.error('Error:', error);
        }
    });
});
        body: JSON.stringify({
            prompt: prompt,
            max_tokens: 100
        })

That is way incorrect.

you specified the chat completions endpoint, but:
There is no model specified.
That endpoint takes an array of JSON messages, not a prompt.

https://platform.openai.com/docs/api-reference/chat/create

Thank you so much for helping!