有了 Vertex AI 服務,在 Apps Script 使用 Vertex AI API 毫不費力。您可以透過這項 API 存取 Gemini 和其他生成式 AI 模型,生成文字和圖像,並輕鬆完成其他大小事。
如要開始使用這項進階服務,請試用快速入門導覽課程。
必要條件
已啟用計費功能的 Google Cloud 專案。如要確認現有專案是否已啟用計費功能,請參閱「確認專案的帳單狀態」。如要建立專案及設定帳單,請參閱「建立 Google Cloud 專案」一文。
在 Google Cloud 控制台中,前往 Cloud 專案並啟用 Vertex AI API:
在 Apps Script 專案中,開啟 Vertex AI 服務。 如需相關步驟,請參閱「進階 Google 服務」。
參考資料
如要進一步瞭解這項服務,請參閱 Vertex AI API 參考說明文件。與 Apps Script 中的所有進階服務一樣,Vertex AI 服務使用的物件、方法和參數,都與公開 API 相同。
程式碼範例
下列程式碼範例使用 Vertex AI API 的第 1 版。
生成文字
這段程式碼範例說明如何提示 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 替換為 Cloud 專案的專案 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);
}