Apps Script公式リファレンス: Apps Script Reference |障害・課題追跡: IssueTracker |Google Workspace: Status Dashboard - Summary

2024年5月19日日曜日

GeminiのAPIをApps Scriptで利用したい - Using Gemini API in Apps Script


Gemini API を Google Apps Script で利用する手順について、公式リファレンスを参照しながら書いていきます。
I will write about the steps to use the Gemini API in Google Apps Script, referencing the official documentation.

今回の手順 - Procedures

STEP 1: API keyを取得する - Get API key
STEP 2: curlでAPI keyを試す - Test API key with curl
STEP 3: REST API を試す- Test REST API


APIの利用料金について
About API usage fees

2024年5月30日から従量課金が始まるようです。
It appears that a pay-as-you-go pricing model will start from May 30, 2024.



STEP 1: API keyを取得する - Get API key


Get an API key


Google AI Studio: https://aistudio.google.com/


Continue


Get API key


Create API key


Got it


Create API key in new project



Copy


STEP 2: curlでAPI keyを試す - Test API key with curl



下の方で試してみる
I tried it out with the second curl command above.

以下の ${API_KEY} 部分に、上記で取得した API key を入れます。
Replace the ${API_KEY} in below to the API key generated above.

     -curl -H 'Content-Type: application/json' \
     -H "x-goog-api-key: ${API_KEY}" \
     -d '{"contents":[
            {"role": "user",
              "parts":[{"text": "Give me five subcategories of jazz?"}]}]}' \
     "https://generativelanguage.googleapis.com/v1/models/gemini-pro:generateContent"


実行結果
Execution results

{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "1. Bebop\n2. Swing\n3. Cool jazz\n4. Modern jazz\n5. Free jazz"
          }
        ],
        "role": "model"
      },
      "finishReason": "STOP",
      "index": 0,
      "safetyRatings": [
        {
          "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
          "probability": "NEGLIGIBLE"
        },
        {
          "category": "HARM_CATEGORY_HATE_SPEECH",
          "probability": "NEGLIGIBLE"
        },
        {
          "category": "HARM_CATEGORY_HARASSMENT",
          "probability": "NEGLIGIBLE"
        },
        {
          "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
          "probability": "NEGLIGIBLE"
        }
      ]
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 9,
    "candidatesTokenCount": 23,
    "totalTokenCount": 32
  }
}


STEP 3: REST API を試す- Test REST API


Quickstart: Get started with Gemini using the REST API 


Gemini and Content based APIs


上記を参考に、実行するコードを以下に書いてみました。
Based on the above information, I have written the following code to execute.


Google Apps Script



Code.gs
function runGeminiApi() {
const apiKey = getProp("apiKey");

const payload = {
"contents": [{
"parts":[{
"text": "Write a story about a magic backpack."
}]
}]
};

const options = {
"method": "POST",
"headers": {
"x-goog-api-key": apiKey,
"Content-Type": "application/json"
},
"payload": JSON.stringify(payload)
};

const url = "https://generativelanguage.googleapis.com/v1/models/gemini-pro:generateContent";
const response = UrlFetchApp.fetch(url, options);
Logger.log(response);
const responseText= JSON.parse(response).candidates[0].content.parts[0].text;
Logger.log(responseText);
}

function getProp(key) {
return PropertiesService.getScriptProperties().getProperty(key);
}



API keyはスクリプト プロパティにapiKeyとして保存しておきます。
Store the API key in a script property named "apiKey".


実行結果

Write a story about a magic backpack.というtextを送ると、以下のような創作物語を作ってくれました。
In response to my request, it generated the following creative story:

