Strukturierte Ausgabe (z. B. JSON und Enumerationen) mit der Gemini API generieren

Die Gemini API gibt Antworten standardmäßig als unstrukturierten Text zurück. Für einige Anwendungsfälle ist jedoch strukturierter Text wie JSON erforderlich. Möglicherweise verwenden Sie die Antwort für andere nachgelagerte Aufgaben, für die ein etabliertes Datenschema erforderlich ist.

Damit die generierte Ausgabe des Modells immer einem bestimmten Schema entspricht, können Sie ein Antwortschema definieren, das als Vorlage für Modellantworten dient. Sie können dann Daten direkt aus der Ausgabe des Modells extrahieren, ohne dass eine umfangreiche Nachbearbeitung erforderlich ist.

Hier sind einige Beispiele:

  • Sorgen Sie dafür, dass die Antwort eines Modells gültiges JSON enthält und Ihrem bereitgestellten Schema entspricht.
    Das Modell kann beispielsweise strukturierte Einträge für Rezepte generieren, die immer den Rezeptnamen, die Zutatenliste und die Zubereitungsschritte enthalten. Anschließend können Sie diese Informationen leichter parsen und in der Benutzeroberfläche Ihrer App anzeigen.

  • Einschränken, wie ein Modell bei Klassifizierungsaufgaben reagieren kann.
    Sie können das Modell beispielsweise Text mit einer bestimmten Gruppe von Labels (z. B. einer bestimmten Gruppe von Enums wie positive und negative) annotieren lassen, anstatt mit Labels, die vom Modell generiert werden (die eine gewisse Variabilität aufweisen können, z. B. good, positive, negative oder bad).

In dieser Anleitung erfahren Sie, wie Sie JSON-Ausgabe generieren, indem Sie responseSchema in einem Aufruf von generateContent angeben. Sie konzentriert sich auf reine Texteingaben, aber Gemini kann auch strukturierte Antworten auf multimodale Anfragen mit Bildern, Videos und Audio als Eingabe generieren.

Unten auf dieser Seite finden Sie weitere Beispiele, z. B. zum Generieren von Enum-Werten als Ausgabe.

Hinweis

Klicken Sie auf Ihren Gemini API-Anbieter, um anbieterspezifische Inhalte und Code auf dieser Seite aufzurufen.

Falls noch nicht geschehen, folgen Sie dem Startleitfaden. Darin wird beschrieben, wie Sie Ihr Firebase-Projekt einrichten, Ihre App mit Firebase verbinden, das SDK hinzufügen, den Backend-Dienst für den ausgewählten Gemini API-Anbieter initialisieren und eine GenerativeModel-Instanz erstellen.

Zum Testen und Iterieren von Prompts und zum Generieren von Code-Snippets empfehlen wir die Verwendung von Google AI Studio.

Schritt 1: Antwortschema definieren

Definieren Sie ein Antwortschema, um die Struktur der Modellausgabe, die Feldnamen und den erwarteten Datentyp für jedes Feld festzulegen.

Wenn ein Modell eine Antwort generiert, verwendet es den Feldnamen und den Kontext aus Ihrem Prompt. Damit Ihre Absicht klar ist, empfehlen wir, eine übersichtliche Struktur, eindeutige Feldnamen und bei Bedarf auch Beschreibungen zu verwenden.

Hinweise zu Antwortschemas

Beachten Sie beim Schreiben des Antwortschemas Folgendes:

  • Die Größe des Antwortschemas wird auf das Eingabetokenlimit angerechnet.

  • Die Funktion „Antwortschema“ unterstützt die folgenden MIME-Typen für Antworten:

    • application/json: JSON-Ausgabe gemäß dem Antwortschema (nützlich für Anforderungen an strukturierte Ausgaben)

    • text/x.enum: Gibt einen Enum-Wert aus, wie im Antwortschema definiert (nützlich für Klassifizierungsaufgaben).

  • Die Funktion „Antwortschema“ unterstützt die folgenden Schemafelder:

    enum
    items
    maxItems
    nullable
    properties
    required

    Wenn Sie ein nicht unterstütztes Feld verwenden, kann das Modell Ihre Anfrage trotzdem bearbeiten, ignoriert das Feld jedoch. Die obige Liste ist eine Teilmenge des OpenAPI 3.0-Schemaobjekts.

  • Standardmäßig gelten für Firebase AI Logic-SDKs alle Felder als erforderlich, sofern Sie sie nicht in einem optionalProperties-Array als optional angeben. Bei diesen optionalen Feldern kann das Modell die Felder ausfüllen oder überspringen. Das ist das Gegenteil des Standardverhaltens der beiden Gemini API-Anbieter, wenn Sie ihre Server-SDKs oder ihre API direkt verwenden.

