الوصول إلى Gemini ونماذج الذكاء الاصطناعي التوليدي الأخرى
تتيح لك خدمة Vertex AI استخدام Vertex AI API في برمجة تطبيقات Google. تتيح لك واجهة برمجة التطبيقات هذه استخدام Gemini ونماذج أخرى للذكاء الاصطناعي التوليدي لإنشاء النصوص والصور وغير ذلك.
لبدء استخدام هذه الخدمة المتقدّمة، جرِّب دليل البدء السريع.
المتطلبات الأساسية
مشروع Google Cloud تم تفعيل الفوترة فيه للتأكّد من تفعيل الفوترة في مشروع حالي، يُرجى الاطّلاع على التحقّق من حالة الفوترة في مشاريعك. لإنشاء مشروع على السحابة الإلكترونية وإعداد الفوترة، يُرجى الاطّلاع على إنشاء مشروع على Google Cloud.
في Google Cloud Console، انتقِل إلى مشروعك على السحابة الإلكترونية وفعِّل واجهة Vertex AI API.
في مشروعك على برمجة تطبيقات، فعِّل خدمة Vertex AI. لمعرفة الخطوات، يُرجى الاطّلاع على خدمات Google المتقدّمة.
مراجع
لمزيد من المعلومات حول هذه الخدمة، يُرجى الاطّلاع على المستندات المرجعية الخاصة بواجهة Vertex AI API. مثل جميع الخدمات المتقدّمة في Apps Script، تستخدم خدمة Vertex AI العناصر والطرق والمعلَمات نفسها التي تستخدمها واجهة برمجة التطبيقات العامة.
نموذج التعليمات البرمجية
يستخدِم نموذج الرمز البرمجي التالي الإصدار 1 من واجهة برمجة التطبيقات Vertex AI API.
إنشاء نص
يوضّح رمز نموذجي هذا كيفية توجيه طلب إلى نموذج 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 بـ
رقم تعريف المشروع
لمشروعك على السحابة الإلكترونية.
إنشاء نص باستخدام حساب خدمة
يوضّح المثال التالي كيفية إنشاء نص من خلال المصادقة كمشروع برمجة تطبيقات باستخدام حساب خدمة.
/**
* 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);
}