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

GAS×AI入門 — スプレッドシートでChatGPT APIを動かす方法

0
Last updated at Posted at 2026-08-26

スプレッドシート × AIという発想

ChatGPTは便利ですが、毎回ブラウザを開いて質問を入力するのは面倒です。もっと自動化できないか?

この問いに対する最も手軽な答えの一つが、**Google Apps Script(GAS)**です。

GASは、Googleのサーバー上で動くJavaScriptベースのスクリプト環境です。スプレッドシート、Gmail、Google Docs、Google Calendarなど、Google Workspaceの全サービスをAPIで操作できます。しかも、Googleアカウントがあれば無料で始められます。

GASからChatGPT、Claude、GeminiといったAIのAPIを呼び出し、スプレッドシート上でAIを動かすことができます。

例えば、スプレッドシートに並んだ1,000件の顧客レビューをAIで感情分析し、一括で「ポジティブ」「ネガティブ」「中立」に分類する。英語のメールを受信したら自動的に日本語に翻訳し、返信ドラフトを作成する。アンケートの自由回答をAIで要約し、レポートにまとめて定期的に送信する。これらはすべて、GASとAI APIの組み合わせで実現できます。

3つのAI APIを比較しながら学ぶ

AI APIには、OpenAI(ChatGPT)、Anthropic(Claude)、Google(Gemini)の3つの主要プロバイダーがあります。各APIには得意・不得意があり、用途に応じて使い分けることが実務では重要です。

  • OpenAI(ChatGPT) — 汎用性が高く、日本語の精度が良い。最もシェアが大きい
  • Anthropic(Claude) — 長文処理に強く、文章の要約・分析に優れる
  • Google(Gemini) — 画像理解に強く、Google Workspaceとの親和性が高い

ChatGPT APIをGASから呼び出す基本

最も基本的なパターンは、スプレッドシートのセルに入力された質問に対してChatGPT APIで回答を生成する仕組みです。

function callChatGPT(prompt) {
  const apiKey = PropertiesService.getScriptProperties().getProperty('OPENAI_API_KEY');
  const url = 'https://api.openai.com/v1/chat/completions';
  
  const response = UrlFetchApp.fetch(url, {
    method: 'post',
    headers: {
      'Authorization': 'Bearer ' + apiKey,
      'Content-Type': 'application/json'
    },
    payload: JSON.stringify({
      model: 'gpt-4o-mini',
      messages: [
        { role: 'user', content: prompt }
      ],
      temperature: 0.7
    }),
    muteHttpExceptions: true
  });
  
  const json = JSON.parse(response.getContentText());
  return json.choices[0].message.content;
}

APIキーはスクリプトプロパティに保存するのが安全です。コードに直接書かないように注意してください。

スプレッドシートで一括処理

この関数を応用すれば、スプレッドシートのデータを一括でAI処理できます。

function processBatch() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Reviews');
  const data = sheet.getDataRange().getValues();
  
  for (let i = 1; i < data.length; i++) {
    const review = data[i][0];  // A列のレビュー文
    if (review) {
      const prompt = '以下のレビューの感情を「ポジティブ」「ネガティブ」「中立」のいずれかで分類してください:\n' + review;
      const result = callChatGPT(prompt);
      sheet.getRange(i + 1, 2).setValue(result);  // B列に結果を書き込み
    }
  }
}

1,000件のレビューでも、このスクリプト一つで数分以内に全件分類が完了します。

APIキーの管理

APIキーは絶対にコード内に直接書かないでください。GASでは「スクリプトプロパティ」を使って安全に管理できます。

// スクリプトプロパティに保存(初回のみ)
PropertiesService.getScriptProperties().setProperty('OPENAI_API_KEY', 'sk-...');

// 取得時
const apiKey = PropertiesService.getScriptProperties().getProperty('OPENAI_API_KEY');

3つのAPIの切り替え

GASからはClaude API、Gemini APIも同様に呼び出せます。エンドポイントとリクエスト形式が異なるだけで、基本は同じです。

// Claude API
function callClaude(prompt) {
  const apiKey = PropertiesService.getScriptProperties().getProperty('ANTHROPIC_API_KEY');
  const response = UrlFetchApp.fetch('https://api.anthropic.com/v1/messages', {
    method: 'post',
    headers: {
      'x-api-key': apiKey,
      'anthropic-version': '2023-06-01',
      'Content-Type': 'application/json'
    },
    payload: JSON.stringify({
      model: 'claude-3-5-sonnet-20241022',
      max_tokens: 1000,
      messages: [{ role: 'user', content: prompt }]
    }),
    muteHttpExceptions: true
  });
  return JSON.parse(response.getContentText()).content[0].text;
}

用途に応じてChatGPTとClaudeを使い分けることで、より精度の高いAI処理が可能になります。

まとめ

GASとAI APIの組み合わせにより、スプレッドシート上でAIを動かす自動化が実現できます。この記事では基本的な呼び出し方法を紹介しましたが、実際の書籍では以下の内容もカバーしています:

  • Gmailの自動翻訳・分類
  • Google Docsの要約自動化
  • トリガーを使った定時実行
  • エラーハンドリングとリトライ
  • 3つのAI API(ChatGPT・Claude・Gemini)の比較と使い分け

著者の葉山悠希(はやま ゆうき)です。AI活用と生産性向上の技術書を執筆しています。

『Google Apps Script × AI 実践入門 — スプレッドシートで動かすAIワークフロー』Amazonで購入する

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