Skip to content

Generating Text with Gemini Pro in Apps Script

Published on Markdown

Short and sweet snippet for generating text in Apps Script with the Gemini Pro Rest API.

JavaScript
function generateContent(text, API_KEY) {
  const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=${API_KEY}`;

  return JSON.parse(
    UrlFetchApp.fetch(url, {
      method: "POST",
      headers: {
        "content-type": "application/json",
      },
      payload: JSON.stringify({
        contents: [
          {
            parts: [{ text }],
          },
        ],
      }),
    }).getContentText(),
  );
}

And parsing the response:

const response = generateContent("Hello world!", API_KEY);
const text = response.candidates[0].content?.parts[0].text;
Disclaimer: I am a member of the Google Workspace Developer Relations team. The opinions expressed here are my own and do not necessarily represent those of Google.

© 2023 by Justin Poehnelt is licensed under CC BY-SA 4.0