Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Running a cURL in GAS

I am trying to use the OpenAI API in Google Apps Script but having a little trouble running the cURL.
The documentation gives me this:

curl https://api.openai.com/v1/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{"model": "text-davinci-002", "prompt": "Say this is a test", "temperature": 0, "max_tokens": 6}'

Which I wrote as this in GAS:

function myFunction() {
  var url = "https://api.openai.com/v1/completions";
  var headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer ******',
    'data': {
      'model': 'text-davinci-002', 'prompt': 'Say this is a test', 'temperature': 0, 'max_tokens': 6
    }
};

var response = UrlFetchApp.fetch(url, headers);
var text = response.getResponseCode();
var data = JSON.parse(response.getContentText());
Logger.log(data);
}

where ****** is my API Key I got from my account. When I run this script, I get an error saying I didn’t provide my API Key. I’ve double-checked and the key is correct so I’m guessing something is wrong with my formatting?
TIA

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In your script, how about the following modification?

From:

  var headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer ******',
    'data': {
      'model': 'text-davinci-002', 'prompt': 'Say this is a test', 'temperature': 0, 'max_tokens': 6
    }
};

var response = UrlFetchApp.fetch(url, headers);

To:

var options = {
  'contentType': 'application/json',
  'headers': { 'Authorization': 'Bearer ******' },
  'payload': JSON.stringify({ 'model': 'text-davinci-002', 'prompt': 'Say this is a test', 'temperature': 0, 'max_tokens': 6 })
};

var response = UrlFetchApp.fetch(url, options);

Note:

  • This modification supposes that your sample curl command worked fine. Please be careful about this.

Reference:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading