Die Gemini API gibt standardmäßig Antworten als unstrukturierten Text zurück. Für einige Anwendungsfälle ist jedoch strukturierter Text wie JSON erforderlich. Möglicherweise verwenden Sie die Antwort beispielsweise für andere nachgelagerte Aufgaben, für die ein festgelegtes Datenschema erforderlich ist.
Damit die vom Modell generierte Ausgabe immer einem bestimmten Schema entspricht, können Sie ein Antwortschema definieren, das als Blaupause für Modellantworten dient. Sie können dann mit weniger Nachbearbeitung direkt Daten aus der Ausgabe des Modells extrahieren.
Hier sind einige Beispiele:
Achten Sie darauf, dass die Antwort eines Modells gültiges JSON generiert und dem angegebenen Schema entspricht.
Das Modell kann beispielsweise strukturierte Einträge für Rezepte generieren, die immer den Rezeptnamen, die Zutatenliste und die Schritte enthalten. Anschließend können Sie diese Informationen leichter analysieren und in der Benutzeroberfläche Ihrer App anzeigen.Einschränken, wie ein Modell bei Klassifizierungsaufgaben reagieren kann.
Sie können beispielsweise festlegen, dass das Modell Text mit einer bestimmten Gruppe von Labels (z. B. einer bestimmten Gruppe von Enumerationen wiepositive
undnegative
) annotiert, anstatt mit Labels, die vom Modell generiert werden (die eine gewisse Variabilität haben können, z. B.good
,positive
,negative
oderbad
).
In dieser Anleitung wird beschrieben, wie Sie eine JSON-Ausgabe generieren, indem Sie einen responseSchema
in einen Aufruf von generateContent
einfügen. Der Schwerpunkt liegt auf der Eingabe von reinen Texten. Gemini kann aber auch strukturierte Antworten auf multimodale Anfragen generieren, die Bilder, Videos und Audio als Eingabe enthalten.
Unten auf dieser Seite finden Sie weitere Beispiele, z. B. wie Sie Enum-Werte als Ausgabe generieren.
Hinweis
Klicke auf deinen Gemini API-Anbieter, um dir anbieterspezifische Inhalte und Code auf dieser Seite anzusehen. |
Sehen Sie sich den Startleitfaden an, in dem beschrieben wird, 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 und zum Generieren eines 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 klare Struktur, eindeutige Feldnamen und bei Bedarf auch Beschreibungen.
Hinweise zu Antwortschemata
Beachten Sie beim Erstellen Ihres Antwortschemas Folgendes:
Die Größe des Antwortschemas wird auf das Eingabetokenlimit angerechnet.
Die Antwortschema-Funktion unterstützt die folgenden MIME-Typen für Antworten:
application/json
: JSON-Ausgabe gemäß dem im Antwortschema definierten Format (nützlich für Anforderungen an die strukturierte Ausgabe)text/x.enum
: Gibt einen im Antwortschema definierten Enum-Wert aus (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 zwar verarbeiten, das Feld wird jedoch ignoriert. Die obige Liste ist eine Teilmenge des OpenAPI 3.0-Schemaobjekts.
Bei Firebase AI Logic-SDKs gelten standardmäßig alle Felder als erforderlich, 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. Hinweis: Das ist das Gegenteil des Standardverhaltens der beiden Gemini API-Anbieter, wenn Sie deren Server-SDKs oder APIs 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 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 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.0-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
In Kotlin sind die Methoden in diesem SDK Suspend-Funktionen und müssen aus einem Coroutine-Kontext 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.0-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
Bei 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 */ "gemini-2.0-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.0-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.0-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.0-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.");
Weitere Informationen zur Auswahl eines Modells
Weitere Beispiele
Hier sind einige weitere Beispiele dafür, wie Sie strukturierte Ausgabe verwenden und generieren können.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 Sie ein Antwortschema für eine Klassifizierungsaufgabe verwenden. Das Modell soll anhand der Beschreibung das Genre eines Films 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 die entsprechende responseMimeType
(in diesem Beispiel text/x.enum
) sowie die responseSchema
angeben, die vom Modell verwendet werden 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.0-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
In Kotlin sind die Methoden in diesem SDK Suspend-Funktionen und müssen aus einem Coroutine-Kontext 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.0-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
Bei 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 */ "gemini-2.0-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.0-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.0-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.0-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.");
Weitere Informationen zur Auswahl eines Modells
Weitere Optionen zur Steuerung der Inhaltsgenerierung
- Weitere Informationen zum Design von Prompts, damit Sie das Modell beeinflussen können, um eine Ausgabe zu generieren, die Ihren Anforderungen entspricht.
- Konfigurieren Sie Modellparameter, um zu steuern, wie das Modell eine Antwort generiert. Bei Gemini-Modellen sind dies die Parameter „max. Ausgabetokens“, „Temperatur“, „Top-K“ und „Top-P“. Bei Imagen-Modellen sind dies beispielsweise das Seitenverhältnis, die Generierung von Personen und das Hinzufügen von Wasserzeichen.
- 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.
- 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