0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

第3回:GAS×Geminiで100行一括処理するAIバッチシステム

0
Posted at

はじめに

第2回では、タスク列を使って「要約」「翻訳」「分類」などのAI処理を切り替えられる仕組みを作成しました。

毎回Apps Scriptエディタから関数を実行するのは少し手間です。

今回は、

  • カスタムメニューの追加
  • メニューからの実行
  • 複数行の一括処理

を実装します。

これで、スプレッドシート上から必要なタイミングでAI処理をまとめて実行できるようになります。


連載記事で完成するスプレッドシート

スクリーンショット 2026-07-14 194423.png


Step1 カスタムメニューを追加する

まずは、スプレッドシートを開いたときにメニューを追加します。

function onOpen() {
  SpreadsheetApp.getUi()
    .createMenu("Gemini操作")
    .addItem("タスクを実行", "executeTasks")
    .addToUi();
}

スプレッドシートを再読み込みすると、メニューバーに

Gemini操作

が追加されます。

ここからAI処理を実行できるようになります。


Step2 Gemini APIを呼び出す関数

第1回で紹介した処理を関数としてまとめます。

function callGeminiAPI(apiKey, prompt) {
  const model = "gemini-2.5-flash";

  const endpoint =
    `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${apiKey}`;

  const requestBody = {
    contents: [{
      parts: [{
        text: prompt
      }]
    }]
  };

  const response = UrlFetchApp.fetch(endpoint, {
    method: "post",
    contentType: "application/json",
    payload: JSON.stringify(requestBody),
    muteHttpExceptions: true
  });

  const result = JSON.parse(response.getContentText());

  if (!result.candidates) {
    throw new Error(response.getContentText());
  }

  return result.candidates[0].content.parts[0].text;
}

Step3 一括処理を実装する

続いて、2行目から最終行までを順番に処理します。

function executeTasks() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const lastRow = sheet.getLastRow();

  const apiKey = PropertiesService.getScriptProperties()
    .getProperty("GEMINI_API_KEY");

  if (!apiKey) {
    SpreadsheetApp.getUi().alert("GEMINI_API_KEYが設定されていません。");
    return;
  }

  for (let row = 2; row <= lastRow; row++) {
    const content = sheet.getRange(row, 1).getValue();
    const task = sheet.getRange(row, 2).getValue();
    const resultCell = sheet.getRange(row, 3);

    // 入力不足や処理済みデータはスキップ
    if (!content || !task || resultCell.getValue()) {
      continue;
    }

    const prompt = `${task}\n\n${content}`;

    try {
      const result = callGeminiAPI(apiKey, prompt);
      resultCell.setValue(result);
    } catch (e) {
      Logger.log(`行 ${row}: ${e.message}`);
    }

    // APIへの連続アクセスを少し抑える
    Utilities.sleep(500);
  }
}

処理の流れ

各行について、次の順番で処理します。

  1. A列(本文)を取得
  2. B列(タスク)を取得
  3. C列に結果があるか確認
  4. 未処理ならGemini APIへ送信
  5. C列へ結果を書き込む

すでに結果が入力されている行はスキップするため、同じデータを何度も処理してAPI料金が発生することを防げます。


メニュー実行にする理由

Apps Scriptには編集時に自動実行する仕組み(onEdit)もあります。

しかし、AI処理を自動実行すると

  • 編集のたびにAPIを呼び出してしまう
  • API利用料金が増える可能性がある
  • 編集中の動作が重くなることがある

といったデメリットがあります。

そのため、必要なタイミングだけメニューから実行する方法が、安全で扱いやすい運用になります。


次回

最終回では、

  • 完成版コード
  • API利用料金を抑える工夫
  • 実際の業務での活用例

を紹介します。


現在、React + FastAPIで教育向けのデータ分析・機械学習プラットフォームを開発しています。

AI・機械学習・Google Apps Script関連の記事も継続して投稿予定です。


0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?