Categories: Daimto

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

The post Its Free! Gemini API with AppScript free anywhere. first appeared on Daimto.

rssfeeds-admin

Share
Published by
rssfeeds-admin

Recent Posts

‘She’s a Killer’ – Daredevil: Born Again’s Vincent D’Onofrio on Karen Page’s Dark Side

When Daredevil: Born Again debuted last year, many fans weren’t particularly happy with the way…

55 minutes ago

McDonald’s Introduces a ‘Pro Gamer Menu’ With an Arch-Shaped Device That Will Keep You From Going AFK While You Eat, But It’s Only Available in Türkiye

McDonald's has introduced a brand-new Pro Game Menu and an 'Archie' device that will keep…

55 minutes ago

Genius RollerCoaster Tycoon 2 Player Makes Longest Rollercoaster Ever Built, Manipulates Guests Into Staying Just Happy Enough to Ride It for 1.947 x 10²²⁷ Years

A RollerCoaster Tycoon 2 superfan has created what is believed to be the longest rollercoaster…

55 minutes ago

Democratic states sue Trump over mail-in ballot order, joining rush to courts

Baskets of ballots sit at a new ballot processing center in Thurston County, Washington, on…

2 hours ago

Free bus rides in Beloit for Wisconsin primary election on April 6

In a bid to encourage voter turnout for Wisconsin's primary election, the city of Beloit…

2 hours ago

Dari Ripple in South Beloit opens for the season

The Dari Ripple in South Beloit has officially opened its doors for the season.

2 hours ago

This website uses cookies.