Vertex AI Service
Stay organized with collections
Save and categorize content based on your preferences.
The Vertex AI service lets you use the Agent Platform API (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.
To get started with this advanced service, try the quickstart.
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. To create a project and set up billing, see Create a Google Cloud project.
In the Google Cloud console, go to your Cloud project and enable the Agent Platform API (formerly the Vertex AI API):
In your Apps Script project, turn on the Vertex AI service. For steps, see Advanced Google services.
Reference
For more information about this service, see the Agent Platform API reference documentation. 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 of the Agent Platform API.
Generate text
This sample code shows how to prompt the Gemini 2.5 Flash model to generate text. The function returns the output to Apps Script's execution log.
/**
* Main entry point to test the Vertex AI integration.
*/
functionmain(){
constprompt='What is Apps Script in one sentence?';
try{
constresponse=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.
*/
functioncallVertexAI(prompt){
// Configuration
constprojectId='GOOGLE_CLOUD_PROJECT_ID';
constregion='us-central1';
constmodelName='gemini-2.5-flash';
constmodel=`projects/${projectId}/locations/${region}/publishers/google/models/${modelName}`;
constpayload={
contents:[{
role:'user',
parts:[{
text:prompt
}]
}],
generationConfig:{
temperature:0.1,
maxOutputTokens:2048
}
};
// Execute the request using the Vertex AI Advanced Service
constresponse=VertexAI.Endpoints.generateContent(payload,model);
// Use optional chaining for safe property access
returnresponse?.candidates?.[0]?.content?.parts?.[0]?.text||'No response generated.';
}
Replace GOOGLE_CLOUD_PROJECT_ID with the
project ID
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.
/**
* Main entry point to test the Vertex AI integration.
*/
functionmain(){
constprompt='What is Apps Script in one sentence?';
try{
constresponse=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.
*/
functioncallVertexAI(prompt){
constservice=getServiceAccountService();
// Configuration
constprojectId='GOOGLE_CLOUD_PROJECT_ID';
constregion='us-central1';
constmodelName='gemini-2.5-flash';
constmodel=`projects/${projectId}/locations/${region}/publishers/google/models/${modelName}`;
constpayload={
contents:[{
role:'user',
parts:[{
text:prompt
}]
}],
generationConfig:{
temperature:0.1,
maxOutputTokens:2048
}
};
// Execute the request using the Vertex AI Advanced Service
constresponse=VertexAI.Endpoints.generateContent(
payload,
model,
{},
// Authenticate with the service account token.
{Authorization:`Bearer ${service.getAccessToken()}`},
);
// Use optional chaining for safe property access
returnresponse?.candidates?.[0]?.content?.parts?.[0]?.text||'No response generated.';
}
/**
* Get a new OAuth2 service for a given service account.
*/
functiongetServiceAccountService(){
constserviceAccountKeyString=PropertiesService.getScriptProperties().getProperty('SERVICE_ACCOUNT_KEY');
if(!serviceAccountKeyString){
thrownewError('SERVICE_ACCOUNT_KEY property is not set. Please follow the setup instructions.');
}
constserviceAccountKey=JSON.parse(serviceAccountKeyString);
constCLIENT_EMAIL=serviceAccountKey.client_email;
constPRIVATE_KEY=serviceAccountKey.private_key;
constSCOPES=['https://www.googleapis.com/auth/cloud-platform'];
returnOAuth2.createService('ServiceAccount')
.setTokenUrl('https://oauth2.googleapis.com/token')
.setPrivateKey(PRIVATE_KEY)
.setIssuer(CLIENT_EMAIL)
.setPropertyStore(PropertiesService.getScriptProperties())
.setScope(SCOPES);
}