إنشاء مخرجات منظَّمة (مثل JSON والعناصر المحدّدة) باستخدام واجهة برمجة التطبيقات Gemini

تعرض الدالة Gemini API الردود كنص غير منظَّم تلقائيًا. ومع ذلك، تتطلّب بعض حالات الاستخدام نصًا منظَّمًا، مثل JSON. على سبيل المثال، قد تستخدم الرد في مهام أخرى لاحقة تتطلّب مخطط بيانات محدّدًا.

لضمان التزام الناتج الذي ينشئه النموذج دائمًا بمخطط معيّن، يمكنك تحديد مخطط ردود يعمل كنموذج أولي لردود النموذج. يمكنك بعد ذلك استخراج البيانات مباشرةً من ناتج النموذج مع تقليل المعالجة اللاحقة.

وإليك بعض الأمثلة:

  • تأكَّد من أنّ استجابة النموذج تنتج JSON صالحًا ويتوافق مع المخطط الذي قدّمته.
    على سبيل المثال، يمكن للنموذج إنشاء إدخالات منظَّمة للوصفات تتضمّن دائمًا اسم الوصفة وقائمة المكوّنات والخطوات. يمكنك بعد ذلك تحليل هذه المعلومات وعرضها بسهولة أكبر في واجهة مستخدم تطبيقك.

  • تقييد طريقة استجابة النموذج أثناء مهام التصنيف:
    على سبيل المثال، يمكنك أن يضيف النموذج تعليقات توضيحية إلى النص باستخدام مجموعة معيّنة من التصنيفات (مثل مجموعة معيّنة من القيم الثابتة مثل positive وnegative)، بدلاً من التصنيفات التي ينتجها النموذج (والتي يمكن أن تتضمّن درجة من التباين مثل good أو positive أو negative أو bad).

يوضّح لك هذا الدليل كيفية إنشاء إخراج JSON من خلال توفير responseSchema في طلب إلى generateContent. يركّز هذا النموذج على إدخال النصوص فقط، ولكن يمكنه أيضًا تقديم ردود منظَّمة على الطلبات المتعددة الوسائط التي تتضمّن الصور والفيديوهات والمقاطع الصوتية كمدخلات.

في أسفل هذه الصفحة، ستجد المزيد من الأمثلة، مثل كيفية إنشاء قيم تعداد كناتج.

قبل البدء

انقر على مزوّد 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.

  • بشكلٍ تلقائي، في ما يتعلّق بحِزم تطوير البرامج (SDK)، تُعدّ جميع الحقول مطلوبة ما لم تحدّدها على أنّها اختيارية في مصفوفة optionalProperties.Firebase AI Logic بالنسبة إلى هذه الحقول الاختيارية، يمكن للنموذج ملء الحقول أو تخطّيها. يُرجى العِلم أنّ هذا الإعداد يختلف عن السلوك التلقائي لمقدِّمي الخدمة Gemini API إذا كنت تستخدم حِزم SDK للخادم أو واجهة برمجة التطبيقات مباشرةً.

الخطوة 2: إنشاء إخراج JSON باستخدام مخطّط الاستجابة

قبل تجربة هذا النموذج، أكمل القسم قبل البدء من هذا الدليل لإعداد مشروعك وتطبيقك.
في هذا القسم، ستنقر أيضًا على زر لمقدّم الخدمة الذي اخترته Gemini API حتى يظهر لك محتوى خاص بمقدّم الخدمة في هذه الصفحة.

يوضّح المثال التالي كيفية إنشاء ناتج JSON منظَّم.

عند إنشاء مثيل GenerativeModel، حدِّد responseMimeType المناسب (في هذا المثال، application/json) بالإضافة إلى responseSchema الذي تريد أن يستخدمه النموذج.

Swift


import FirebaseAI

// 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-2.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، تكون الطرق في حزمة تطوير البرامج (SDK) هذه عبارة عن دوال معلّقة ويجب استدعاؤها من نطاق روتين فرعي.

// 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-2.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، تعرض طرق العرض المباشر في حزمة تطوير البرامج (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-2.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-2.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-2.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-2.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 FirebaseAI

// 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-2.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، تكون الطرق في حزمة تطوير البرامج (SDK) هذه عبارة عن دوال معلّقة ويجب استدعاؤها من نطاق روتين فرعي.

// 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-2.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، تعرض طرق العرض المباشر في حزمة تطوير البرامج (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-2.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-2.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-2.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-2.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 النماذج، تتضمّن هذه المَعلمات الحد الأقصى لعدد الرموز المميزة للناتج ودرجة الحرارة وtopK وtopP. بالنسبة إلى نماذج Imagen، تشمل هذه القيود نسبة العرض إلى الارتفاع، وإنشاء صور أشخاص، والعلامات المائية، وما إلى ذلك.
  • استخدِم إعدادات الأمان لتعديل احتمالية تلقّي ردود قد تُعتبر ضارة، بما في ذلك خطاب الكراهية والمحتوى الجنسي الفاضح.
  • اضبط تعليمات النظام لتوجيه سلوك النموذج. هذه الميزة تشبه المقدمة التي تضيفها قبل أن يتلقّى النموذج أي تعليمات أخرى من المستخدم النهائي.


تقديم ملاحظات حول تجربتك مع Firebase AI Logic