Automation using Airtable

I’m trying to write this script for automation in Airtable but the console says there’s an error when making the API request to ChatGPT. Can someone help me?
WhatsApp Image 2024-05-08 at 16.51.12



let apiKey = "api key"; // Replace with your ChatGPT API key

let table = base.getTable("Teste");

let query = await table.selectRecordsAsync();

for (let record of query.records) {
    let greeting = record.getCellValueAsString("Obrigado");
    if (greeting) {
        let response = await fetch('https://api.openai.com/v1/chat/completions', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${apiKey}`
            },
            body: JSON.stringify({
                model: "gpt-4",
                messages: [
                    { role: 'user', content: greeting }
                ]
            })
        });

        if (!response.ok) {
            console.error("Error making request to the ChatGPT API");
            return;
        }

        let data = await response.json();
        let reply = data.choices[0].message.content;

        await table.updateRecordAsync(record, {
            "Imagine": reply
        });
    }
}

I found your post while searching for the solution, I have the following code which works inside Airtable Scripting extension, but I don’t know how can it be used for different rows continuously.

async function getGPTResponse() {
    const userInput = "why is the sky blue?";
    const maxTokens = 500;
    const temperature = 0.7;
    const model = "gpt-4.1";
    const systemPrompt = "be precise";

    const messages = [
        { role: "system", content: systemPrompt },
        { role: "user", content: userInput },
    ];

    const res = await fetch('https://api.openai.com/v1/chat/completions', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${openaiApiKey}`,
        },
        body: JSON.stringify({
            model,
            messages,
            max_tokens: maxTokens,
            temperature,
        }),
    });

    const data = await res.json();
    return data.choices?.[0]?.message?.content || null;
}