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 reinem Text. 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. Weitere Beispiele für die Generierung strukturierter Ausgabe finden Sie in der Google Cloud-Dokumentation in der Liste der Beispielschemata und Modellantworten.
Hinweis
Lesen Sie den Startleitfaden, in dem beschrieben wird, wie Sie ein Firebase-Projekt einrichten, Ihre App mit Firebase verbinden, das SDK hinzufügen, den Vertex AI-Dienst initialisieren und eine GenerativeModel
-Instanz erstellen.
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äß Definition im Antwortschema (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 (siehe Vertex AI-Schemareferenz).
Bei Vertex AI in Firebase-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.Dies ist das Gegenteil des Standardverhaltens für die Vertex AI Gemini API.
Schritt 2: Prompt mit einem Antwortschema senden, um JSON zu generieren
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 FirebaseVertexAI
// 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 Vertex AI service and the generative model.
let model = VertexAI.vertexAI().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 Vertex AI service and the generative model.
val generativeModel = Firebase.vertexAI.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 Vertex AI service and the generative model.
GenerativeModel gm = FirebaseVertexAI.getInstance().generativeModel(
/* modelName */ "gemini-2.0-flash",
/* generationConfig */ generationConfig);
GenerativeModelFutures model = GenerativeModelFutures.from(gm);
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 { getVertexAI, getGenerativeModel, Schema } from "firebase/vertexai";
// 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 Vertex AI service.
const vertexAI = getVertexAI(firebaseApp);
// 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"],
}),
}),
}
});
// Initialize the generative model.
const model = getGenerativeModel(vertexAI, {
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_vertexai/firebase_vertexai.dart';
import 'package:firebase_core/firebase_core.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'],
);
await Firebase.initializeApp();
// Initialize the Vertex AI service and the generative model.
final model =
FirebaseVertexAI.instance.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);
Hier erfahren Sie, wie Sie ein Modell und optional einen Standort für Ihren Anwendungsfall und Ihre App auswählen.
Weitere Beispiele
Weitere Beispiele für die Verwendung und Generierung strukturierter Ausgabe finden Sie in der Google Cloud-Dokumentation in der Liste der Beispielschemata und Modellantworten.
Enum-Werte als Ausgabe generieren
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 FirebaseVertexAI
// 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 Vertex AI service and the generative model.
let model = VertexAI.vertexAI().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 Vertex AI service and the generative model.
val generativeModel = Firebase.vertexAI.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 Vertex AI service and the generative model.
GenerativeModel gm = FirebaseVertexAI.getInstance().generativeModel(
/* modelName */ "gemini-2.0-flash",
/* generationConfig */ generationConfig);
GenerativeModelFutures model = GenerativeModelFutures.from(gm);
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 { getVertexAI, getGenerativeModel, Schema } from "firebase/vertexai";
// 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 Vertex AI service.
const vertexAI = getVertexAI(firebaseApp);
// 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"],
});
// Initialize the generative model.
const model = getGenerativeModel(vertexAI, {
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_vertexai/firebase_vertexai.dart';
import 'package:firebase_core/firebase_core.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']);
await Firebase.initializeApp();
// Initialize the Vertex AI service and the generative model.
final model =
FirebaseVertexAI.instance.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);
Hier erfahren Sie, wie Sie ein Modell und optional einen Standort für Ihren Anwendungsfall und Ihre App auswählen.
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 weiteren Anweisungen des Endnutzers ausgesetzt wird.
Feedback zu Vertex AI in Firebase geben