Vertex AI 服務

您可以在 Apps Script 中使用 Vertex AI 服務的 Vertex AI API。您可透過這項 API 存取 Gemini 和其他生成式 AI 模型,生成文字、圖像等內容。

必要條件

  • 已啟用計費功能的 Google Cloud 專案。如要確認現有專案是否已啟用計費功能,請參閱「確認專案的帳單狀態」。如要建立專案及設定帳單,請參閱「建立 Google Cloud 專案」一文。

  • 在 Google Cloud 控制台中,前往 Cloud 專案並啟用 Vertex AI API:

    啟用 API

  • 設定 Apps Script 專案:

參考資料

如要進一步瞭解這項服務,請參閱 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