Logger.log(response) で、response全体はこのように取得できました。
The entire response is as follows:
{ "candidates": [ { "content": { "parts": [ { "text": "In the quaint little town of Willow Creek, there lived a young girl named Anya. Her days were filled with the ordinary routine of school and chores, until fate intervened in the form of a peculiar backpack.\n\nAs Anya ambled home from school one afternoon, her gaze fell upon a peculiar object lying beneath a towering oak tree. Curiosity sparked within her, and she approached cautiously. The backpack lay open, revealing a vibrant tapestry of colors and twinkling baubles.\n\nUpon lifting the straps, Anya felt a surge of warmth and energy coursing through her body. To her astonishment, the backpack shimmered and grew lighter, as if suspended by an invisible force. With trembling hands, she fastened it upon her shoulders and embarked on the journey home.\n\nAs she walked, Anya discovered the backpack's extraordinary powers. With each step, it emitted a gentle hum that seemed to dispel her weariness. The heavy textbooks she carried seemed to vanish into thin air, leaving her feeling light and carefree.\n\nUpon reaching her doorstep, Anya was greeted by her bewildered parents. As she opened the backpack to retrieve her belongings, a cascade of glittering sparkles filled the room. To their amazement, the backpack had transformed into a veritable treasure chest, filled with delicious treats, exotic toys, and priceless trinkets.\n\nWord of Anya's magical backpack spread throughout Willow Creek like wildfire. Children begged her to share its wonders, and adults marveled at its ability to lighten their burdens. Anya became known as the \"Guardian of the Backpack,\" using its powers to bring joy and laughter to all who crossed her path.\n\nBut with great power came great responsibility. Anya realized that the backpack's magic could be used for both good and evil. She made a solemn vow to safeguard its secrets and use its powers only for worthy purposes.\n\nAnd so, the legend of the magical backpack lived on in Willow Creek for generations to come, a testament to the transformative power of imagination and the indomitable spirit of a young girl who dared to embrace the extraordinary." } ], "role": "model" }, "finishReason": "STOP", "index": 0, "safetyRatings": [ { "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "probability": "NEGLIGIBLE" }, { "category": "HARM_CATEGORY_HATE_SPEECH", "probability": "NEGLIGIBLE" }, { "category": "HARM_CATEGORY_HARASSMENT", "probability": "NEGLIGIBLE" }, { "category": "HARM_CATEGORY_DANGEROUS_CONTENT", "probability": "NEGLIGIBLE" } ] } ], "usageMetadata": { "promptTokenCount": 8, "candidatesTokenCount": 408, "totalTokenCount": 416 } }


Logger.log(responseText)で、textだけを抽出するとこのように取得できました。
Extracting only the "text", it is as follows:
In the quaint little town of Willow Creek, there lived a young girl named Anya. Her days were filled with the ordinary routine of school and chores, until fate intervened in the form of a peculiar backpack. As Anya ambled home from school one afternoon, her gaze fell upon a peculiar object lying beneath a towering oak tree. Curiosity sparked within her, and she approached cautiously. The backpack lay open, revealing a vibrant tapestry of colors and twinkling baubles. Upon lifting the straps, Anya felt a surge of warmth and energy coursing through her body. To her astonishment, the backpack shimmered and grew lighter, as if suspended by an invisible force. With trembling hands, she fastened it upon her shoulders and embarked on the journey home. As she walked, Anya discovered the backpack's extraordinary powers. With each step, it emitted a gentle hum that seemed to dispel her weariness. The heavy textbooks she carried seemed to vanish into thin air, leaving her feeling light and carefree. Upon reaching her doorstep, Anya was greeted by her bewildered parents. As she opened the backpack to retrieve her belongings, a cascade of glittering sparkles filled the room. To their amazement, the backpack had transformed into a veritable treasure chest, filled with delicious treats, exotic toys, and priceless trinkets. Word of Anya's magical backpack spread throughout Willow Creek like wildfire. Children begged her to share its wonders, and adults marveled at its ability to lighten their burdens. Anya became known as the "Guardian of the Backpack," using its powers to bring joy and laughter to all who crossed her path. But with great power came great responsibility. Anya realized that the backpack's magic could be used for both good and evil. She made a solemn vow to safeguard its secrets and use its powers only for worthy purposes. And so, the legend of the magical backpack lived on in Willow Creek for generations to come, a testament to the transformative power of imagination and the indomitable spirit of a young girl who dared to embrace the extraordinary.


Pricing


以下の情報は今後変更になる可能性もあるため、APIの利用料については公式サイトで確認してください。
The information below may change in the future, so please check the official website for API pricing details.


2024/04/18現在
(As of April 18, 2024)


2024/05/19現在
(As of May 19, 2024)


上記で作成したAPI keyはFree of chargeになっており、請求の対象にはなっていないようです。
The API key generated above is currently free of charge and does not appear to be subject to billing.

Plan > Set up Billing 
This project has no billing account


Reference

Gemini > Model variants

Latest post

Google Apps Scriptの障害時はIssueTrackerを見てみる - Incidents for Apps Script are reported on Issue Tracker

IssueTracker > Apps Script issues https://issuetracker.google.com/savedsearches/566234 Google Apps Scriptの障害時は IssueTracker に課題が上がっていることが...