تعرض Gemini API الردود كنص غير منظَّم تلقائيًا. ومع ذلك، تتطلب بعض حالات الاستخدام نصًا منظَّمًا، مثل JSON. على سبيل المثال، قد تستخدم الردّ في مهام أخرى لاحقة تتطلب مخطط بيانات محدّدًا.
لضمان التزام الإخراج الذي ينشئه النموذج بمخطط معيّن دائمًا، يمكنك تحديد مخطط ردود يعمل كمخطط أولي لردود النموذج. يمكنك بعد ذلك استخراج البيانات مباشرةً من إخراج النموذج مع تقليل مرحلة ما بعد المعالجة.
إليك بعض الأمثلة:
ضمان أن ينتج ردّ النموذج JSON صالحًا ويتوافق مع المخطط الذي تقدّمه.
على سبيل المثال، يمكن للنموذج إنشاء إدخالات منظَّمة للوصفات تتضمّن دائمًا اسم الوصفة وقائمة المكوّنات والخطوات. يمكنك بعد ذلك تحليل هذه المعلومات وعرضها بسهولة أكبر في واجهة مستخدم تطبيقك.فرض قيود على طريقة ردّ النموذج أثناء مهام التصنيف
على سبيل المثال، يمكنك أن تطلب من النموذج إضافة تعليقات توضيحية إلى النص باستخدام مجموعة معيّنة من التصنيفات (على سبيل المثال، مجموعة معيّنة من قيم enum مثلpositiveوnegative)، بدلاً من التصنيفات التي ينتجها النموذج (والتي قد تتضمّن درجة من التباين مثلgoodأوpositiveأوnegativeأوbad).
يوضّح لك هذا الدليل كيفية إنشاء إخراج JSON من خلال توفير responseSchema في طلب إلى generateContent. يركّز الدليل على الإدخال النصي فقط، ولكن يمكن لنموذج Gemini أيضًا إنشاء ردود منظَّمة على الطلبات المتعدّدة الوسائط التي تتضمّن الصور والفيديوهات والمقاطع الصوتية كإدخال.
في أسفل هذه الصفحة، ستجد المزيد من الأمثلة، مثل كيفية إنشاء قيم enum كإخراج.
قبل البدء
|
انقر على موفّر Gemini API لعرض المحتوى والرمز البرمجي الخاصَّين بالموفّر على هذه الصفحة. |
إذا لم يسبق لك ذلك، يُرجى إكمال
دليل البدء الذي يوضّح كيفية
إعداد مشروعك على Firebase وربط تطبيقك بـ Firebase وإضافة حزمة تطوير البرامج (SDK) و
تهيئة خدمة الخلفية لموفّر Gemini API الذي اخترته و
إنشاء مثيل GenerativeModel.
لاختبار طلباتك وتكرارها، ننصحك باستخدام Google AI Studio.
الخطوة 1: تحديد مخطط ردود
حدِّد مخطط ردود لتحديد بنية إخراج النموذج وأسماء الحقول ونوع البيانات المتوقّع لكل حقل.
عندما ينشئ النموذج ردّه، يستخدم اسم الحقل والسياق من طلبك. للتأكّد من أنّ هدفك واضح، ننصحك باستخدام بنية واضحة وأسماء حقول غير غامضة، وحتى أوصاف حسب الحاجة.
اعتبارات مخططات الردود
ضَع في اعتبارك ما يلي عند كتابة مخطط الردود:
يتم احتساب حجم مخطط الردود ضمن الحدّ الأقصى لعدد الرموز المميّزة للإدخال.
تتيح ميزة مخطط الردود أنواع MIME التالية للردود:
application/json: إخراج JSON كما هو محدّد في مخطط الردود (مفيد لمتطلبات الإخراج المنظَّم)text/x.enum: إخراج قيمة 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 FirebaseAILogic
// 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 Gemini Developer API backend service
let ai = FirebaseAI.firebaseAI(backend: .googleAI())
// Create a `GenerativeModel` instance with a model that supports your use case
let model = ai.generativeModel(
modelName: "gemini-3-flash-preview",
// 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 Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
modelName = "gemini-3-flash-preview",
// 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 Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.generativeModel(
/* modelName */ "gemini-3-flash-preview",
/* generationConfig */ generationConfig);
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
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 { getAI, getGenerativeModel, GoogleAIBackend, Schema } from "firebase/ai";
// 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 Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// 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"],
}),
}),
}
});
// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(ai, {
model: "gemini-3-flash-preview",
// 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_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.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'],
);
// Initialize FirebaseApp
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
final model =
FirebaseAI.googleAI().generativeModel(
model: 'gemini-3-flash-preview',
// 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 Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
var model = FirebaseAI.DefaultInstance.GetGenerativeModel(
modelName: "gemini-3-flash-preview",
// 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 الذي اخترته حتى يظهر لك المحتوى الخاص بالموفّر على هذه الصفحة. |
يوضّح المثال التالي كيفية استخدام مخطط ردود لمهمة تصنيف. يُطلب من النموذج تحديد نوع فيلم استنادًا إلى وصفه. الإخراج هو قيمة enum بنص عادي يختارها النموذج من قائمة قيم محدّدة في مخطط الردود المقدَّم.
لإجراء مهمة التصنيف المنظَّمة هذه، عليك تحديد responseMimeType المناسب (في هذا المثال، text/x.enum) بالإضافة إلى responseSchema الذي تريد أن يستخدمه النموذج، وذلك أثناء تهيئة النموذج.
Swift
import FirebaseAILogic
// 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 Gemini Developer API backend service
let ai = FirebaseAI.firebaseAI(backend: .googleAI())
// Create a `GenerativeModel` instance with a model that supports your use case
let model = ai.generativeModel(
modelName: "gemini-3-flash-preview",
// 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 Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
modelName = "gemini-3-flash-preview",
// 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 Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.generativeModel(
/* modelName */ "gemini-3-flash-preview",
/* generationConfig */ generationConfig);
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
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 { getAI, getGenerativeModel, GoogleAIBackend, Schema } from "firebase/ai";
// 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 Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// 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"],
});
// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(ai, {
model: "gemini-3-flash-preview",
// 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_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.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']);
// Initialize FirebaseApp
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
final model =
FirebaseAI.googleAI().generativeModel(
model: 'gemini-3-flash-preview',
// 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 Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
var model = FirebaseAI.DefaultInstance.GetGenerativeModel(
modelName: "gemini-3-flash-preview",
// 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، تتضمّن هذه المَعلمات الحدّ الأقصى لعدد الرموز المميّزة للإخراج ودرجة العشوائية وأعلى K كلمات محتملة وأعلى احتمال تراكمي. بالنسبة إلى نماذج Imagen، تتضمّن هذه المَعلمات نسبة العرض إلى الارتفاع وإنشاء الأشخاص، ووضع العلامات المائية وما إلى ذلك.
- استخدام إعدادات الأمان لضبط احتمالية الحصول على ردود قد تُعتبر ضارة، بما في ذلك خطاب الكراهية والمحتوى الجنسي الفاضح
- ضبط تعليمات النظام لتوجيه سلوك النموذج تشبه هذه الميزة مقدمة تضيفها قبل أن يتعرّض النموذج لأي تعليمات أخرى من المستخدم النهائي.
تقديم ملاحظات حول تجربتك مع Firebase AI Logic