google-apps-scriptgoogle-sheetsurlfetchopenai-api

Why Open AI API returns a random text


I'm using Apps script to create a video title out of input text. But I get irrelevant gibberish-type text in return, a mixture of some code, symbols, and random text. I have also tried different prompts but it didn't solve the issue. However, it returns good results on the website (ChatGPT).

var UrlFetchApp = UrlFetchApp || Import.google.script.url;
var apiUrl = "https://api.openai.com/v1/engines/davinci-codex/completions";
var apiKey = "*****************";

function generateContentForMultipleRows(myRange) {
  var bulletPoints = myRange.getValues();

  bulletPoints.forEach(function (row, i) {
    var prompt1 = "create a title of up to 6 words that sums up this content" + row[0];

    var options1 = {
      "method": "POST",
      "headers": {
        "Content-Type": "application/json",
        "Authorization": "Bearer " + apiKey
      },
      "payload": JSON.stringify({
        "prompt": prompt1,
        "max_tokens": 100
      })
    };
    var response1 = UrlFetchApp.fetch(apiUrl, options1);
    var json1 = JSON.parse(response1.getContentText());
    var generatedContent1 = json1.choices[0].text;

    SpreadsheetApp.getActiveSheet().getRange(2 + i, 4).setValue(generatedContent1);
  });
}

Solution

  • I have solved it by changing API URL:

    When I added 'model' in payload it raised an error that you can't specify engine and model both. So, I deleted engine from URL and kept 'model' in payload only. That's it, it's working ok now.