Vertex AI 服务

借助 Vertex AI 服务,您可以在 Apps 脚本中使用 Vertex AI API。通过此 API,您可以访问 Gemini 和其他生成式 AI 模型,以用于文本生成、图片生成等。

前提条件

参考

如需详细了解此服务,请参阅 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