Vertex AI サービスを使用すると、Apps Script で Vertex AI API を使用できます。この API を使用すると、テキスト生成や画像生成などの Gemini やその他の生成 AI モデルにアクセスできます。
前提条件
課金を有効にした Google Cloud プロジェクト。既存のプロジェクトで課金が有効になっていることを確認するには、プロジェクトの課金ステータスを確認するをご覧ください。プロジェクトを作成して課金管理を設定するには、Google Cloud プロジェクトを作成するをご覧ください。
Google Cloud コンソールで、Cloud プロジェクトに移動して Vertex AI API を有効にします。
Apps Script プロジェクトを構成します。
- Vertex AI サービスを有効にします。手順については、高度な Google サービスをご覧ください。
- プロジェクト設定で、Cloud プロジェクトを追加します。
リファレンス
このサービスの詳細については、Vertex AI API リファレンス ドキュメントをご覧ください。Apps Script のすべての高度なサービスと同様に、Vertex AI サービスでは、公開 API と同じオブジェクト、メソッド、パラメータを使用します。
サンプルコード
次のサンプルコードでは、Vertex AI API のバージョン 1 を使用します。
テキストを生成
このサンプルコードは、Gemini 2.5 Flash モデルにテキストを生成するようにプロンプトする方法を示しています。この関数は、Apps Script の実行ログに出力を返します。
/**
* Main entry point to test the Vertex AI integration.
*/
function main() {
const prompt = 'What is Apps Script in one sentence?';
try {
const response = callVertexAI(prompt);
console.log(`Response: ${response}`);
} catch (error) {
console.error(`Failed to call Vertex AI: ${error.message}`);
}
}
/**
* Calls the Vertex AI Gemini model.
*
* @param {string} prompt - The user's input prompt.
* @return {string} The text generated by the model.
*/
function callVertexAI(prompt) {
// Configuration
const projectId = 'GOOGLE_CLOUD_PROJECT_ID';
const region = 'us-central1';
const modelName = 'gemini-2.5-flash';
const model = `projects/${projectId}/locations/${region}/publishers/google/models/${modelName}`;
const payload = {
contents: [{
role: 'user',
parts: [{
text: prompt
}]
}],
generationConfig: {
temperature: 0.1,
maxOutputTokens: 2048
}
};
// Execute the request using the Vertex AI Advanced Service
const response = VertexAI.Endpoints.generateContent(payload, model);
// Use optional chaining for safe property access
return response?.candidates?.[0]?.content?.parts?.[0]?.text || 'No response generated.';
}
GOOGLE_CLOUD_PROJECT_ID は、Cloud プロジェクトのプロジェクト ID に置き換えます。