Создание структурированного вывода (например, JSON и перечислений) с помощью Gemini API.

API Gemini по умолчанию возвращает ответы в виде неструктурированного текста. Однако в некоторых случаях требуется структурированный текст, например JSON. Например, вы можете использовать ответ для других задач, требующих установленной схемы данных.

Чтобы гарантировать, что выходные данные модели всегда соответствуют определённой схеме, можно определить схему ответа , которая служит своего рода шаблоном для ответов модели. После этого вы сможете напрямую извлекать данные из выходных данных модели, сокращая объём постобработки.

Вот несколько примеров:

  • Убедитесь, что ответ модели создает корректный JSON и соответствует предоставленной вами схеме.
    Например, модель может генерировать структурированные записи для рецептов, которые всегда включают название рецепта, список ингредиентов и этапы его приготовления. Затем вы сможете легко анализировать и отображать эту информацию в пользовательском интерфейсе вашего приложения.

  • Ограничить реакцию модели при выполнении задач классификации.
    Например, вы можете заставить модель аннотировать текст с помощью определенного набора меток (например, определенного набора перечислений, таких как positive и negative ), а не меток, которые создает модель (которые могут иметь определенную степень изменчивости, например good , positive , negative или bad ).

В этом руководстве показано, как генерировать выходные данные JSON, предоставляя responseSchema в вызове generateContent . Основное внимание уделяется только текстовому вводу, но Gemini также может генерировать структурированные ответы на мультимодальные запросы, включающие изображения, видео и аудио в качестве входных данных.

В нижней части этой страницы приведены дополнительные примеры, например, как генерировать значения перечисления в качестве выходных данных .

Прежде чем начать

Щелкните своего поставщика API Gemini , чтобы просмотреть специфичный для этого поставщика контент и код на этой странице.

Если вы еще этого не сделали, ознакомьтесь с руководством по началу работы , в котором описывается, как настроить проект Firebase, подключить приложение к Firebase, добавить SDK, инициализировать внутреннюю службу для выбранного поставщика API Gemini и создать экземпляр GenerativeModel .

Для тестирования и итерации ваших подсказок и даже получения сгенерированного фрагмента кода мы рекомендуем использовать Google AI Studio .

Шаг 1 : Определите схему ответа

Определите схему ответа, чтобы указать структуру выходных данных модели, имена полей и ожидаемый тип данных для каждого поля.

При формировании ответа модель использует имя поля и контекст из вашего запроса. Чтобы убедиться в ясности ваших намерений, мы рекомендуем использовать чёткую структуру, однозначные имена полей и даже описания при необходимости.

Соображения относительно схем реагирования

При написании схемы ответа помните следующее:

  • Размер схемы ответа учитывается при расчете лимита входных токенов.

  • Функция схемы ответа поддерживает следующие типы MIME ответов:

    • application/json : вывод JSON, как определено в схеме ответа (полезно для требований структурированного вывода)

    • text/x.enum : вывести значение перечисления, как определено в схеме ответа (полезно для задач классификации)

  • Функция схемы ответа поддерживает следующие поля схемы:

    enum
    items
    maxItems
    nullable
    properties
    required

    Если вы используете неподдерживаемое поле, модель всё равно сможет обработать ваш запрос, но проигнорирует это поле. Обратите внимание, что приведённый выше список — это подмножество объекта схемы OpenAPI 3.0.

  • По умолчанию в Firebase AI Logic SDK все поля считаются обязательными , если только они не указаны как необязательные в массиве optionalProperties . Модель может заполнить эти необязательные поля или пропустить их. Обратите внимание, что это отличается от поведения по умолчанию двух поставщиков Gemini API , если вы используете их серверные SDK или API напрямую.

Шаг 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.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);

Единство


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.");

Узнайте, как выбрать модельподходящий для вашего варианта использования и приложения.

Дополнительные примеры

Вот несколько дополнительных примеров того, как можно использовать и генерировать структурированный вывод.

Генерировать значения перечисления в качестве выходных данных

Прежде чем приступить к работе с этим примером, выполните указания раздела «Перед началом работы» данного руководства, чтобы настроить свой проект и приложение.
В этом разделе вы также нажмете кнопку для выбранного вами поставщика API Gemini , чтобы увидеть на этой странице контент, специфичный для этого поставщика .

В следующем примере показано, как использовать схему ответа для задачи классификации. Модель должна определить жанр фильма на основе его описания. Выходные данные представляют собой одно текстовое значение перечисления, которое модель выбирает из списка значений, определённых в предоставленной схеме ответа.

Чтобы выполнить эту задачу структурированной классификации, вам необходимо указать во время инициализации модели соответствующий 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.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);

Единство


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