Schritt 2: JSON-Ausgabe mit dem Antwortschema generieren

Bevor Sie dieses Beispiel ausprobieren, müssen Sie den Abschnitt Vorbereitung in diesem Leitfaden durcharbeiten, um Ihr Projekt und Ihre App einzurichten.
In diesem Abschnitt klicken Sie auch auf eine Schaltfläche für den von Ihnen ausgewählten Gemini API-Anbieter, damit auf dieser Seite anbieterspezifische Inhalte angezeigt werden.

Das folgende Beispiel zeigt, wie strukturierte JSON-Ausgabe generiert wird.

Wenn Sie die GenerativeModel-Instanz erstellen, geben Sie die entsprechende responseMimeType (in diesem Beispiel application/json) sowie die responseSchema an, die das Modell verwenden soll.

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

Für Kotlin sind die Methoden in diesem SDK Suspend-Funktionen und müssen aus einem Coroutine-Bereich aufgerufen werden.

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

Für Java geben die Streamingmethoden in diesem SDK einen Publisher-Typ aus der Reactive Streams-Bibliothek zurück.

// 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);

Einheit


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

Hier erfahren Sie, wie Sie ein Modell auswählen, der für Ihren Anwendungsfall und Ihre App geeignet ist.

Weitere Beispiele

Hier sind einige zusätzliche Beispiele für die Verwendung und Generierung strukturierter Ausgaben.

Enum-Werte als Ausgabe generieren

Bevor Sie dieses Beispiel ausprobieren, müssen Sie den Abschnitt Vorbereitung in diesem Leitfaden durcharbeiten, um Ihr Projekt und Ihre App einzurichten.
In diesem Abschnitt klicken Sie auch auf eine Schaltfläche für den von Ihnen ausgewählten Gemini API-Anbieter, damit auf dieser Seite anbieterspezifische Inhalte angezeigt werden.

Das folgende Beispiel zeigt, wie ein Antwortschema für eine Klassifizierungsaufgabe verwendet wird. Das Modell wird aufgefordert, das Genre eines Films anhand seiner Beschreibung zu ermitteln. Die Ausgabe ist ein Nur-Text-Enum-Wert, der vom Modell aus einer Liste von Werten ausgewählt wird, die im bereitgestellten Antwortschema definiert sind.

Für diese strukturierte Klassifizierungsaufgabe müssen Sie bei der Modellinitialisierung die entsprechende responseMimeType (in diesem Beispiel text/x.enum) sowie die responseSchema angeben, die das Modell verwenden soll.

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

Für Kotlin sind die Methoden in diesem SDK Suspend-Funktionen und müssen aus einem Coroutine-Bereich aufgerufen werden.

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

Für Java geben die Streamingmethoden in diesem SDK einen Publisher-Typ aus der Reactive Streams-Bibliothek zurück.

// 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);

Einheit


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

Hier erfahren Sie, wie Sie ein Modell auswählen, der für Ihren Anwendungsfall und Ihre App geeignet ist.

Weitere Optionen zum Steuern der Inhaltserstellung

  • Weitere Informationen zum Erstellen von Prompts, mit denen Sie das Modell so beeinflussen können, dass es Ausgaben generiert, die Ihren Anforderungen entsprechen.
  • Modellparameter konfigurieren, um zu steuern, wie das Modell eine Antwort generiert. Für Gemini-Modelle umfassen diese Parameter die maximale Anzahl von Ausgabetokens, Temperatur, Top‑K und Top‑P. Für Imagen-Modelle gehören dazu unter anderem das Seitenverhältnis, die Personengenerierung und das Wasserzeichen.
  • Mit Sicherheitseinstellungen können Sie anpassen, wie wahrscheinlich es ist, dass Sie Antworten erhalten, die als schädlich eingestuft werden könnten, z. B. Hassrede und sexuell explizite Inhalte.
  • Legen Sie Systemanweisungen fest, um das Verhalten des Modells zu steuern. Diese Funktion ist wie eine Präambel, die Sie hinzufügen, bevor das Modell für weitere Anweisungen des Endnutzers freigegeben wird.


Feedback zu Firebase AI Logic geben