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

Gemini API renvoie des réponses sous forme de texte non structuré par défaut. Toutefois, 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 les 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'UI 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 de libellés (par exemple, un ensemble spécifique d'énums comme positive et negative), plutôt qu'avec des libellés produits par le modèle (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, 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.

Vous trouverez d'autres exemples en bas de cette page, 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 et le code spécifiques à ce fournisseur sur cette page.

Si ce n'est pas déjà fait, suivez le guide de démarrage, qui décrit comment configurer votre projet Firebase, associer 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, et même obtenir un extrait de code généré, nous vous recommandons d'utiliser Google AI Studio.

Étape 1 : Définissez 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 le nom du champ et le contexte de votre requête. Pour que votre intention soit 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

Tenez compte des points suivants 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 un fichier JSON tel que défini dans le schéma de réponse (utile pour les exigences de sortie structurée)

    • text/x.enum : affiche 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 SDK Firebase AI Logic, tous les champs sont considérés comme obligatoires, sauf si vous les spécifiez comme facultatifs dans un tableau optionalProperties. 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 fournisseurs Gemini API si vous utilisez leurs SDK serveur ou leur API directement.

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

Avant d'essayer cet exemple, suivez la section Avant de commencer de ce guide pour configurer votre projet et votre application.
Dans cette section, vous devez également cliquer sur un bouton pour le fournisseur Gemini API de votre choix afin d'afficher le contenu spécifique à ce 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é (application/json dans cet exemple) ainsi que le responseSchema que vous souhaitez que le modèle utilise.

Swift


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

Pour Kotlin, les méthodes de ce SDK sont des fonctions de suspension et doivent être appelées à partir d'un champ d'application 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-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

Pour Java, les méthodes de streaming de ce SDK renvoient un type Publisher 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-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);

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

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

Exemples supplémentaires

Voici d'autres exemples d'utilisation et de génération de résultats structurés.

Générer des valeurs enum en tant que sortie

Avant d'essayer cet exemple, suivez la section Avant de commencer de ce guide pour configurer votre projet et votre application.
Dans cette section, vous devez également cliquer sur un bouton pour le fournisseur Gemini API de votre choix afin d'afficher le contenu spécifique à ce 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 doit 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 parmi 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 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

Pour Kotlin, les méthodes de ce SDK sont des fonctions de suspension et doivent être appelées à partir d'un champ d'application 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-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

Pour Java, les méthodes de streaming de ce SDK renvoient un type Publisher 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-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);

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

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

  • Découvrez la conception des requêtes pour influencer le modèle et générer des résultats spécifiques à 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, topK et topP. Pour les modèles Imagen, cela inclut 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 des contenus incitant à la haine et à caractère sexuel explicite.
  • Définissez des instructions système pour orienter le comportement du modèle. Cette fonctionnalité est semblable à 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