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

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

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

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

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

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

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

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

قبل از شروع

اگر قبلاً این کار را نکرده‌اید، راهنمای شروع را کامل کنید، که نحوه راه‌اندازی پروژه Firebase را توضیح می‌دهد، برنامه خود را به Firebase متصل کنید، SDK را اضافه کنید، سرویس Vertex AI را راه‌اندازی کنید، و یک نمونه GenerativeModel ایجاد کنید.

مرحله 1 : یک طرح پاسخ را تعریف کنید

برای تعیین ساختار خروجی مدل، نام فیلدها و نوع داده مورد انتظار برای هر فیلد، یک طرح پاسخ تعریف کنید.

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

ملاحظات برای طرحواره های پاسخ

هنگام نوشتن طرح پاسخ به موارد زیر توجه کنید:

  • اندازه طرح پاسخ در حد توکن ورودی به حساب می آید.

  • ویژگی طرح پاسخ از انواع MIME پاسخ زیر پشتیبانی می کند:

    • application/json : خروجی JSON همانطور که در طرح پاسخ تعریف شده است (مفید برای الزامات خروجی ساختاریافته)

    • text/x.enum : خروجی مقدار enum همانطور که در طرح پاسخ تعریف شده است (مفید برای وظایف طبقه بندی)

  • ویژگی طرحواره پاسخ از فیلدهای طرحواره زیر پشتیبانی می کند:

    enum
    items
    maxItems
    nullable
    properties
    required

    اگر از یک فیلد پشتیبانی‌نشده استفاده می‌کنید، مدل همچنان می‌تواند به درخواست شما رسیدگی کند، اما فیلد را نادیده می‌گیرد. توجه داشته باشید که لیست بالا زیرمجموعه ای از شی طرح OpenAPI 3.0 است (به مرجع طرحواره Vertex AI مراجعه کنید).

  • به‌طور پیش‌فرض، برای Vertex AI در Firebase SDK، همه فیلدها ضروری در نظر گرفته می‌شوند مگر اینکه آنها را به‌عنوان اختیاری در آرایه optionalProperties مشخص کنید. برای این فیلدهای اختیاری، مدل می تواند فیلدها را پر کند یا آنها را رد کند.

    توجه داشته باشید که این برخلاف رفتار پیش‌فرض برای Vertex AI Gemini API است.

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

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

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

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

نحوه انتخاب یک مدل و به صورت اختیاری مکان مناسب برای مورد استفاده و برنامه خود را بیاموزید.

نمونه های اضافی

برای مشاهده نمونه‌های اضافی از نحوه استفاده و تولید خروجی ساختاریافته، فهرست طرح‌واره‌های نمونه و پاسخ‌های مدل را در اسناد Google Cloud بررسی کنید.

مقادیر enum را به عنوان خروجی تولید کنید

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

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

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

نحوه انتخاب یک مدل و به صورت اختیاری مکان مناسب برای مورد استفاده و برنامه خود را بیاموزید.

گزینه های دیگر برای کنترل تولید محتوا

  • در مورد طراحی سریع بیشتر بیاموزید تا بتوانید مدل را تحت تأثیر قرار دهید تا خروجی خاصی برای نیازهای شما ایجاد کند.
  • پارامترهای مدل را برای کنترل نحوه ایجاد پاسخ توسط مدل پیکربندی کنید. برای مدل‌های Gemini ، این پارامترها شامل حداکثر توکن‌های خروجی، دما، topK و topP هستند. برای مدل های Imagen ، این موارد شامل نسبت ابعاد، تولید شخص، واترمارک و غیره است.
  • از تنظیمات ایمنی برای تنظیم احتمال دریافت پاسخ هایی که ممکن است مضر تلقی شوند، از جمله سخنان مشوق عداوت و تنفر و محتوای صریح جنسی استفاده کنید.
  • دستورالعمل های سیستم را برای هدایت رفتار مدل تنظیم کنید. این ویژگی مانند یک «مقدمه» است که قبل از اینکه مدل در معرض هر دستورالعمل دیگری از کاربر نهایی قرار گیرد، اضافه می‌کنید.


درباره تجربه خود با Vertex AI در Firebase بازخورد بدهید