Servicio de Vertex AI

El servicio de Vertex AI te permite usar la API de Vertex AI en Apps Script. Esta API te brinda acceso a Gemini y otros modelos de IA generativa para la generación de texto, de imágenes y mucho más.

Para comenzar a usar este servicio avanzado, prueba la guía de inicio rápido.

Requisitos previos

Referencia

Para obtener más información sobre este servicio, consulta la documentación de referencia de la API de Vertex AI. Al igual que todos los servicios avanzados en Apps Script, el servicio de Vertex AI usa los mismos objetos, métodos y parámetros que la API pública.

Código de muestra

El siguiente código de muestra usa la versión 1 de la API de Vertex AI.

Generar texto

En este código de muestra, se muestra cómo solicitarle al modelo Gemini 2.5 Flash que genere texto. La función devuelve el resultado al registro de ejecución de 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.';
}

Reemplaza GOOGLE_CLOUD_PROJECT_ID por el ID del proyecto de tu proyecto de Cloud.

Genera texto con una cuenta de servicio

En el siguiente ejemplo, se muestra cómo generar texto autenticándose como un proyecto de Apps Script con una cuenta de servicio.

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