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.
- Запустите скрипт для генерации текста.
Предварительные требования
- Проект Google Cloud с включенной оплатой. Чтобы проверить, включена ли оплата в существующем проекте, см. раздел «Проверка статуса оплаты ваших проектов ». Чтобы создать проект и настроить оплату, см. раздел «Создание проекта Google Cloud» .
Настройте свою среду
This section explains how to configure and set up your environment in the Google Cloud console and Apps Script.
Включите API Vertex AI в своем облачном проекте.
In the Google Cloud console, open your Google Cloud project and enable the Vertex AI API:
Убедитесь, что вы включаете API в правильном облачном проекте, затем нажмите «Далее» .
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:
- Перейдите на script.google.com .
- Click New project to create an Apps Script project.
- В левом верхнем углу нажмите «Безымянный проект» .
- 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:
- In the script editor, go to Services and click Add a service
.
- В выпадающем меню выберите Vertex AI API и нажмите «Добавить» .
Open the
Code.gsfile 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_IDwith the project ID of your Cloud project.Нажмите «Сохранить».
.
Протестируйте скрипт
- In the script editor, click Run to run the
mainfunction. - При появлении запроса авторизуйте выполнение скрипта.
- 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? .

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.
- In the Google Cloud console, go to the Manage resources page. Click Menu > IAM & Admin > Manage Resources .
- In the project list, select the project you want to delete and then click Delete .
- 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.
Связанные темы
- Расширенная сервисная документация Vertex AI
- Документация платформы Vertex AI
- Посмотреть галерею примеров Google Workspace AI