يعرض الرمز Gemini API الردود كنص غير منظَّم تلقائيًا. ومع ذلك، تتطلّب بعض حالات الاستخدام نصًا منظَّمًا، مثل JSON. على سبيل المثال، قد يتم استخدام الردّ في مهام أخرى لاحقة تتطلّب ملفًا تعريفيًا محددًا للبيانات.
لضمان أن يلتزم الناتج الذي ينشئه النموذج دائمًا بمخطّط معيّن، يمكنك تحديد مخطّط استجابة، الذي يعمل بمثابة مخطّط تفصيلي للردود المستندة إلى النموذج. يمكنك بعد ذلك استخراج البيانات مباشرةً من مخرجات النموذج مع إجراء قدر أقل من عمليات المعالجة اللاحقة.
وإليك بعض الأمثلة:
تأكَّد من أنّ استجابة النموذج تُنشئ ملف JSON صالحًا وأنّها تمتثل للمخطّط المقدَّم.
على سبيل المثال، يمكن للنموذج إنشاء إدخالات منظَّمة للوصفات التي تشمل دائمًا اسم الوصفة وقائمة المكونات والخطوات. يمكنك بعد ذلك تحليل هذه المعلومات وعرضها في واجهة مستخدم تطبيقك بسهولة أكبر.فرض قيود على كيفية استجابة النموذج أثناء مهام التصنيف
على سبيل المثال، يمكنك أن تطلب من النموذج إضافة تعليقات توضيحية إلى النص باستخدام مجموعة محدّدة من التصنيفات (على سبيل المثال، مجموعة محدّدة من التصنيفات المحدّدة مثلpositive
وnegative
)، بدلاً من التصنيفات التي ينشئها النموذج (التي يمكن أن تتضمّن درجة من التفاوت مثلgood
أوpositive
أوnegative
أوbad
).
يوضّح لك هذا الدليل كيفية إنشاء إخراج بتنسيق JSON من خلال تقديم responseSchema
في طلب إلى generateContent
. ويركز هذا النموذج على الإدخال النصي فقط، ولكن يمكن لـ Gemini
تقديم ردود منظَّمة أيضًا على الطلبات المتعدّدة الوسائط التي تتضمّن الصور
والفيديوهات والمحتوى الصوتي كإدخال.
في أسفل هذه الصفحة، يمكنك الاطّلاع على المزيد من الأمثلة، مثل كيفية إنشاء قيم مصنّفة كإخراج. للاطّلاع على مثالين إضافيين على كيفية إنشاء مخرجات منظَّمة، يمكنك الاطّلاع على قائمة أمثلة على المخططات والردود النموذجية في مستندات Google Cloud.
خيارات أخرى للعمل مع Gemini API
يمكنك تجربة إصدار "Google AI" بديل من Gemini API
الحصول على إذن وصول مجاني (ضمن الحدود المتاحة) باستخدام Google AI Studio و حِزم تطوير برامج (SDK) Google AI للعملاء. يجب استخدام حِزم تطوير البرامج (SDK) هذه لإنشاء النماذج الأولية فقط في تطبيقات الويب والتطبيقات المتوافقة مع الأجهزة الجوّالة.بعد التعرّف على طريقة عمل Gemini API، يمكنك نقل بياناتك إلى حِزم Vertex AI in Firebase SDK (هذه المستندات)، التي تتضمّن العديد من الميزات الإضافية المهمة للتطبيقات المتوافقة مع الأجهزة الجوّالة والويب، مثل حماية واجهة برمجة التطبيقات من إساءة الاستخدام باستخدام Firebase App Check وتوفير إمكانية استخدام ملفات وسائط كبيرة في الطلبات.
يمكنك اختياريًا استدعاء Vertex AI Gemini API من جهة الخادم (مثل استخدام Python أو Node.js أو Go)
استخدِم حِزم تطوير البرامج (SDK) من جهة الخادم لVertex AI أو Genkit أو Firebase Extensions لGemini API.
قبل البدء
إذا لم يسبق لك ذلك، أكمِل قراءة
دليل البدء الذي يوضّح كيفية
إعداد مشروعك على Firebase وربط تطبيقك بـ Firebase وإضافة حزمة تطوير البرامج (SDK)
وبدء خدمة Vertex AI وإنشاء مثيل GenerativeModel
.
الخطوة 1: تحديد مخطّط استجابة
حدِّد مخطّط استجابة لتحديد بنية ناتج النموذج وأسماء الحقل ونوع البيانات المتوقّع لكل حقل.
عندما ينشئ النموذج رده، يستخدم اسم الحقل والسياق من طلبك. للتأكّد من أنّ هدفك واضح، ننصحك باستخدام بنية واضحة وأسماء حقول لا لبس فيها، وحتى أوصاف حسب الحاجة.
اعتبارات حول مخطّطات الردود
يُرجى مراعاة ما يلي عند كتابة مخطّط الردّ:
يتم احتساب حجم مخطّط الاستجابة ضمن الحد الأقصى لرمز المرور المُدخل.
تتيح ميزة مخطّط الاستجابة أنواع MIME التالية للإجابات:
application/json
: إخراج تنسيق JSON كما هو محدّد في مخطّط الاستجابة (مفيد لمتطلبات الإخراج المنظّم)
text/x.enum
: عرض قيمة إحصائية كما هو محدّد في مخطّط الاستجابة (مفيد لمهام التصنيف)
تتيح ميزة مخطّط الاستجابة حقول المخطّط التالية:
enum
items
maxItems
nullable
properties
required
في حال استخدام حقل غير متوافق، سيظل بإمكان النموذج معالجة طلبك، ولكن سيتجاهل الحقل. يُرجى العِلم أنّ القائمة أعلاه هي مجموعة فرعية من عنصر مخطّط OpenAPI 3.0 (اطّلِع على مرجع مخطّط Vertex AI).
بشكلٍ تلقائي، بالنسبة إلى Vertex AI in Firebase حِزم تطوير البرامج (SDK)، تُعتبَر جميع الحقول مطلوبة ما لم تحدّدها كحقول اختيارية في صفيف
optionalProperties
. بالنسبة إلى هذه الحقول الاختيارية، يمكن للنموذج تعبئة الحقول أو تخطّيها.يُرجى العلم أنّ هذا السلوك هو عكس السلوك التلقائي لعنصر Vertex AI Gemini API.
الخطوة 2: إرسال طلب يتضمّن مخطّط استجابة لإنشاء ملف JSON
يوضّح المثال التالي كيفية إنشاء إخراج JSON منظَّم.
عند إنشاء مثيل GenerativeModel
، حدِّد
responseMimeType
المناسب (application/json
في هذا المثال) بالإضافة إلى
responseSchema
الذي تريد أن يستخدمه النموذج.
import FirebaseVertexAI
// Provide a JSON schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
let jsonSchema = Schema.object(
properties: [
"characters": Schema.array(
items: .object(
properties: [
"name": .string(),
"age": .integer(),
"species": .string(),
"accessory": .enumeration(values: ["hat", "belt", "shoes"]),
],
optionalProperties: ["accessory"]
)
),
]
)
// Initialize the Vertex AI service and the generative model.
let model = VertexAI.vertexAI().generativeModel(
modelName: "gemini-2.0-flash",
// In the generation config, set the `responseMimeType` to `application/json`
// and pass the JSON schema object into `responseSchema`.
generationConfig: GenerationConfig(
responseMIMEType: "application/json",
responseSchema: jsonSchema
)
)
let prompt = "For use in a children's card game, generate 10 animal-based characters."
let response = try await model.generateContent(prompt)
print(response.text ?? "No text in response.")
// Provide a JSON schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
val jsonSchema = Schema.obj(
mapOf("characters" to Schema.array(
Schema.obj(
mapOf(
"name" to Schema.string(),
"age" to Schema.integer(),
"species" to Schema.string(),
"accessory" to Schema.enumeration(listOf("hat", "belt", "shoes")),
),
optionalProperties = listOf("accessory")
)
))
)
// Initialize the Vertex AI service and the generative model.
val generativeModel = Firebase.vertexAI.generativeModel(
modelName = "gemini-2.0-flash",
// In the generation config, set the `responseMimeType` to `application/json`
// and pass the JSON schema object into `responseSchema`.
generationConfig = generationConfig {
responseMimeType = "application/json"
responseSchema = jsonSchema
})
val prompt = "For use in a children's card game, generate 10 animal-based characters."
val response = generativeModel.generateContent(prompt)
print(response.text)
Publisher
من مكتبة Reactive Streams.
// Provide a JSON schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
Schema jsonSchema = Schema.obj(
/* properties */
Map.of(
"characters", Schema.array(
/* items */ Schema.obj(
/* properties */
Map.of("name", Schema.str(),
"age", Schema.numInt(),
"species", Schema.str(),
"accessory",
Schema.enumeration(
List.of("hat", "belt", "shoes")))
))),
List.of("accessory"));
// In the generation config, set the `responseMimeType` to `application/json`
// and pass the JSON schema object into `responseSchema`.
GenerationConfig.Builder configBuilder = new GenerationConfig.Builder();
configBuilder.responseMimeType = "application/json";
configBuilder.responseSchema = jsonSchema;
GenerationConfig generationConfig = configBuilder.build();
// Initialize the Vertex AI service and the generative model.
GenerativeModel gm = FirebaseVertexAI.getInstance().generativeModel(
/* modelName */ "gemini-2.0-flash",
/* generationConfig */ generationConfig);
GenerativeModelFutures model = GenerativeModelFutures.from(gm);
Content content = new Content.Builder()
.addText("For use in a children's card game, generate 10 animal-based characters.")
.build();
// For illustrative purposes only. You should use an executor that fits your needs.
Executor executor = Executors.newSingleThreadExecutor();
ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(
response,
new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
String resultText = result.getText();
System.out.println(resultText);
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
},
executor);
import { initializeApp } from "firebase/app";
import { getVertexAI, getGenerativeModel, Schema } from "firebase/vertexai";
// TODO(developer) Replace the following with your app's Firebase configuration.
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
// ...
};
// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);
// Initialize the Vertex AI service.
const vertexAI = getVertexAI(firebaseApp);
// Provide a JSON schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
const jsonSchema = Schema.object({
properties: {
characters: Schema.array({
items: Schema.object({
properties: {
name: Schema.string(),
accessory: Schema.string(),
age: Schema.number(),
species: Schema.string(),
},
optionalProperties: ["accessory"],
}),
}),
}
});
// Initialize the generative model.
const model = getGenerativeModel(vertexAI, {
model: "gemini-2.0-flash",
// In the generation config, set the `responseMimeType` to `application/json`
// and pass the JSON schema object into `responseSchema`.
generationConfig: {
responseMimeType: "application/json",
responseSchema: jsonSchema
},
});
let prompt = "For use in a children's card game, generate 10 animal-based characters.";
let result = await model.generateContent(prompt)
console.log(result.response.text());
import 'package:firebase_vertexai/firebase_vertexai.dart';
import 'package:firebase_core/firebase_core.dart';
// Provide a JSON schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
final jsonSchema = Schema.object(
properties: {
'characters': Schema.array(
items: Schema.object(
properties: {
'name': Schema.string(),
'age': Schema.integer(),
'species': Schema.string(),
'accessory':
Schema.enumString(enumValues: ['hat', 'belt', 'shoes']),
},
),
),
},
optionalProperties: ['accessory'],
);
await Firebase.initializeApp();
// Initialize the Vertex AI service and the generative model.
final model =
FirebaseVertexAI.instance.generativeModel(
model: 'gemini-2.0-flash',
// In the generation config, set the `responseMimeType` to `application/json`
// and pass the JSON schema object into `responseSchema`.
generationConfig: GenerationConfig(
responseMimeType: 'application/json', responseSchema: jsonSchema));
final prompt = "For use in a children's card game, generate 10 animal-based characters.";
final response = await model.generateContent([Content.text(prompt)]);
print(response.text);
تعرَّف على كيفية اختيار نموذج وموقع جغرافي اختياريًا مناسبَين لحالة الاستخدام والتطبيق.
أمثلة إضافية
للاطّلاع على أمثلة إضافية حول كيفية استخدام النتائج المنظَّمة وإنشائها، اطّلِع على قائمة أمثلة على المخططات والردود النموذجية في مستندات Google Cloud.
إنشاء قيم enum كإخراج
يوضّح المثال التالي كيفية استخدام مخطّط استجابة لمهمّة تصنيف. يُطلب من النموذج تحديد نوع الفيلم استنادًا إلى وصفه. الناتج هو قيمة واحدة من القيم المحدّدة في النصوص العادية التي يختارها النموذج من قائمة القيم المحدّدة في مخطّط الاستجابة المقدَّم.
لتنفيذ مهمة التصنيف المُنظَّم هذه، عليك تحديد responseMimeType
المناسب (في هذا المثال،
text/x.enum
) بالإضافة إلى responseSchema
الذي تريد أن يستخدمه النموذج أثناء بدء تشغيله.
import FirebaseVertexAI
// Provide an enum schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
let enumSchema = Schema.enumeration(values: ["drama", "comedy", "documentary"])
// Initialize the Vertex AI service and the generative model.
let model = VertexAI.vertexAI().generativeModel(
modelName: "gemini-2.0-flash",
// In the generation config, set the `responseMimeType` to `text/x.enum`
// and pass the enum schema object into `responseSchema`.
generationConfig: GenerationConfig(
responseMIMEType: "text/x.enum",
responseSchema: enumSchema
)
)
let prompt = """
The film aims to educate and inform viewers about real-life subjects, events, or people.
It offers a factual record of a particular topic by combining interviews, historical footage,
and narration. The primary purpose of a film is to present information and provide insights
into various aspects of reality.
"""
let response = try await model.generateContent(prompt)
print(response.text ?? "No text in response.")
// Provide an enum schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
val enumSchema = Schema.enumeration(listOf("drama", "comedy", "documentary"))
// Initialize the Vertex AI service and the generative model.
val generativeModel = Firebase.vertexAI.generativeModel(
modelName = "gemini-2.0-flash",
// In the generation config, set the `responseMimeType` to `text/x.enum`
// and pass the enum schema object into `responseSchema`.
generationConfig = generationConfig {
responseMimeType = "text/x.enum"
responseSchema = enumSchema
})
val prompt = """
The film aims to educate and inform viewers about real-life subjects, events, or people.
It offers a factual record of a particular topic by combining interviews, historical footage,
and narration. The primary purpose of a film is to present information and provide insights
into various aspects of reality.
"""
val response = generativeModel.generateContent(prompt)
print(response.text)
Publisher
من مكتبة Reactive Streams.
// Provide an enum schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
Schema enumSchema = Schema.enumeration(List.of("drama", "comedy", "documentary"));
// In the generation config, set the `responseMimeType` to `text/x.enum`
// and pass the enum schema object into `responseSchema`.
GenerationConfig.Builder configBuilder = new GenerationConfig.Builder();
configBuilder.responseMimeType = "text/x.enum";
configBuilder.responseSchema = enumSchema;
GenerationConfig generationConfig = configBuilder.build();
// Initialize the Vertex AI service and the generative model.
GenerativeModel gm = FirebaseVertexAI.getInstance().generativeModel(
/* modelName */ "gemini-2.0-flash",
/* generationConfig */ generationConfig);
GenerativeModelFutures model = GenerativeModelFutures.from(gm);
String prompt = "The film aims to educate and inform viewers about real-life subjects," +
" events, or people. It offers a factual record of a particular topic by" +
" combining interviews, historical footage, and narration. The primary purpose" +
" of a film is to present information and provide insights into various aspects" +
" of reality.";
Content content = new Content.Builder().addText(prompt).build();
// For illustrative purposes only. You should use an executor that fits your needs.
Executor executor = Executors.newSingleThreadExecutor();
ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(
response,
new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
String resultText = result.getText();
System.out.println(resultText);
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
},
executor);
import { initializeApp } from "firebase/app";
import { getVertexAI, getGenerativeModel, Schema } from "firebase/vertexai";
// TODO(developer) Replace the following with your app's Firebase configuration.
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
// ...
};
// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);
// Initialize the Vertex AI service.
const vertexAI = getVertexAI(firebaseApp);
// Provide an enum schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
const enumSchema = Schema.enumString({
enum: ["drama", "comedy", "documentary"],
});
// Initialize the generative model.
const model = getGenerativeModel(vertexAI, {
model: "gemini-2.0-flash",
// In the generation config, set the `responseMimeType` to `text/x.enum`
// and pass the JSON schema object into `responseSchema`.
generationConfig: {
responseMimeType: "text/x.enum",
responseSchema: enumSchema,
},
});
let prompt = `The film aims to educate and inform viewers about real-life
subjects, events, or people. It offers a factual record of a particular topic
by combining interviews, historical footage, and narration. The primary purpose
of a film is to present information and provide insights into various aspects
of reality.`;
let result = await model.generateContent(prompt);
console.log(result.response.text());
import 'package:firebase_vertexai/firebase_vertexai.dart';
import 'package:firebase_core/firebase_core.dart';
// Provide an enum schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
final enumSchema = Schema.enumString(enumValues: ['drama', 'comedy', 'documentary']);
await Firebase.initializeApp();
// Initialize the Vertex AI service and the generative model.
final model =
FirebaseVertexAI.instance.generativeModel(
model: 'gemini-2.0-flash',
// In the generation config, set the `responseMimeType` to `text/x.enum`
// and pass the enum schema object into `responseSchema`.
generationConfig: GenerationConfig(
responseMimeType: 'text/x.enum', responseSchema: enumSchema));
final prompt = """
The film aims to educate and inform viewers about real-life subjects, events, or people.
It offers a factual record of a particular topic by combining interviews, historical footage,
and narration. The primary purpose of a film is to present information and provide insights
into various aspects of reality.
""";
final response = await model.generateContent([Content.text(prompt)]);
print(response.text);
تعرَّف على كيفية اختيار نموذج وموقع جغرافي اختياريًا مناسبَين لحالة الاستخدام والتطبيق.
خيارات أخرى للتحكّم في إنشاء المحتوى
- اطّلِع على مزيد من المعلومات عن تصميم الطلب حتى تتمكّن من التأثير في النموذج لإنشاء نتائج خاصة باحتياجاتك.
- يمكنك ضبط مَعلمات النموذج للتحكّم في كيفية إنشاء النموذج لردّ. بالنسبة إلى نماذج Gemini، تتضمّن هذه المَعلمات الحد الأقصى لرموز الإخراج ودرجة الحرارة وtopK وtopP. بالنسبة إلى نماذج Imagen، تشمل هذه الإعدادات نسبة العرض إلى الارتفاع وإنشاء الأشخاص ووضع العلامة المائية وما إلى ذلك.
- استخدِم إعدادات الأمان لضبط احتمالية تلقّي ردود قد تُعتبر ضارة، بما في ذلك خطاب الكراهية والمحتوى الجنسي الفاضح.
- اضبط تعليمات النظام لتوجيه سلوك النموذج. هذه الميزة تشبه "مقدّمة" تضعها قبل عرض النموذج على أي تعليمات أخرى من المستخدم النهائي.
تقديم ملاحظات حول تجربتك مع Vertex AI in Firebase