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

Gemini API renvoie par défaut les réponses sous forme de texte non structuré. 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 par le modèle respecte toujours un schéma spécifique, vous pouvez définir un schéma de réponse qui fonctionne comme un modèle 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 :

  • S'assurer 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.

  • Limiter 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 telles que positive et negative), plutôt qu'avec des étiquettes produites par le modèle (qui pourraient 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 à des requêtes multimodales qui incluent des images, des vidéos et des fichiers audio en entrée.

Vous trouverez d'autres exemples au bas de cette page, par exemple pour 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 au fournisseur 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.

Modèles compatibles avec cette fonctionnalité

  • gemini-4-argon
  • gemini-3.8-flash (et les versions plus anciennes gemini-3.7-flash, gemini-3.6-flash et gemini-3.5-flash)
  • gemini-3.5-flash-lite (et l'ancien gemini-3.1-flash-lite)

Les modèles gemini-3.1-pro-preview et Gemini 2.5 à usage général (qui sont obsolètes) sont également compatibles avec cette fonctionnalité.

É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 le nom du champ et le contexte de votre prompt. 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.

Remarques concernant 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 : sortie JSON telle que définie 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 renseigner ou les ignorer. Notez que ce comportement est l'inverse du comportement par défaut des deux fournisseurs Gemini API si vous utilisez directement leurs SDK de serveur ou leur API.

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

Avant d'essayer cet exemple, suivez les instructions 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 correspondant au 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é (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_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

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_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

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

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 sorties structurées.

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

Avant d'essayer cet exemple, suivez les instructions 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 correspondant au 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 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

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_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

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

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 comment concevoir des requêtes afin d'influencer le modèle pour qu'il génère des résultats adaptés à vos besoins.
  • Configurez les paramètres du modèle pour contrôler la façon dont le modèle génère une réponse, comme le nombre maximal de jetons de sortie, la probabilité de jetons de sortie répétés, etc.
  • Utilisez les paramètres de sécurité pour ajuster la probabilité d'obtenir des réponses pouvant être considérées comme nuisibles, y compris l'incitation à la haine et le contenu à 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