บริการ Vertex AI ช่วยให้คุณใช้ Vertex AI API ใน Apps Script ได้ API นี้ให้คุณเข้าถึง Gemini และโมเดล Generative AI อื่นๆ สำหรับการสร้างข้อความ การสร้างรูปภาพ และอื่นๆ
ข้อกำหนดเบื้องต้น
โปรเจ็กต์ Google Cloud ที่เปิดใช้การเรียกเก็บเงิน หากต้องการตรวจสอบว่าโปรเจ็กต์ที่มีอยู่เปิดใช้การเรียกเก็บเงินแล้วหรือไม่ ให้ดูที่ยืนยันสถานะการเรียกเก็บเงินของโปรเจ็กต์ หากต้องการสร้างโปรเจ็กต์และตั้งค่าการเรียกเก็บเงิน โปรดดูสร้างโปรเจ็กต์ Google Cloud
ใน Google Cloud Console ให้ไปที่โปรเจ็กต์ Cloud แล้วเปิดใช้ Vertex AI API โดยทำดังนี้
กำหนดค่าโปรเจ็กต์ Apps Script ดังนี้
- เปิดใช้บริการ Vertex AI โปรดดูขั้นตอนต่างๆ ที่ บริการขั้นสูงของ Google
- เพิ่มโปรเจ็กต์ที่อยู่ในระบบคลาวด์ในการตั้งค่าโปรเจ็กต์
ข้อมูลอ้างอิง
ดูข้อมูลเพิ่มเติมเกี่ยวกับบริการนี้ได้ที่เอกสารอ้างอิง 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