با استفاده از Gemini API خروجی ساختاریافته (مانند JSON و enums) ایجاد کنید

Gemini API به صورت پیش‌فرض پاسخ‌ها را به صورت متن بدون ساختار برمی‌گرداند. با این حال، برخی موارد استفاده به متن ساختاریافته مانند JSON نیاز دارند. به عنوان مثال، ممکن است از پاسخ برای سایر کارهای پایین دستی که به یک طرح داده ثابت نیاز دارند استفاده کنید.

برای اطمینان از اینکه خروجی تولید شده مدل همیشه به یک طرح خاص پایبند است، می توانید یک طرح پاسخ تعریف کنید که مانند یک طرح اولیه برای پاسخ های مدل عمل می کند. سپس می توانید مستقیماً داده ها را از خروجی مدل با پس پردازش کمتر استخراج کنید.

در اینجا چند نمونه آورده شده است:

  • اطمینان حاصل کنید که پاسخ یک مدل JSON معتبر تولید می کند و با طرح ارائه شده شما مطابقت دارد.
    به عنوان مثال، مدل می‌تواند ورودی‌های ساختاریافته‌ای را برای دستور العمل‌ها ایجاد کند که همیشه شامل نام دستور غذا، فهرست مواد تشکیل دهنده و مراحل است. سپس می توانید به راحتی این اطلاعات را در رابط کاربری برنامه خود تجزیه و نمایش دهید.

  • نحوه پاسخگویی یک مدل را در طول وظایف طبقه بندی محدود کنید.
    به عنوان مثال، می‌توانید مدل را به جای برچسب‌هایی که مدل تولید می‌کند (که می‌تواند درجه‌ای از تنوع مانند good ، positive ، positive یا negative داشته باشد)، متنی را با مجموعه‌ای از برچسب‌ها (مثلاً مجموعه‌ای خاص از فهرست‌ها مانند مثبت و negativebad کند.

این راهنما به شما نشان می‌دهد که چگونه می‌توانید خروجی JSON را با ارائه responseSchema در یک فراخوان برای generateContent ایجاد کنید. بر روی ورودی فقط متن تمرکز دارد، اما Gemini همچنین می‌تواند پاسخ‌های ساختاری به درخواست‌های چندوجهی تولید کند که شامل تصاویر، ویدیوها و صدا به عنوان ورودی است.

در پایین این صفحه نمونه های بیشتری وجود دارد، مانند نحوه تولید مقادیر enum به عنوان خروجی .

قبل از شروع

برای مشاهده محتوا و کد ارائه دهنده خاص در این صفحه، روی ارائه دهنده API Gemini خود کلیک کنید.

اگر قبلاً این کار را نکرده‌اید، راهنمای شروع را کامل کنید، که نحوه راه‌اندازی پروژه Firebase را توضیح می‌دهد، برنامه خود را به Firebase متصل کنید، SDK را اضافه کنید، سرویس Backend را برای ارائه‌دهنده API Gemini انتخابی خود مقداردهی کنید و یک نمونه 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 مشخص کنید. برای این فیلدهای اختیاری، مدل می تواند فیلدها را پر کند یا آنها را رد کند. توجه داشته باشید که اگر مستقیماً از SDK سرور یا API آنها استفاده کنید، این برخلاف رفتار پیش‌فرض دو ارائه‌دهنده API Gemini است.

مرحله 2 : خروجی JSON را با استفاده از طرح پاسخ خود ایجاد کنید

قبل از امتحان این نمونه، بخش قبل از شروع این راهنما را تکمیل کنید تا پروژه و برنامه خود را راه اندازی کنید.
در آن بخش، همچنین روی دکمه ای برای ارائه دهنده API Gemini انتخابی خود کلیک می کنید تا محتوای خاص ارائه دهنده را در این صفحه ببینید .

مثال زیر نحوه تولید خروجی JSON ساخت یافته را نشان می دهد.

هنگامی که نمونه GenerativeModel ایجاد می کنید، responseMimeType مناسب (در این مثال، application/json ) و همچنین responseSchema که می خواهید مدل استفاده کند را مشخص کنید.

سویفت


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.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 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.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

برای جاوا، روش‌های پخش در این 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.0-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.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_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.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);

وحدت


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.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 را به عنوان خروجی تولید کنید

قبل از امتحان این نمونه، بخش قبل از شروع این راهنما را تکمیل کنید تا پروژه و برنامه خود را راه اندازی کنید.
در آن بخش، همچنین روی دکمه ای برای ارائه دهنده API Gemini انتخابی خود کلیک می کنید تا محتوای خاص ارائه دهنده را در این صفحه ببینید .

مثال زیر نحوه استفاده از طرح پاسخ را برای یک کار طبقه بندی نشان می دهد. از مدل خواسته می شود تا ژانر یک فیلم را بر اساس توضیحات آن شناسایی کند. خروجی یک مقدار enum متن ساده است که مدل از لیستی از مقادیری که در طرح پاسخ ارائه شده تعریف شده اند، انتخاب می کند.

برای انجام این کار طبقه‌بندی ساختاریافته، باید در طول اولیه‌سازی مدل، responseMimeType مناسب (در این مثال، text/x.enum ) و همچنین responseSchema را که می‌خواهید مدل استفاده کند، مشخص کنید.

سویفت


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.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 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.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

برای جاوا، روش‌های پخش در این 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.0-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.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_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.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);

وحدت


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.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 بازخورد بدهید