Быстрый старт: Создание текста с помощью Vertex AI

This page explains how to use Google Apps Script's Vertex AI advanced service to prompt the Gemini 2.5 Flash model to generate text.

To learn more about the Vertex AI advanced service, see the reference documentation .

Цели

  • Настройте свою среду.
  • Create an Apps Script project that uses the Vertex AI advanced service.
  • Запустите скрипт для генерации текста.

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

Настройте свою среду

This section explains how to configure and set up your environment in the Google Cloud console and Apps Script.

Включите API Vertex AI в своем облачном проекте.

  1. In the Google Cloud console, open your Google Cloud project and enable the Vertex AI API:

    Включить API

  2. Убедитесь, что вы включаете API в правильном облачном проекте, затем нажмите «Далее» .

  3. Confirm that you're enabling the correct API, then click Enable .

Создайте и настройте свой проект Apps Script.

To create and set up your Apps Script project, complete the following steps:

  1. Перейдите на script.google.com .
  2. Click New project to create an Apps Script project.
  3. В левом верхнем углу нажмите «Безымянный проект» .
  4. Name your script Vertex AI quickstart and click Rename .

Настройте расширенную службу Vertex AI.

To enable the Vertex AI advanced service and set up the code, do the following:

  1. In the script editor, go to Services and click Add a service Значок для добавления услуги .
  2. В выпадающем меню выберите Vertex AI API и нажмите «Добавить» .
  3. Open the Code.gs file and replace its contents with the following code:

    /**
     * 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.

  4. Нажмите «Сохранить». Значок для сохранения проекта .

Протестируйте скрипт

  1. In the script editor, click Run to run the main function.
  2. При появлении запроса авторизуйте выполнение скрипта.
  3. Click Execution log to view the response from Vertex AI.

The Vertex AI service returns a response to the prompt, What is Apps Script in one sentence? .

AI-generated text from Apps Script's Vertex AI advanced service.
Ответ службы Vertex AI в журнале выполнения Apps Script.

For example, the execution log returns a response such as the following:

Response: Google Apps Script is a cloud-based, JavaScript platform that lets you
automate, integrate, and extend Google Workspace applications like Sheets, Docs,
and Gmail.

Уборка

Чтобы избежать списания средств с вашего аккаунта Google Cloud за ресурсы, использованные в этом руководстве, мы рекомендуем удалить проект Cloud.

  1. In the Google Cloud console, go to the Manage resources page. Click Menu > IAM & Admin > Manage Resources .

    Перейдите в Диспетчер ресурсов

  2. In the project list, select the project you want to delete and then click Delete .
  3. In the dialog, type the project ID and then click Shut down to delete the project.

To avoid incurring charges to your Google Cloud account for the resources used in this quickstart, we recommend that you delete the Cloud project.