3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Gemini Pro APIをGAS(Google Apps Script)で利用してみた【サンプルコード】

Last updated at Posted at 2023-12-14

概略

  • 2023年12月13日(日本時間12月14日)に公開されたGemini Pro APIをGASで使ってみました。
  • APIキーの取得方法と、動作するGASサンプルコードを作成しましたので置いておきます。

APIキーの取得方法

Google AI StudioのGet API Keyで、APIキーを取得します。

注意)通常のGoogleアカウントでは問題なく取得できました。私のGoogle Workspaceアカウントでは早期アクセスアプリ へのアクセス権をonにしても利用できませんでした。(早々に利用可能になると思います。)

同意項目は一番目は必須です。2番めはニュースレターの登録、3番目は調査研究参加への招待状が欲しい場合です。
2023-12-14_08h55_15.png

これで得たAPIキーを安全な場所に保存しましょう。

GAS(Google Apps Script)のコード

下記に作成したサンプルコードを示します。

getGeminiProResponse

function fetchApiResponse() {

  const apiKey = "YOUR_API_KEY"; // 実際のAPIキーに置き換えてください
  const questionText = "200文字程度で、地球の大きさについて教えて下さい。"; // 実際の質問テキストに置き換えてください

  let resultText = getGeminiProResponse(apiKey, questionText);
  Logger.log(resultText);

}

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

  const payload = {
    "contents": [{
      "parts": [{
        "text": questionText
      }]
    }]
  };

  const options = {
    "method": "post",
    "contentType": "application/json",
    "payload": JSON.stringify(payload)
  };

  const response = UrlFetchApp.fetch(url, options);
  const jsonResponse = JSON.parse(response.getContentText());

  if (jsonResponse && jsonResponse.candidates && jsonResponse.candidates.length > 0) {
    const answerText = jsonResponse.candidates[0].content.parts[0].text;
    return answerText;
  } else {
    return "回答を取得できませんでした。";
  }
}

実行ログ

2023-12-14_09h18_47.png

問題なく結果が得られました。

API Reference

Gemini Docs and API Reference  |  Google AI for Developers

2025/1 追記

Gemini Pro APIが登場してすぐにひとまず使えるGASコードを書いたので、現在だと動かないかもしれません。

上記のサンプルを元にして、最近の環境でも動作するGASコードの例を書いていただいている記事を見つけましたので、よろしければ参考にしていただくのもいいかと思います。
SlackにRSS配信の要約投稿をLLMでやらせてみた。 | まじ(本気)

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?