Search code examples
javascriptgoogle-apps-scripturlfetchpalm-apimakersuite

Accessing Googles Palm api from Apps Script


There are currently a few QuickStart's for Palm API text.

PaLM API: Text Quickstart

The examples show how to do this in Python, but I have not found any way of getting it to work with Google Apps Script.

Can I send a request to this API with Apps Script directly, or do I need to wait for them to create a library?


Solution

  • I was not able to find any direct information about the endpoint to call but Makersuite gave me a curl example which I was then able to figure out what the call looked like

    enter image description here

    curl \
      -H 'Content-Type: application/json' \
      -X POST 'https://generativelanguage.googleapis.com/v1beta2/models/text-bison-001:generateText?key='${API_KEY} \
      -d '{ "prompt": { "text": "Write a poem about an adventure in an underwater castle\n\n"}, "temperature": 0.7, "top_k": 40, "top_p": 0.95, "candidate_count": 1, "max_output_tokens": 1024, "stop_sequences": [], "safety_settings": [{"category":"HARM_CATEGORY_DEROGATORY","threshold":1},{"category":"HARM_CATEGORY_TOXICITY","threshold":1},{"category":"HARM_CATEGORY_VIOLENCE","threshold":2},{"category":"HARM_CATEGORY_SEXUAL","threshold":2},{"category":"HARM_CATEGORY_MEDICAL","threshold":2},{"category":"HARM_CATEGORY_DANGEROUS","threshold":2}]}'
    

    Then I was able to use UrlFetchApp.fetch to access the data from the PALM api directly via app script. This seems to work well until they create a library for it.

    function myFunction() {
      
      // Make a POST request with form data.
      var data = {
                  "prompt": {
                        "text": "Write a story about a magic backpack."
                        },
                  "temperature": 1.0,
                  "candidateCount": 2};
      var options = {
        'method' : 'post',
        'contentType': 'application/json',
        // Convert the JavaScript object to a JSON string.
        'payload' : JSON.stringify(data)
      };
    
    
      try {
          
          const response = UrlFetchApp.fetch('https://generativelanguage.googleapis.com/v1beta2/models/text-bison-001:generateText?key=REDACTED', options);
          Logger.log(response);
          const data = JSON.parse(response.getContentText());
    
          Logger.log(data.candidates[0].output);
      } catch (f) {
          Logger.log(f.message);
      }
    }
    

    The tricky part was parsing the response. It returns in an array sometimes there can be more then one candidate.