借助 Vertex AI 服务,您可以在 Apps 脚本中使用 Vertex AI API。通过此 API,您可以访问 Gemini 和其他生成式 AI 模型,以用于文本生成、图片生成等。
如需开始使用这项高级服务,请尝试快速入门。
前提条件
启用了结算功能的 Google Cloud 项目。如需检查现有项目是否已启用结算功能,请参阅验证项目的结算状态。 如需创建项目并设置结算,请参阅创建 Google Cloud 项目。
在 Google Cloud 控制台中,前往您的 Cloud 项目并启用 Vertex AI API:
在您的 Apps 脚本项目中,启用 Vertex AI 服务。 如需了解具体步骤,请参阅高级 Google 服务。
参考
如需详细了解此服务,请参阅 Vertex AI API 参考文档。与 Apps 脚本中的所有高级服务一样,Vertex AI 服务使用的对象、方法和参数均与公共 API 相同。
示例代码
以下示例代码使用 Vertex AI API 的版本 1。
生成文本
此示例代码展示了如何提示 Gemini 2.5 Flash 模型生成文本。该函数会将输出返回到 Apps 脚本的执行日志。
/**
* 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。