Vertex AI service

The Vertex AI service lets you use the Vertex AI API in Apps Script. This API gives you access to Gemini and other generative AI models for text generation, image generation, and more.

Prerequisites

Reference

For more information about this service, see the Vertex AI API reference documentation. Like all advanced services in Apps Script, the Vertex AI service uses the same objects, methods, and parameters as the public API.

Sample code

The following sample code uses version 1 of the Vertex AI API.

Generate text

This sample code shows how to prompt the Gemini 2.5 Flash model to generate text. The function returns the output to Apps Script's execution log.

/**
 * 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.';
}

Replace GOOGLE_CLOUD_PROJECT_ID with the project ID of your Cloud project.