บริการ Vertex AI

บริการ Vertex AI ช่วยให้คุณใช้ Vertex AI API ใน Apps Script ได้ API นี้ให้คุณเข้าถึง Gemini และโมเดล Generative AI อื่นๆ สำหรับการสร้างข้อความ การสร้างรูปภาพ และอื่นๆ

ข้อกำหนดเบื้องต้น

ข้อมูลอ้างอิง

ดูข้อมูลเพิ่มเติมเกี่ยวกับบริการนี้ได้ที่เอกสารอ้างอิง 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