Как создавать структурированные выходные данные (например, JSON и перечисления) с помощью Gemini API

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

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

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

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

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

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

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

Подготовка

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

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

Для тестирования и доработки запросов рекомендуем использовать Google AI Studio.

Модели, поддерживающие эту функцию

  • gemini-4-argon
  • gemini-3.8-flash (и более старые версии gemini-3.7-flash, gemini-3.6-flash и gemini-3.5-flash)
  • gemini-3.5-flash-lite (и более старый gemini-3.1-flash-lite)

Модели gemini-3.1-pro-preview и Gemini 2.5 общего назначения (которые больше не поддерживаются) также поддерживают эту возможность.

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

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

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

Что нужно учитывать при работе со схемами ответов

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

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

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

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

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

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

    enum
    items
    maxItems
    nullable
    properties
    required

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

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

Шаг 2. Сгенерируйте выходные данные JSON, используя схему ответа

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

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

При создании экземпляра GenerativeModel укажите подходящий responseMimeType (в этом примере – application/json), а также responseSchema, который должна использовать модель.

Swift


import FirebaseAILogic

// Provide a JSON schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
let jsonSchema = Schema.object(
  properties: [
    "characters": Schema.array(
      items: .object(
        properties: [
          "name": .string(),
          "age": .integer(),
          "species": .string(),
          "accessory": .enumeration(values: ["hat", "belt", "shoes"]),
        ],
        optionalProperties: ["accessory"]
      )
    ),
  ]
)

// Initialize the Gemini Developer API backend service.
let ai = FirebaseAI.firebaseAI(backend: .googleAI())

// Create a `GenerativeModel` instance with a model that supports your use case.
let model = ai.generativeModel(
  modelName: "GEMINI_MODEL_NAME",
  // 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_MODEL_NAME",
    // 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 */ "<var>GEMINI_MODEL_NAME</var>",
            /* 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_MODEL_NAME",
  // 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_MODEL_NAME',
        // 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_MODEL_NAME",
  // 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.");

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

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

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

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

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

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

Чтобы выполнить эту задачу структурированной классификации, при инициализации модели необходимо указать подходящий responseMimeType (в этом примере text/x.enum), а также responseSchema, который должна использовать модель.

Swift


import FirebaseAILogic

// Provide an enum schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
let enumSchema = Schema.enumeration(values: ["drama", "comedy", "documentary"])

// Initialize the Gemini Developer API backend service.
let ai = FirebaseAI.firebaseAI(backend: .googleAI())

// Create a `GenerativeModel` instance with a model that supports your use case.
let model = ai.generativeModel(
  modelName: "GEMINI_MODEL_NAME",
  // 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_MODEL_NAME",
    // 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 */ "<var>GEMINI_MODEL_NAME</var>",
            /* 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_MODEL_NAME",
  // 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_MODEL_NAME',
        // 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_MODEL_NAME",
  // 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.");

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

Другие способы управления генерацией контента

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


Оставить отзыв о работе с Firebase AI Logic