تعرض 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 كما هو محدّد في مخطّط الاستجابة (مفيد لمهام التصنيف)
تتيح ميزة "مخطط الردود" استخدام حقول المخطط التالية:
enum
items
maxItems
nullable
properties
required
إذا كنت تستخدم حقلًا غير متوافق، سيظل بإمكان النموذج التعامل مع طلبك، ولكن سيتم تجاهل الحقل. يُرجى العِلم أنّ القائمة أعلاه هي مجموعة فرعية من عنصر المخطط في OpenAPI 3.0.
بشكلٍ تلقائي، بالنسبة إلى حِزم تطوير البرامج Firebase AI Logic، يتم اعتبار جميع الحقول مطلوبة ما لم تحدّدها على أنّها اختيارية في
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.5-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، تكون الطرق في حزمة تطوير البرامج هذه عبارة عن دوال معلّقة ويجب استدعاؤها من نطاق 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.5-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، تعرض طرق العرض المباشر في حزمة تطوير البرامج هذه النوع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.5-flash",
/* 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.5-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_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.5-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 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.5-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 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.5-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، تكون الطرق في حزمة تطوير البرامج هذه عبارة عن دوال معلّقة ويجب استدعاؤها من نطاق 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.5-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، تعرض طرق العرض المباشر في حزمة تطوير البرامج هذه النوع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.5-flash",
/* 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.5-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_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.5-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 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.5-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، تتضمّن هذه المَعلمات الحد الأقصى لعدد الرموز المميزة في الناتج، واحتمالية تكرار الرموز المميزة في الناتج، وما إلى ذلك. أما بالنسبة إلى نماذج Imagen، فتتضمّن نسبة العرض إلى الارتفاع، وإنشاء صور أشخاص، والعلامات المائية، وما إلى ذلك.
- استخدِم إعدادات الأمان لتعديل احتمالية تلقّي ردود قد تُعتبر ضارة، بما في ذلك كلام يحض على الكراهية والمحتوى الجنسي الفاضح.
- اضبط تعليمات النظام لتوجيه سلوك النموذج. هذه الميزة تشبه المقدمة التي تضيفها قبل أن يتلقّى النموذج أي تعليمات أخرى من المستخدم النهائي.
تقديم ملاحظات حول تجربتك مع Firebase AI Logic