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 festgelegtes Datenschema erforderlich ist.

Damit die generierte Ausgabe des Modells immer einem bestimmten Schema entspricht, können Sie ein Antwortschema definieren, das wie eine Blaupause für Modellantworten funktioniert. So können Sie Daten direkt aus der Ausgabe des Modells extrahieren, ohne dass eine aufwendige Nachbearbeitung erforderlich ist.

Hier einige Beispiele:

  • Sicherstellen, dass die Antwort eines Modells gültiges JSON erzeugt und Ihrem angegebenen Schema entspricht.
    Das Modell kann beispielsweise strukturierte Einträge für Rezepte generieren, die immer den Namen des Rezepts, eine Liste der Zutaten und die Zubereitungsschritte enthalten. Anschließend können Sie diese Informationen einfacher in der Benutzeroberfläche Ihrer App parsen und anzeigen.

  • Einschränken, wie ein Modell bei Klassifizierungsaufgaben antworten kann.
    Sie können beispielsweise festlegen, dass das Modell Text mit einer bestimmten Reihe von Labels annotiert (z. B. eine bestimmte Reihe von Enums wie positive und negative) und nicht mit Labels, die das Modell selbst erstellt (die eine gewisse Variabilität aufweisen können, z. B. good, positive, negative oder bad).

In dieser Anleitung wird gezeigt, wie Sie JSON-Ausgaben generieren, indem Sie in einem Aufruf von generateContent ein responseSchema angeben. Der Schwerpunkt liegt auf reinen Texteingaben, aber Gemini kann auch strukturierte Antworten auf multimodale Anfragen erstellen, die Bilder, Videos und Audio als Eingabe enthalten.

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.

Wenn Sie es noch nicht getan haben, folgen Sie der Anleitung für den Einstieg. Dort wird beschrieben, wie Sie Ihr Firebase-Projekt einrichten, Ihre App mit Firebase verbinden, das SDK hinzufügen, den Backend-Dienst für Ihren ausgewählten Gemini API Anbieter initialisieren und eine GenerativeModel Instanz erstellen.

Zum Testen und Iterieren Ihrer Prompts 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 klare Struktur, eindeutige Feldnamen und bei Bedarf auch Beschreibungen zu verwenden.

Hinweise zu Antwortschemas

Beachten Sie beim Schreiben Ihres Antwortschemas Folgendes:

  • Die Größe des Antwortschemas wird auf das Limit für Eingabetokens angerechnet.

  • Die Funktion für Antwortschemas unterstützt die folgenden MIME-Typen für Antworten:

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

    • text/x.enum: Enum-Wert gemäß Definition im Antwortschema ausgeben (nützlich für Klassifizierungsaufgaben)

  • Die Funktion für Antwortschemas 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 verarbeiten, ignoriert das Feld jedoch. Die Liste oben ist eine Teilmenge des OpenAPI 3.0-Schemaobjekts.

  • Standardmäßig werden für Firebase AI Logic SDKs alle Felder als erforderlich betrachtet, es sei denn, Sie geben sie in einem optionalProperties Array als optional an. Für diese optionalen Felder kann das Modell die Felder ausfüllen oder überspringen. Dies 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 Ihrem Antwortschema generieren

Bevor Sie dieses Beispiel ausprobieren, führen Sie die Schritte im Abschnitt Hinweis dieser Anleitung aus, um Ihr Projekt und Ihre App einzurichten.
In diesem Abschnitt klicken Sie auch auf eine Schaltfläche für Ihren ausgewählten Gemini API Anbieter, damit auf dieser Seite anbieterspezifische Inhalte angezeigt werden..

Im folgenden Beispiel wird gezeigt, wie Sie strukturierte JSON-Ausgaben generieren.

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

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

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

Für Java geben die Streaming-Methoden 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-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);

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

Informationen zum Auswählen eines Modells , der für Ihren Anwendungsfall und Ihre App geeignet ist

Weitere Beispiele

Hier sind einige weitere Beispiele zum Verwenden und Generieren strukturierter Ausgaben.

Enum-Werte als Ausgabe generieren

Bevor Sie dieses Beispiel ausprobieren, führen Sie die Schritte im Abschnitt Hinweis dieser Anleitung aus, um Ihr Projekt und Ihre App einzurichten.
In diesem Abschnitt klicken Sie auch auf eine Schaltfläche für Ihren ausgewählten Gemini API Anbieter, damit auf dieser Seite anbieterspezifische Inhalte angezeigt werden..

Im folgenden Beispiel wird gezeigt, wie Sie ein Antwortschema für eine Klassifizierungsaufgabe verwenden. 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 angegebenen Antwortschema definiert sind.

Um diese strukturierte Klassifizierungsaufgabe auszuführen, müssen Sie bei der Modellinitialisierung den entsprechenden responseMimeType (in diesem Beispiel text/x.enum) sowie das responseSchema angeben, das das Modell verwenden soll.

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

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

Für Java geben die Streaming-Methoden 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-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);

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

Informationen zum Auswählen eines Modells , der für Ihren Anwendungsfall und Ihre App geeignet ist

Weitere Optionen zum Steuern der Inhaltserstellung

  • Weitere Informationen zum Prompt-Design damit 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, die Temperatur, Top-K und Top-P. Für Imagen Modelle umfassen sie das Seitenverhältnis, die Personengenerierung, Wasserzeichen usw.
  • Mit Sicherheitseinstellungen können Sie die Wahrscheinlichkeit steuern, Antworten zu erhalten, die als schädlich angesehen werden können, einschließlich Hassreden und sexuell anstößiger Inhalte.
  • Systemanweisungen festlegen, 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 geben zu Ihren Erfahrungen mit Firebase AI Logic