Dịch vụ Vertex AI

truy cập vào Gemini và các mô hình AI tạo sinh khác.

Dịch vụ Vertex AI cho phép bạn sử dụng Vertex AI API trong Google Apps Script. API này cấp cho bạn quyền truy cập vào Gemini và các mô hình AI tạo sinh khác để tạo văn bản, tạo hình ảnh và nhiều tính năng khác.

Để bắt đầu sử dụng dịch vụ nâng cao này, hãy thử hướng dẫn bắt đầu nhanh.

Điều kiện tiên quyết

Tài liệu tham khảo

Để biết thêm thông tin về dịch vụ này, hãy xem tài liệu tham khảo API của Vertex AI. Giống như tất cả các dịch vụ nâng cao trong Apps Script, dịch vụ Vertex AI sử dụng cùng các đối tượng, phương thức và tham số như API công khai.

Mã mẫu

Mã mẫu sau đây sử dụng phiên bản 1 của Vertex AI API.

Tạo văn bản

Mã mẫu này cho biết cách đưa ra lời nhắc cho mô hình Gemini 2.5 Flash để tạo văn bản. Hàm này trả về kết quả cho nhật ký thực thi của 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.';
}

Thay GOOGLE_CLOUD_PROJECT_ID bằng mã dự án của dự án trên đám mây của bạn.

Tạo văn bản bằng tài khoản dịch vụ

Ví dụ sau đây cho biết cách tạo văn bản bằng cách xác thực dưới dạng một dự án Apps Script bằng tài khoản dịch vụ.

/**
 * 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);
}