Der Gemini API gibt Antworten standardmäßig als unstrukturierten Text zurück. Einige Anwendungsfälle erfordern jedoch strukturierten Text wie JSON. Beispielsweise können Sie die Antwort für andere nachgelagerte Aufgaben verwenden, die ein festgelegtes Datenschema erfordern.
Damit die generierte Ausgabe des Modells immer einem bestimmten Schema entspricht, können Sie ein Antwortschema definieren, das als Vorlage für Modellantworten dient. Anschließend können Sie Daten direkt aus der Ausgabe des Modells extrahieren, ohne dass eine umfangreiche Nachbearbeitung erforderlich ist.
Hier einige Beispiele:
Sorgen Sie dafür, dass die Antwort eines Modells gültiges JSON erzeugt und dem von Ihnen bereitgestellten Schema entspricht.
Das Modell kann beispielsweise strukturierte Einträge für Rezepte generieren, die immer den Rezeptnamen, die Zutatenliste und die Schritte enthalten. Diese Informationen lassen sich dann 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 einem bestimmten Satz von Labels annotieren lassen (z. B. einem bestimmten Satz von Enums wiepositiveundnegative), anstatt Labels zu verwenden, die das Modell erzeugt (die einen gewissen Grad an Variabilität wiegood,positive,negativeoderbadaufweisen könnten).
In diesem Leitfaden wird beschrieben, wie Sie eine JSON-Ausgabe 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 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, lesen Sie den Startleitfaden. Dort 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 Ihrer Prompts empfehlen wir die Verwendung von Google AI Studio.
Modelle, die diese Funktion unterstützen
gemini-4-argongemini-3.8-flash(und die älterengemini-3.7-flash,gemini-3.6-flashundgemini-3.5-flash)gemini-3.5-flash-lite(und die älteregemini-3.1-flash-lite)
Die Modelle gemini-3.1-pro-preview und die allgemeinen Gemini 2.5-Modelle (die verworfen wurden) unterstützen diese Funktion ebenfalls.
Schritt 1: Antwortschema definieren
Sie können ein Antwortschema definieren, 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 sogar Beschreibungen zu verwenden.
Hinweise zu Antwortschemas
Beachten Sie beim Schreiben des Antwortschemas Folgendes:
Die Größe des Antwortschemas wird auf das Eingabetokenlimit angerechnet.
Das Antwortschema-Feature unterstützt die folgenden MIME-Typen für Antworten:
application/json: Ausgabe-JSON, wie im Antwortschema definiert (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).
Das 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 verarbeiten, ignoriert aber das Feld. Die obige Liste ist eine Teilmenge des OpenAPI 3.0-Schemaobjekts.
Standardmäßig werden für Firebase AI Logic-SDKs alle Felder als erforderlich betrachtet, sofern Sie sie nicht in einem
optionalProperties-Array als optional angeben. Bei diesen optionalen Feldern kann das Modell die Felder ausfüllen oder überspringen. Beachten Sie, dass dies das Gegenteil des Standardverhaltens der beiden Gemini API-Anbieter ist, wenn Sie deren Server-SDKs oder API direkt verwenden.
Schritt 2: JSON-Ausgabe mit Ihrem Antwortschema generieren
|
Bevor Sie dieses Beispiel ausprobieren, führen Sie die Schritte im Abschnitt Vorbereitung dieses Leitfadens aus, um Ihr Projekt und Ihre App einzurichten. In diesem Abschnitt klicken Sie auch auf eine Schaltfläche für den ausgewählten Gemini API-Anbieter, damit Sie auf dieser Seite anbieterspezifische Inhalte sehen. |
Im folgenden Beispiel wird gezeigt, wie eine strukturierte JSON-Ausgabe generiert wird.
Geben Sie beim Erstellen der GenerativeModel-Instanz die entsprechende responseMimeType (in diesem Beispiel application/json) sowie die responseSchema an, die 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_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
In Kotlin sind die Methoden in diesem SDK Suspend-Funktionen und müssen aus einem Koroutinenbereich 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_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
In Java geben die Streamingmethoden in diesem SDK einenPublisher-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 */ "<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);
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_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.");
Hier erfahren Sie, wie Sie ein Modell auswählen, die für Ihren Anwendungsfall und Ihre App geeignet sind.
Weitere Beispiele
Hier sind einige zusätzliche Beispiele dafür, wie Sie strukturierte Ausgaben verwenden und generieren können.Enum-Werte als Ausgabe generieren
|
Bevor Sie dieses Beispiel ausprobieren, führen Sie die Schritte im Abschnitt Vorbereitung dieses Leitfadens aus, um Ihr Projekt und Ihre App einzurichten. In diesem Abschnitt klicken Sie auch auf eine Schaltfläche für den ausgewählten Gemini API-Anbieter, damit Sie auf dieser Seite anbieterspezifische Inhalte sehen. |
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 identifizieren. 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 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
In Kotlin sind die Methoden in diesem SDK Suspend-Funktionen und müssen aus einem Koroutinenbereich 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_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
In Java geben die Streamingmethoden in diesem SDK einenPublisher-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 */ "<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);
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_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.");
Hier erfahren Sie, wie Sie ein Modell auswählen, die für Ihren Anwendungsfall und Ihre App geeignet sind.
Weitere Optionen zum Steuern der Inhaltsgenerierung
- 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, z. B. maximale Anzahl von Ausgabetokens, Wahrscheinlichkeit wiederholter Ausgabetokens usw.
- Mit den Sicherheitseinstellungen können Sie die Wahrscheinlichkeit anpassen, dass Sie Antworten erhalten, die als schädlich eingestuft werden könnten, einschließlich Hassrede und sexuell expliziter Inhalte.
- Systemanweisungen festlegen, um das Verhalten des Modells zu steuern. Diese Funktion ist wie eine Präambel, die Sie hinzufügen, bevor das Modell weiteren Anweisungen des Endnutzers ausgesetzt wird.
Feedback zu Ihren Erfahrungen mit Firebase AI Logic geben