يعرض الرمز Gemini API الردود كنص غير منظَّم تلقائيًا. ومع ذلك، تتطلّب بعض حالات الاستخدام نصًا منظَّمًا، مثل JSON. على سبيل المثال، قد يتم استخدام الردّ في مهام أخرى لاحقة تتطلّب ملفًا تعريفيًا محددًا للبيانات.
لضمان التزام النموذج دائمًا بمخطّط معيّن في النتائج التي ينشئها، يمكنك تحديد مخطّط استجابة يعمل كخطة نموذجية للردود. يمكنك بعد ذلك استخراج البيانات مباشرةً من مخرجات النموذج مع إجراء قدر أقل من عمليات المعالجة اللاحقة.
وإليك بعض الأمثلة:
تأكَّد من أنّ استجابة النموذج تُنشئ ملف JSON صالحًا وأنّها تمتثل للمخطّط المقدَّم.
على سبيل المثال، يمكن للنموذج إنشاء إدخالات منظَّمة للوصفات التي تشمل دائمًا اسم الوصفة وقائمة المكونات والخطوات. يمكنك بعد ذلك تحليل هذه المعلومات وعرضها في واجهة مستخدم تطبيقك بسهولة أكبر.فرض قيود على كيفية استجابة النموذج أثناء مهام التصنيف
على سبيل المثال، يمكنك أن تطلب من النموذج إضافة تعليقات توضيحية إلى النص باستخدام مجموعة محدّدة من التصنيفات (على سبيل المثال، مجموعة محدّدة من التصنيفات المحدّدة مثلpositive
وnegative
)، بدلاً من التصنيفات التي ينشئها النموذج (التي يمكن أن تتضمّن درجة من التفاوت مثلgood
أوpositive
أوnegative
أوbad
).
يوضّح لك هذا الدليل كيفية إنشاء إخراج بتنسيق JSON من خلال تقديم responseSchema
في طلب إلى generateContent
. ويركز هذا النموذج على الإدخال النصي فقط، ولكن يمكن لـ Gemini
تقديم ردود منظَّمة أيضًا على الطلبات المتعدّدة الوسائط التي تتضمّن الصور
والفيديوهات والمحتوى الصوتي كإدخال.
في أسفل هذه الصفحة، يمكنك الاطّلاع على المزيد من الأمثلة، مثل كيفية إنشاء قيم مصنّفة كإخراج.
قبل البدء
انقر على مزوّد Gemini API لعرض المحتوى الخاص بالمزوّد والرمز البرمجي في هذه الصفحة. |
أكمِل قراءة
دليل البدء، الذي يوضّح كيفية
إعداد مشروعك على Firebase وربط تطبيقك بـ Firebase وإضافة حزمة تطوير البرامج (SDK)
وبدء خدمة الخلفية لمزوّد Gemini API الذي اخترته،
وإنشاء مثيل GenerativeModel
، إذا لم يسبق لك إجراء ذلك.
لاختبار طلباتك وتكرارها وحتى الحصول على مقتطف رمز تم إنشاؤه، ننصحك باستخدام Google AI Studio.
الخطوة 1: تحديد مخطّط استجابة
حدِّد مخطّط استجابة لتحديد بنية مخرجات النموذج وأسماء الحقول ونوع البيانات المتوقّع لكل حقل.
عندما ينشئ النموذج رده، يستخدم اسم الحقل والسياق من طلبك. للتأكّد من أنّ هدفك واضح، ننصحك باستخدام بنية واضحة وأسماء حقول لا لبس فيها، وحتى أوصاف حسب الحاجة.
اعتبارات حول مخطّطات الردود
يُرجى مراعاة ما يلي عند كتابة مخطّط الردّ:
يتم احتساب حجم مخطّط الاستجابة ضمن الحد الأقصى لرمز المرور المُدخل.
تتيح ميزة مخطّط الاستجابة أنواع MIME التالية للإجابات:
application/json
: إخراج JSON كما هو محدّد في مخطّط الاستجابة (مفيد لمتطلبات الإخراج المنظّم)
text/x.enum
: عرض قيمة إحصائية كما هو محدّد في مخطّط الاستجابة (مفيد لمهام التصنيف)
تتيح ميزة مخطّط الاستجابة حقول المخطّط التالية:
enum
items
maxItems
nullable
properties
required
في حال استخدام حقل غير متوافق، سيظل بإمكان النموذج معالجة طلبك، ولكن سيتجاهل الحقل. يُرجى العِلم أنّ القائمة أعلاه هي مجموعة فرعية من عنصر مخطّط OpenAPI 3.0.
بالنسبة إلى Firebase AI Logic حِزم تطوير البرامج (SDK)، يتم اعتبار جميع الحقول تلقائيًا مطلوبة ما لم تحدّدها كحقول اختيارية في صفيف
optionalProperties
. بالنسبة إلى هذه الحقول الاختيارية، يمكن للنموذج تعبئة الحقول أو تخطّيها. يُرجى العِلم أنّ هذا السلوك يختلف عن السلوك التلقائي لموفّري Gemini API هذين إذا كنت تستخدم حِزم SDK للخادم أو واجهات برمجة التطبيقات الخاصة بهما مباشرةً.
الخطوة 2: إنشاء إخراج بتنسيق JSON باستخدام مخطّط الاستجابة
قبل تجربة هذا العيّنة، عليك إكمال القسم
قبل البدء من هذا الدليل
لإعداد مشروعك وتطبيقك. في هذا القسم، عليك أيضًا النقر على زر Gemini API مقدّم الخدمة الذي اخترته حتى يظهر لك المحتوى الخاص بالمقدّم في هذه الصفحة. |
يوضّح المثال التالي كيفية إنشاء إخراج JSON منظَّم.
عند إنشاء مثيل GenerativeModel
، حدِّد
responseMimeType
المناسب (application/json
في هذا المثال) بالإضافة إلى
responseSchema
الذي تريد أن يستخدمه النموذج.
Swift
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.")
Kotlin
بالنسبة إلى Kotlin، تكون الطرق في حزمة تطوير البرامج (SDK) هذه دوالّ معلّقة ويجب استدعاؤها من نطاق Coroutine.// 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)
Java
بالنسبة إلى Java، تُعرِض طُرق البث في حزمة SDK هذه نوعًا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);
Web
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());
Dart
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);
Unity
using Firebase;
using Firebase.AI;
// Provide a JSON schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
var jsonSchema = Schema.Object(
properties: new System.Collections.Generic.Dictionary<string, Schema> {
{ "characters", Schema.Array(
items: Schema.Object(
properties: new System.Collections.Generic.Dictionary<string, Schema> {
{ "name", Schema.String() },
{ "age", Schema.Int() },
{ "species", Schema.String() },
{ "accessory", Schema.Enum(new string[] { "hat", "belt", "shoes" }) },
},
optionalProperties: new string[] { "accessory" }
)
) },
}
);
// Initialize the Firebase AI service and the generative model.
var model = FirebaseAI.DefaultInstance.GetGenerativeModel(
modelName: "gemini-2.0-flash",
// In the generation config, set the `responseMimeType` to `application/json`
// and pass the JSON schema object into `responseSchema`.
generationConfig: new GenerationConfig(
responseMimeType: "application/json",
responseSchema: jsonSchema
)
);
var prompt = "For use in a children's card game, generate 10 animal-based characters.";
var response = await model.GenerateContentAsync(prompt);
UnityEngine.Debug.Log(response.Text ?? "No text in response.");
تعرَّف على كيفية اختيار نموذج مناسب لحالة الاستخدام والتطبيق.
أمثلة إضافية
في ما يلي بعض الأمثلة الإضافية حول كيفية استخدام المخرجات الواضحة وإنشاءها.إنشاء قيم enum كإخراج
قبل تجربة هذا العيّنة، عليك إكمال القسم
قبل البدء من هذا الدليل
لإعداد مشروعك وتطبيقك. في هذا القسم، عليك أيضًا النقر على زر Gemini API مقدّم الخدمة الذي اخترته حتى يظهر لك المحتوى الخاص بالمقدّم في هذه الصفحة. |
يوضّح المثال التالي كيفية استخدام مخطّط استجابة لمهمّة تصنيف. يُطلب من النموذج تحديد نوع الفيلم استنادًا إلى وصفه. الناتج هو قيمة واحدة من القيم المحدّدة في النصوص العادية التي يختارها النموذج من قائمة القيم المحدّدة في مخطّط الاستجابة المقدَّم.
لتنفيذ مهمة التصنيف المنظَّم هذه، عليك تحديد responseMimeType
المناسب (في هذا المثال،
text/x.enum
) بالإضافة إلى responseSchema
الذي تريد أن يستخدمه النموذج أثناء بدء تشغيله.
Swift
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.")
Kotlin
بالنسبة إلى Kotlin، تكون الطرق في حزمة تطوير البرامج (SDK) هذه دوالّ معلّقة ويجب استدعاؤها من نطاق Coroutine.// 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)
Java
بالنسبة إلى Java، تُعرِض طُرق البث في حزمة SDK هذه نوعًا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);
Web
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());
Dart
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);
Unity
using Firebase;
using Firebase.AI;
// Provide an enum schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
var enumSchema = Schema.Enum(new string[] { "drama", "comedy", "documentary" });
// Initialize the Firebase AI service and the generative model.
var model = FirebaseAI.DefaultInstance.GetGenerativeModel(
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: new GenerationConfig(
responseMimeType: "text/x.enum",
responseSchema: enumSchema
)
);
var 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.
";
var response = await model.GenerateContentAsync(prompt);
UnityEngine.Debug.Log(response.Text ?? "No text in response.");
تعرَّف على كيفية اختيار نموذج مناسب لحالة الاستخدام والتطبيق.
خيارات أخرى للتحكّم في إنشاء المحتوى
- اطّلِع على مزيد من المعلومات عن تصميم الطلب حتى تتمكّن من التأثير في النموذج لإنشاء مخرجات خاصة باحتياجاتك.
- يمكنك ضبط مَعلمات النموذج للتحكّم في كيفية إنشاء النموذج لردّ. بالنسبة إلى نماذج Gemini، تتضمّن هذه المَعلمات الحد الأقصى لرموز الإخراج ودرجة الحرارة وtopK وtopP. بالنسبة إلى نماذج Imagen، تشمل هذه الإعدادات نسبة العرض إلى الارتفاع وإنشاء الأشخاص ووضع العلامة المائية وما إلى ذلك.
- استخدِم إعدادات الأمان لضبط احتمالية تلقّي ردود قد تُعتبر ضارة، بما في ذلك خطاب الكراهية والمحتوى الجنسي الفاضح.
- اضبط تعليمات النظام لتوجيه سلوك النموذج. هذه الميزة تشبه مقدّمة تضعها قبل تعريض النموذج لأي تعليمات أخرى من المستخدم النهائي.
تقديم ملاحظات حول تجربتك مع Firebase AI Logic