The Vertex AI service lets you use the
[Agent Platform API](https://cloud.google.com/vertex-ai/docs/reference/rest) (formerly the Vertex AI API) in
Google Apps Script. This API gives you access to Gemini and other
generative AI models for text generation, image generation, and more.
[Video](https://www.youtube.com/watch?v=SlJGPx_bRC4)

To get started with this advanced service, try the
[quickstart](https://developers.google.com/apps-script/quickstart/vertex-ai).

## Prerequisites

- A Google Cloud project with billing enabled. To check that an existing project
  has billing enabled, see [Verify the billing status of your
  projects](https://cloud.google.com/billing/docs/how-to/verify-billing-enabled).
  To create a project and set up billing, see [Create a
  Google Cloud project](https://developers.google.com/workspace/guides/create-project).

- In the Google Cloud console, go to your Cloud project and enable the
  Agent Platform API (formerly the Vertex AI API):

  [Enable the API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com)
- In your Apps Script project, turn on the Vertex AI service.
  For steps, see
  [Advanced Google services](https://developers.google.com/apps-script/guides/services/advanced#enable).

## Reference

For more information about this service, see the
[Agent Platform API reference documentation](https://docs.cloud.google.com/vertex-ai/docs/reference/rest).
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](https://docs.cloud.google.com/vertex-ai/docs/reference#versions) of
the Agent Platform API.

### Generate text

This sample code shows how to prompt the
[Gemini 2.5 Flash model](https://docs.cloud.google.com/vertex-ai/generative-ai/docs/learn/model-versions#latest-stable)
to generate text. The function returns the output to
Apps Script's [execution log](https://developers.google.com/apps-script/guides/logging).

    /**
     * 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](https://docs.cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects)
of your Cloud project.

#### Generate text using a service account

The following example shows how to generate text by
[authenticating as an Apps Script project using a service account](https://developers.google.com/apps-script/guides/service-account).

    /**
     * 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) {
      const service = getServiceAccountService();

      // 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,
        {},
        // Authenticate with the service account token.
        { Authorization: `Bearer ${service.getAccessToken()}` },
      );

      // Use optional chaining for safe property access
      return response?.candidates?.[0]?.content?.parts?.[0]?.text || 'No response generated.';
    }

    /**
     * Get a new OAuth2 service for a given service account.
     */
    function getServiceAccountService() {
      const serviceAccountKeyString = PropertiesService.getScriptProperties().getProperty('SERVICE_ACCOUNT_KEY');

      if (!serviceAccountKeyString) {
        throw new Error('SERVICE_ACCOUNT_KEY property is not set. Please follow the setup instructions.');
      }

      const serviceAccountKey = JSON.parse(serviceAccountKeyString);

      const CLIENT_EMAIL = serviceAccountKey.client_email;
      const PRIVATE_KEY = serviceAccountKey.private_key;
      const SCOPES = ['https://www.googleapis.com/auth/cloud-platform'];

      return OAuth2.createService('ServiceAccount')
          .setTokenUrl('https://oauth2.googleapis.com/token')
          .setPrivateKey(PRIVATE_KEY)
          .setIssuer(CLIENT_EMAIL)
          .setPropertyStore(PropertiesService.getScriptProperties())
          .setScope(SCOPES);
    }