Vertex AI の Gemini を GAS (Google Apps Script) から呼び出す
Vertex AI の Gemini を GAS (Google Apps Script) から呼び出す
English follows Japanese.
概要
主なポイントは以下の4点である。
- GAS 拡張サービスの旧称 Vertex AI サービス(Agent Platform API サービス)がそのまま使える
- 名称・並び順に注意(今後の改称にも注意)
- API キーが不要
- 実行者で権限管理が可能
GAS 拡張サービスの利用で、UrlFetchApp を使わずに Gemini Enterprise Agent Platform API を呼び出すことができる。つまり、背後で POST リクエストが行われていることを全く意識せずに、50行程度(コア部分は5行程度)のコードで実装できる。
はじめに
Gemini をプログラムから呼び出す方法はいくつかあるが、AI Studio 等から利用され generativelanguage.googleapis.com というエンドポイントを使う “Gemini API"(名前が紛らわしい)と、(Google Cloud の)Gemini Enterprise Agent Platform API で提供される aiplatform.googleapis.com というエンドポイントを使う “Agent Platform API"(旧称 Vertex AI API)の2種類は良く知られている。
本記事では、GAS (Google Apps Script) から Gemini Enterprise Agent Platform API を UrlFetchApp を「使わずに」呼び出す方法について解説する。つまり、背後で POST リクエストが行われていることを全く意識せずに、50行程度(コア部分は5行程度)のコードで実装できる方法を紹介する。
2026-01-12 のリリースノート にあるように、GAS の拡張サービスとして Vertex AI サービスが追加された(参考: Google Apps ScriptにVertex AI Serviceが追加されました)。これにより、GAS から Gemini Enterprise Agent Platform API を呼び出すことが可能になった。
当時は Vertex AI API として拡張サービスが提供されていた cf. https://officeforest.org/wp/wp-content/uploads/2026/01/G-i51rQbQAEbb1O.webp が、2026-08-16 現在では (Gemini Enterprise) Agent Platform API に改称されており、 “A" のところに並んでいる。このため、解説記事を書くことにした。
“Gemini API" と “Agent Platform API" の違いについては、備考 で少し触れているので、そちらを参照してほしい。
導入方法
Google Cloud のプロジェクト作成や API(サービス)の有効化については、手順を省略する。解説記事は豊富なので、皆さんで調べてほしい。
まずは以下の準備が必要である:
- Google Cloud Project を作成する
- Gemini Enterprise Agent Platform API を有効化する
作成後、プロジェクト ID を控えておく。後で GAS のスクリプト プロパティに設定する。
続いて、GAS の環境準備を行う。スプレッドシートをコンテナとする GAS プロジェクトを作成する。
- スプレッドシートを作成する
- 子シート名(シート1)を “gemini" にする
- 拡張機能メニューから Apps Script を開く
- サービスから Agent Platform API を “VertexAI" という名前で追加する ※ A のところにある
- 「ファイル」から「スクリプト」を追加し、"main" という名前にする
- コードを貼り付ける(後述コード)
- スクリプト プロパティに
PROJECT_ID,REGION,MODEL_NAMEを設定する - スプレッドシートをリロードする
- シートの A2, A3 に「Gemini に聞きたい内容」を入力しておく
本記事最大のポイントは “A" のところに VertexAI が並んでいる 点に注意することである。GAS 拡張サービスの発表当時は Vertex AI API として拡張サービスが提供されていた cf. https://officeforest.org/wp/wp-content/uploads/2026/01/G-i51rQbQAEbb1O.webp が、2026-08-16 現在では (Gemini Enterprise) Agent Platform API に改称されているためだ。本記事を書くに至った最大の動機はここである。今後もサービス名の改称があるかもしれないが、同様にメニュー上の位置が変わるかもしれないので、ここに記しておく。注意してほしい。
実行方法
onOpen 関数によってメニューが追加される仕組みにしてある。
スプレッドシートをリロードする。
- メニューが追加されるので選択
- 認証を許可する(初回実行時のみ)
- ポップアップが出るかもしれないが先に進む
- 選択して右下の続行
- 出力が埋まる
コード
このサンプルコードでは、シートの A2, A3 セルに書かれたプロンプトを、Gemini API に渡して、結果を B2, B3 セルに出力するようにしている。
GitHub のリポジトリ gas_vertexai_gemini/dist/index.js に同じファイルを置いているので、そちらも参考にしてほしい。
ASIDE(GAS の開発フレームワーク)で初期化したプロジェクトとして TypeScript 版もあるので、TypeScript で書きたい人はそちらを参考にしてほしい。
同様のサンプルコードは、公式ドキュメントや以下の記事でも紹介されているため、適宜参考にしてほしい。
- Vertex AI サービス
- 通常のリクエスト (直後には、添付ファイルを付けてリクエストする方法や、Claude4 を呼び出す方法も紹介されている!)
function callVertexAiGenerateContent(prompt) {
const scriptProperties = PropertiesService.getScriptProperties();
const projectId =
scriptProperties.getProperty('PROJECT_ID') ??
scriptProperties.getProperty('projectId') ??
'';
const region =
scriptProperties.getProperty('REGION') ??
scriptProperties.getProperty('region') ??
'global';
const modelName =
scriptProperties.getProperty('MODEL_NAME') ??
scriptProperties.getProperty('modelName') ??
'gemini-3.7-flash';
if (!projectId) {
throw new Error('Project ID is not configured in Script Properties.');
}
const model = `projects/${projectId}/locations/${region}/publishers/google/models/${modelName}`;
const payload = {
contents: [
{
role: 'user',
parts: [
{
text: prompt,
},
],
},
],
};
const response = VertexAI.Endpoints.generateContent(payload, model);
return (
response?.candidates?.[0]?.content?.parts?.[0]?.text ??
'No response from Gemini API'
);
}
function runGeminiAPI() {
const sheet = SpreadsheetApp.getActiveSheet();
const promptA2 = String(sheet.getRange('A2').getValue() ?? '');
if (promptA2) {
try {
const resultB2 = callVertexAiGenerateContent(promptA2);
sheet.getRange('B2').setValue(resultB2);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.error(`Failed to call Vertex AI: ${message}`);
}
}
const promptA3 = String(sheet.getRange('A3').getValue() ?? '');
if (promptA3) {
try {
const resultB3 = callVertexAiGenerateContent(promptA3);
sheet.getRange('B3').setValue(resultB3);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.error(`Failed to call Vertex AI: ${message}`);
}
}
}
function onOpen() {
const ui = SpreadsheetApp.getUi();
ui.createMenu('Gemini')
.addItem('Read sheet and invoke Gemini API and write', runGeminiAPI.name)
.addToUi();
}
備考
generativelanguage.googleapis.com と aiplatform.googleapis.com は違うものである。前者は Google の AI Studio などから利用される Gemini API で、主に API キーを使って利用する。OAuth2 の導入も可能であるが面倒である。
一方、後者の aiplatform.googleapis.com は、AI Platform API から Vertex AI API に改称され、更に、Gemini Enterprise Agent Platform API に改称された。こちらは、GAS 組み込みの認証機能を使って呼び出せるため、別途 OAuth2 の設定等を行う必要がない。GAS × Vertex AI (Gemini) で画像解析スクリプトを作る や APIキー不要!GASからOAuth認証でGeminiを呼び出す は UrlFetchApp を使った方法であるが、これすらも使う必要がない。なお API キーで呼び出すことも可能であるが、言及に留め、細かい方法は省略する。
是非、UrlFetchApp を「使わずに」利用してほしい。
なお、VertexAI.Endpoints.generateContent(payload, model) が「一般的なクライアントライブラリのどことどう同じか」を簡単に調べてみたのだが、見つけることができなかった。
REST API のリファレンスは以下の通りである。
https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/rest
https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/rest#rest-resource:-v1.projects.locations.endpoints
https://ai.google.dev/api/all-methods?hl=ja#service-endpoint
Interactions API は Vertex AI (Gemini Enterprise Agent Platform) 側では、2026-08-16 現在まだ開発中の様子である。こちらが使えるようになったら続報を書きたいと思う。
https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/models/interactions-api
https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/rest/v1beta1/projects.locations.interactions
まとめ
本記事では、GAS (Google Apps Script) の拡張サービスを利用して、Vertex AI の Gemini (Gemini Enterprise Agent Platform API) を呼び出す方法を解説した。
従来の UrlFetchApp を用いた HTTP リクエストや面倒な OAuth2 認証・API キー管理を行わずに、拡張サービスを追加するだけでわずか数行のコードから安全かつ直感的に Gemini を呼び出すことができる。
最大の注意点は、拡張サービスの名称が Agent Platform API に改称されたことにより、サービスの追加一覧での並び順が “A" の位置になっている点である(識別子は VertexAI のまま)。
スプレッドシートをはじめとする Google Workspace と Gemini の連携がこれまで以上に手軽になるため、ぜひ本記事の手順で試してみてほしい。
参考
- Google Apps Script Release Notes (January 12, 2026)
- Google Apps Script Advanced Services – Vertex AI サービス
- Google Apps ScriptにVertex AI Serviceが追加されました – Office Forest
- GitHub: takotakot/misc (サンプルコード)
- Gemini Enterprise Agent Platform API REST Reference
- GAS × Vertex AI (Gemini) で画像解析スクリプトを作る – Zenn
- APIキー不要!GASからOAuth認証でGeminiを呼び出す – Zenn
Calling Vertex AI Gemini from Google Apps Script (GAS)
Overview
The key points are the following four:
- The GAS advanced service formerly called Vertex AI Service (now Agent Platform API Service) can be used as-is
- Pay attention to the name and alphabetical order (and to future renames)
- No API key required
- Access control is managed by the executing user’s identity
By using the GAS advanced service, you can call the Gemini Enterprise Agent Platform API without using UrlFetchApp. In other words, you can implement this in about 50 lines of code (around 5 lines for the core logic) without having to worry about the underlying POST requests.
Introduction
There are several ways to call Gemini programmatically. Two well-known approaches are the “Gemini API" (a confusingly named API) that uses the generativelanguage.googleapis.com endpoint accessed from AI Studio and similar tools, and the “Agent Platform API" (formerly Vertex AI API) provided by the (Google Cloud) Gemini Enterprise Agent Platform API that uses the aiplatform.googleapis.com endpoint.
This article explains how to call the Gemini Enterprise Agent Platform API from GAS (Google Apps Script) without using UrlFetchApp. You will see how to implement it with only about 50 lines of code (around 5 lines for the core logic), completely abstracting away the underlying HTTP requests.
As noted in the January 12, 2026 release notes, the Vertex AI Service was added as a GAS advanced service (see also: Vertex AI Service added to Google Apps Script). This made it possible to call the Gemini Enterprise Agent Platform API from GAS.
At that time, the advanced service was listed as “Vertex AI API" (cf. https://officeforest.org/wp/wp-content/uploads/2026/01/G-i51rQbQAEbb1O.webp), but as of 2026-08-16, it has been renamed to “(Gemini Enterprise) Agent Platform API" and is sorted under “A". This prompted me to write this article.
For the difference between the “Gemini API" and the “Agent Platform API," see the Notes section below.
How to Set Up
Detailed steps for creating a Google Cloud project and enabling the API (service) are omitted here, as plenty of comprehensive guides are available online.
First, the following preparation is required:
- Create a Google Cloud Project
- Enable the Gemini Enterprise Agent Platform API
After creation, make a note of the project ID. You will set it in the GAS script properties later.
Next, prepare the GAS environment. Create a GAS project bound to a spreadsheet.
- Create a spreadsheet
- Rename the sheet tab (Sheet1) to “gemini"
- Open Apps Script from the Extensions menu
- Under Services, add the Agent Platform API with the identifier “VertexAI" (Note: It is listed under “A")
- Add a script file from “File" and name it “main"
- Paste the code (see Code below)
- Set
PROJECT_ID,REGION, andMODEL_NAMEin the script properties - Reload the spreadsheet
- Enter your prompts for Gemini in cells A2 and A3
The most important point of this article is to note that the service is sorted under “A" (as “Agent Platform API"). When the GAS advanced service was first announced, it was listed as “Vertex AI API" (cf. https://officeforest.org/wp/wp-content/uploads/2026/01/G-i51rQbQAEbb1O.webp), but as of 2026-08-16, it has been renamed to “(Gemini Enterprise) Agent Platform API". This was the primary motivation for writing this article. The service may be renamed again in the future, and its alphabetical position in the list may shift accordingly, so please keep this in mind.
How to Run
The onOpen function adds a custom menu to the spreadsheet.
Reload the spreadsheet.
- A menu is added; select it
- Grant the required permissions when prompted (first run only)
- If an authorization warning popup appears, proceed through it
- Select your account and click “Continue" / “Allow" in the bottom right
- The output cells (B2, B3) will be populated with Gemini’s responses
Code
In this sample code, prompts written in cells A2 and A3 of the sheet are passed to the Gemini API, and the results are output to cells B2 and B3.
The same file is available in the GitHub repository at gas_vertexai_gemini/dist/index.js, so please refer to it as well.
There is also a TypeScript version in a project initialized with ASIDE (a development framework for GAS), so if you prefer to write in TypeScript, please refer to that.
Similar sample code is also introduced in the official documentation and the following articles:
- Vertex AI Service
- Standard request (immediately after, methods for making requests with attachments and for calling Claude 4 are also introduced!)
function callVertexAiGenerateContent(prompt) {
const scriptProperties = PropertiesService.getScriptProperties();
const projectId =
scriptProperties.getProperty('PROJECT_ID') ??
scriptProperties.getProperty('projectId') ??
'';
const region =
scriptProperties.getProperty('REGION') ??
scriptProperties.getProperty('region') ??
'global';
const modelName =
scriptProperties.getProperty('MODEL_NAME') ??
scriptProperties.getProperty('modelName') ??
'gemini-3.7-flash';
if (!projectId) {
throw new Error('Project ID is not configured in Script Properties.');
}
const model = `projects/${projectId}/locations/${region}/publishers/google/models/${modelName}`;
const payload = {
contents: [
{
role: 'user',
parts: [
{
text: prompt,
},
],
},
],
};
const response = VertexAI.Endpoints.generateContent(payload, model);
return (
response?.candidates?.[0]?.content?.parts?.[0]?.text ??
'No response from Gemini API'
);
}
function runGeminiAPI() {
const sheet = SpreadsheetApp.getActiveSheet();
const promptA2 = String(sheet.getRange('A2').getValue() ?? '');
if (promptA2) {
try {
const resultB2 = callVertexAiGenerateContent(promptA2);
sheet.getRange('B2').setValue(resultB2);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.error(`Failed to call Vertex AI: ${message}`);
}
}
const promptA3 = String(sheet.getRange('A3').getValue() ?? '');
if (promptA3) {
try {
const resultB3 = callVertexAiGenerateContent(promptA3);
sheet.getRange('B3').setValue(resultB3);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.error(`Failed to call Vertex AI: ${message}`);
}
}
}
function onOpen() {
const ui = SpreadsheetApp.getUi();
ui.createMenu('Gemini')
.addItem('Read sheet and invoke Gemini API and write', runGeminiAPI.name)
.addToUi();
}
Notes
generativelanguage.googleapis.com and aiplatform.googleapis.com are two distinct endpoints. The former is the Gemini API used from Google AI Studio and similar tools, and is mainly accessed using an API key (while setting up OAuth2 is possible, it is fairly cumbersome).
On the other hand, aiplatform.googleapis.com evolved from AI Platform API to Vertex AI API, and was further renamed to Gemini Enterprise Agent Platform API. This can be called using GAS’s built-in authentication, completely eliminating the need to configure custom OAuth2 flows or manage API keys. Articles such as Building an image analysis script with GAS × Vertex AI (Gemini) and No API key needed! Calling Gemini from GAS with OAuth authentication describe methods using UrlFetchApp, but with the advanced service, even UrlFetchApp is unnecessary. (Note: While calling it via an API key is technically possible, that method is omitted here.)
Please do take advantage of calling it without using UrlFetchApp.
I looked into how VertexAI.Endpoints.generateContent(payload, model) maps to the standard Google Cloud client libraries / SDK methods, but could not find a direct 1-to-1 counterpart in the documentation.
The REST API references are as follows:
https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/rest
https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/rest#rest-resource:-v1.projects.locations.endpoints
https://ai.google.dev/api/all-methods?hl=ja#service-endpoint
As of 2026-08-16, the Interactions API still appears to be under active development on the Vertex AI (Gemini Enterprise Agent Platform) side. I plan to write a follow-up article once it becomes available.
https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/models/interactions-api
https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/rest/v1beta1/projects.locations.interactions
Conclusion
This article explained how to call Vertex AI Gemini (Gemini Enterprise Agent Platform API) using the advanced service in GAS (Google Apps Script).
Without resorting to manual HTTP requests via UrlFetchApp, cumbersome OAuth2 setup, or API key management, you can call Gemini safely and intuitively with just a few lines of code simply by enabling the advanced service.
The most important caveat is that, because the advanced service was renamed to Agent Platform API, it is now sorted under “A" in the Services list (even though the default identifier remains VertexAI).
Because integration between Google Workspace products — starting with Spreadsheets — and Gemini has become easier than ever, I encourage you to try it out following the steps in this article.
References
- Google Apps Script Release Notes (January 12, 2026)
- Google Apps Script Advanced Services – Vertex AI Service
- Vertex AI Service added to Google Apps Script – Office Forest
- GitHub: takotakot/misc (sample code)
- Gemini Enterprise Agent Platform API REST Reference
- Building an image analysis script with GAS × Vertex AI (Gemini) – Zenn
- No API key needed! Calling Gemini from GAS with OAuth authentication – Zenn
ディスカッション
コメント一覧
まだ、コメントがありません