Its Free! Gemini API with AppScript free anywhere.


One of the issues with Gemini currently is that it is location locked. So you cant use it from the EU. One of the ways to get around that is to use Google APP script. Google App script runs on Googles servers so it is not effected by the location discrimination. Currently in place with Gemini API

Configuration

You need an API key to run Gemini the only way to get an API key is to use a VPN and create it on Google AI studio. Once you have your API key. You can include it in the code directly or create a script property as i have done here

function run() {
  try {
    var model = "gemini-pro";
    var prompt = "hello";
    var key = getKey(); // Replace with your API key
    var responseContent = doPostRequestWithExponentialBackoff(model, prompt, key);
    var textContent = extractTextFromResponse(responseContent);
    Logger.log("Response: " + textContent);
  } catch (error) {
    Logger.log("An error occurred: " + error);
  }
}

function getKey(){

   return PropertiesService.getScriptProperties().getProperty('API_KEY');
}

Backoff

Currently Gemini has an issue with being overloaded so I have implemented Exponential backoff. Which will retry the call until it is able to go though to the AI.

function sendPostRequest(model, prompt, key) {
  // URL to which you want to send the POST request
  var url = "https://generativelanguage.googleapis.com/v1/models/" + model + ":generateContent?key=" + key;

  var part = { "text": prompt };      
  var contents = { "parts": [part] };

  // Request payload
  var payload = { "contents": [contents] }; 

  // Options for the request
  var options = {
    method: "post",
    contentType: "application/json",
    payload: JSON.stringify(payload)
  };

  // Make the POST request
  var response = UrlFetchApp.fetch(url, options);
  
  // Return the response content
  return response.getContentText();
}

function doPostRequestWithExponentialBackoff(model, prompt, key) {
  var maxAttempts = 5; // Maximum number of retry attempts
  var baseDelay = 1000; // Base delay in milliseconds
  var maxDelay = 60000; // Maximum delay in milliseconds
  var backoffFactor = 2; // Backoff factor

  return backoffWithFunctionRetry(function() {
    return sendPostRequest(model, prompt, key);
  }, maxAttempts, baseDelay, maxDelay, backoffFactor);
}

function extractTextFromResponse(responseContent) {
  // Parse the JSON response
  var responseObject = JSON.parse(responseContent);

  // Check if "candidates" array exists and is not empty
  if (responseObject.hasOwnProperty("candidates") && responseObject.candidates.length > 0) {
    // Get the text content from the first candidate
    return responseObject.candidates[0].content.parts[0].text;
  } else {
    return "No text content found in the response.";
  }
}

function backoffWithFunctionRetry(actionFunction, maxAttempts, baseDelay, maxDelay, backoffFactor) {
  for (var attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      var result = actionFunction();
      return result; // Action successful, return result
    } catch (error) {
      if (attempt === maxAttempts) {
        throw new Error("Max number of retry attempts reached. Last error: " + error);
      }

      // Calculate exponential backoff delay
      var delay = Math.min(baseDelay * Math.pow(backoffFactor, attempt - 1), maxDelay);
      Logger.log("Attempt #" + attempt + ": Action failed with error - " + error + ". Retrying in " + delay + " milliseconds.");
      Utilities.sleep(delay);
    }
  }
}

Conclusion

You can test Gemini from Google App script. simply run the Run method above in app script and it will return the response to you.

Please check my article on using A Pro’s Guide Multimodal Magic: Python-Powered Gemini for Creative Breakthroughs


About Linda Lawton

My name is Linda Lawton I have more than 20 years experience working as an application developer and a database expert. I have also been working with Google APIs since 2012 and I have been contributing to the Google .Net client library since 2013. In 2013 I became a a Google Developer Experts for Google Analytics.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.