Générer une sortie structurée (comme JSON et énumérations) à l'aide de l'API Gemini

Le Gemini API renvoie des réponses sous forme de texte non structuré par défaut. Cependant, certains cas d'utilisation nécessitent du texte structuré, comme JSON. Par exemple, vous pouvez utiliser la réponse pour d'autres tâches en aval qui nécessitent un schéma de données établi.

Pour vous assurer que la sortie générée du modèle respecte toujours un schéma spécifique, vous pouvez définir un schéma de réponse qui fonctionne comme un plan pour les réponses du modèle. Vous pouvez ensuite extraire directement les données de la sortie du modèle avec moins de post-traitement.

Voici quelques exemples :

  • Assurez-vous que la réponse d'un modèle produit du code JSON valide et qu'elle est conforme au schéma que vous avez fourni.
    Par exemple, le modèle peut générer des entrées structurées pour des recettes qui incluent toujours le nom de la recette, la liste des ingrédients et les étapes. Vous pouvez ensuite analyser et afficher plus facilement ces informations dans l'interface utilisateur de votre application.

  • Limitez la façon dont un modèle peut répondre lors des tâches de classification.
    Par exemple, vous pouvez demander au modèle d'annoter du texte avec un ensemble spécifique d'étiquettes (par exemple, un ensemble spécifique d'énumérations comme positive et negative), plutôt qu'avec des étiquettes que le modèle produit (qui peuvent présenter un certain degré de variabilité comme good, positive, negative ou bad).

Ce guide vous explique comment générer une sortie JSON en fournissant un responseSchema dans un appel à generateContent. Il se concentre sur les entrées textuelles uniquement, mais Gemini peut également produire des réponses structurées aux requêtes multimodales qui incluent des images, des vidéos et de l'audio en entrée.

En bas de cette page, vous trouverez d'autres exemples, comme la façon de générer des valeurs d'énumération en sortie.

Avant de commencer

Cliquez sur votre fournisseur Gemini API pour afficher le contenu spécifique au fournisseur et le code sur cette page.

Si ce n'est pas déjà fait, suivez le guide de démarrage, qui explique comment configurer votre projet Firebase, connecter votre application à Firebase, ajouter le SDK, initialiser le service de backend pour le fournisseur Gemini API de votre choix et créer une instance GenerativeModel.

Pour tester et effectuer des itérations de vos requêtes, nous vous recommandons d'utiliser Google AI Studio.

Étape 1 : Définir un schéma de réponse

Définissez un schéma de réponse pour spécifier la structure de la sortie d'un modèle, les noms des champs et le type de données attendu pour chaque champ.

Lorsqu'un modèle génère sa réponse, il utilise les noms de champs et le contexte de votre requête. Pour vous assurer que votre intention est claire, nous vous recommandons d'utiliser une structure claire, des noms de champs non ambigus et même des descriptions si nécessaire.

Éléments à prendre en compte pour les schémas de réponse

Gardez les points suivants à l'esprit lorsque vous rédigez votre schéma de réponse :

  • La taille du schéma de réponse est comptabilisée dans la limite des jetons d'entrée.

  • La fonctionnalité de schéma de réponse est compatible avec les types MIME de réponse suivants :

    • application/json: génère du code JSON tel que défini dans le schéma de réponse (utile pour les exigences de sortie structurée)

    • text/x.enum: génère une valeur d'énumération telle que définie dans le schéma de réponse (utile pour les tâches de classification)

  • La fonctionnalité de schéma de réponse est compatible avec les champs de schéma suivants :

    enum
    items
    maxItems
    nullable
    properties
    required

    Si vous utilisez un champ non compatible, le modèle peut toujours traiter votre requête, mais il ignore le champ. Notez que la liste ci-dessus est un sous-ensemble de l'objet de schéma OpenAPI 3.0.

  • Par défaut, pour les Firebase AI Logic SDK, tous les champs sont considérés obligatoires , sauf si vous les spécifiez comme facultatifs dans un optionalProperties tableau. Pour ces champs facultatifs, le modèle peut les remplir ou les ignorer. Notez que cela est l'inverse du comportement par défaut des deux Gemini API fournisseurs si vous utilisez leurs SDK serveur ou leur API directement.

Étape 2 : Générer une sortie JSON à l'aide de votre schéma de réponse

Avant d'essayer cet exemple, suivez les étapes de la section Avant de commencer de ce guide pour configurer votre projet et votre application.
Dans cette section, vous cliquerez également sur un bouton pour le fournisseur Gemini API de votre choix afin d'afficher le contenu spécifique au fournisseur sur cette page.

L'exemple suivant montre comment générer une sortie JSON structurée.

Lorsque vous créez l'instance GenerativeModel, spécifiez le responseMimeType approprié (dans cet exemple, application/json), ainsi que le responseSchema que vous souhaitez que le modèle utilise.

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-3-flash-preview",
  // 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

Pour Kotlin, les méthodes de ce SDK sont des fonctions de suspension et doivent être appelées à partir d'une portée de 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-3-flash-preview",
    // 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

Pour Java, les méthodes de streaming de ce SDK renvoient un Publisher type à partir de la bibliothèque 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-3-flash-preview",
            /* 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-3-flash-preview",
  // 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-3-flash-preview',
        // 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-3-flash-preview",
  // 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.");

Découvrez comment choisir un modèle adapté à votre cas d'utilisation et à votre application.

Exemples supplémentaires

Voici quelques exemples supplémentaires d'utilisation et de génération de sorties structurées.

Générer des valeurs d'énumération en sortie

Avant d'essayer cet exemple, suivez les étapes de la section Avant de commencer de ce guide pour configurer votre projet et votre application.
Dans cette section, vous cliquerez également sur un bouton pour le fournisseur Gemini API de votre choix afin d'afficher le contenu spécifique au fournisseur sur cette page.

L'exemple suivant montre comment utiliser un schéma de réponse pour une tâche de classification. Le modèle est invité à identifier le genre d'un film en fonction de sa description. La sortie est une valeur d'énumération en texte brut que le modèle sélectionne dans une liste de valeurs définies dans le schéma de réponse fourni.

Pour effectuer cette tâche de classification structurée, vous devez spécifier lors de l'initialisation du modèle le responseMimeType approprié (dans cet exemple, text/x.enum), ainsi que le responseSchema que vous souhaitez que le modèle utilise.

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-3-flash-preview",
  // 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

Pour Kotlin, les méthodes de ce SDK sont des fonctions de suspension et doivent être appelées à partir d'une portée de 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-3-flash-preview",
    // 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

Pour Java, les méthodes de streaming de ce SDK renvoient un Publisher type à partir de la bibliothèque 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-3-flash-preview",
            /* 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-3-flash-preview",
  // 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-3-flash-preview',
        // 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-3-flash-preview",
  // 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.");

Découvrez comment choisir un modèle adapté à votre cas d'utilisation et à votre application.

Autres options pour contrôler la génération de contenu

  • En savoir plus sur la conception de requêtes pour influencer le modèle afin qu'il génère une sortie spécifique à vos besoins.
  • Configurez les paramètres du modèle pour contrôler la manière dont il génère une réponse. Pour les modèles Gemini, ces paramètres incluent le nombre maximal de jetons de sortie, la température, le top-K et le top-P. Pour les modèles Imagen, ils incluent le format, la génération de personnes, le filigrane, etc.
  • Utilisez les paramètres de sécurité pour ajuster la probabilité d'obtenir des réponses qui peuvent être considérées comme nuisibles, y compris les discours haineux et les contenus à caractère sexuel explicite.
  • Définissez des instructions système pour orienter le comportement du modèle. Cette fonctionnalité s'apparente à un préambule que vous ajoutez avant que le modèle ne soit exposé à d'autres instructions de l'utilisateur final.


Envoyer des commentaires sur votre expérience avec Firebase AI Logic