Dịch vụ Vertex AI

Dịch vụ Vertex AI cho phép bạn sử dụng Vertex AI API trong 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 nội dung khác.

Đ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 Vertex AI API. 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

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

Tạo văn bản

Đoạn mã mẫu này cho biết cách nhắc mô hình Gemini 2.5 Flash tạo văn bản. Hàm này trả về đầu ra 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.