Сервис искусственного интеллекта Vertex

Сервис Vertex AI позволяет использовать API Vertex AI в Apps Script. Этот API предоставляет доступ к Gemini и другим моделям генеративного ИИ для генерации текста, изображений и многого другого.

Чтобы начать пользоваться этим расширенным сервисом, попробуйте воспользоваться функцией быстрого запуска .

Предварительные требования

Ссылка

Для получения дополнительной информации об этом сервисе см. справочную документацию по API Vertex AI . Как и все расширенные сервисы в Apps Script, сервис Vertex AI использует те же объекты, методы и параметры, что и публичный API.

Пример кода

В приведенном ниже примере кода используется версия 1 API Vertex AI.

Сгенерировать текст

Этот пример кода показывает, как заставить модель 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 на идентификатор вашего облачного проекта.

Сгенерируйте текст, используя учетную запись службы.

В следующем примере показано, как сгенерировать текст, пройдя аутентификацию в качестве проекта 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) {
  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);
}