Per impostazione predefinita, Gemini API restituisce le risposte come testo non strutturato. Tuttavia, alcuni casi d'uso richiedono testo strutturato, come JSON. Ad esempio, potresti utilizzare la risposta per altre attività a valle che richiedono uno schema di dati stabilito.
Per assicurarti che l'output generato dal modello rispetti sempre uno schema specifico, puoi definire uno schema di risposta, che funge da modello per le risposte del modello. In questo modo, puoi estrarre direttamente i dati dall'output del modello con meno post-elaborazione.
Ecco alcuni esempi:
Assicurati che la risposta di un modello generi JSON valido e sia conforme allo schema fornito.
Ad esempio, il modello può generare voci strutturate per le ricette che includono sempre il nome della ricetta, l'elenco degli ingredienti e i passaggi. In questo modo, potrai analizzare e visualizzare più facilmente queste informazioni nell'interfaccia utente della tua app.Limita il modo in cui un modello può rispondere durante le attività di classificazione.
Ad esempio, puoi chiedere al modello di annotare il testo con un insieme specifico di etichette (ad esempio, un insieme specifico di enum comepositive
enegative
) anziché con le etichette prodotte dal modello (che potrebbero avere un grado di variabilità comegood
,positive
,negative
obad
).
Questa guida illustra come generare un output JSON fornendo un responseSchema
in una chiamata a generateContent
. Si concentra sull'input di solo testo, ma Gemini può anche produrre risposte strutturate a richieste multimodali che includono immagini, video e audio come input.
Nella parte inferiore di questa pagina sono riportati altri esempi, ad esempio come generare valori enum come output. Per visualizzare altri esempi di come generare output strutturato, consulta l'elenco di schemi di esempio e risposte del modello nella documentazione di Google Cloud.
Prima di iniziare
Se non l'hai ancora fatto, consulta la
guida introduttiva, che descrive come configurare il progetto Firebase, collegare l'app a Firebase, aggiungere l'SDK, inizializzare il servizio Vertex AI e creare un'istanza GenerativeModel
.
Passaggio 1: definisci uno schema di risposta
Definisci uno schema di risposta per specificare la struttura dell'output di un modello, i nomi dei campi e il tipo di dati previsto per ogni campo.
Quando un modello genera la sua risposta, utilizza il nome e il contesto del campo del prompt. Per assicurarti che le tue intenzioni siano chiare, ti consigliamo di utilizzare una struttura chiara, nomi di campi non ambigui e, se necessario, anche descrizioni.
Considerazioni per gli schemi di risposta
Quando scrivi lo schema di risposta, tieni presente quanto segue:
Le dimensioni dello schema di risposta vengono conteggiate ai fini del limite di token di input.
La funzionalità dello schema di risposta supporta i seguenti tipi MIME di risposta:
application/json
: output JSON come definito nello schema di risposta (utile per i requisiti di output strutturato)text/x.enum
: restituisce un valore enum come definito nello schema di risposta (utile per le attività di classificazione)
La funzionalità dello schema di risposta supporta i seguenti campi dello schema:
enum
items
maxItems
nullable
properties
required
Se utilizzi un campo non supportato, il modello può comunque gestire la tua richiesta, ma ignora il campo. Tieni presente che l'elenco riportato sopra è un sottoinsieme dell'oggetto schema di OpenAPI 3.0 (consulta il riferimento allo schema di Vertex AI).
Per impostazione predefinita, per gli SDK Vertex AI in Firebase tutti i campi sono considerati obbligatori, a meno che non li specifichi come facoltativi in un array
optionalProperties
. Per questi campi facoltativi, il modello può completarli o ignorarli.Tieni presente che questo è opposto al comportamento predefinito per Vertex AI Gemini API.
Passaggio 2: invia un prompt con uno schema di risposta per generare JSON
Il seguente esempio mostra come generare un output JSON strutturato.
Quando crei l'istanza GenerativeModel
, specifica il valore responseMimeType
appropriato (in questo esempio application/json
) e il valore responseSchema
che vuoi che venga utilizzato dal modello.
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
Per Kotlin, i metodi in questo SDK sono funzioni sospese e devono essere chiamati da un ambito coroutine.// 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
Per Java, i metodi di streaming in questo SDK restituiscono un tipoPublisher
della libreria Reactive Streams.
// 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);
Scopri come scegliere un modello e, facoltativamente, una località appropriata per il tuo caso d'uso e la tua app.
Altri esempi
Per visualizzare altri esempi di come utilizzare e generare output strutturato, consulta l'elenco di schemi di esempio e risposte del modello nella documentazione di Google Cloud.
Genera valori enum come output
L'esempio seguente mostra come utilizzare uno schema di risposta per un'attività di classificazione. Al modello viene chiesto di identificare il genere di un film in base alla sua descrizione. L'output è un valore enumerato in testo normale selezionato dal modello da un elenco di valori definiti nello schema di risposta fornito.
Per eseguire questa attività di classificazione strutturata, devi specificare durante l'inizializzazione del modello il responseMimeType
appropriato (in questo esempio, text/x.enum
) e il responseSchema
che vuoi che il modello utilizzi.
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
Per Kotlin, i metodi in questo SDK sono funzioni sospese e devono essere chiamati da un ambito coroutine.// 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
Per Java, i metodi di streaming in questo SDK restituiscono un tipoPublisher
della libreria Reactive Streams.
// 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);
Scopri come scegliere un modello e, facoltativamente, una località appropriata per il tuo caso d'uso e la tua app.
Altre opzioni per controllare la generazione di contenuti
- Scopri di più sul design dei prompt per poter influenzare il modello in modo che generi output specifici per le tue esigenze.
- Configura i parametri del modello per controllare il modo in cui il modello genera una risposta. Per i modelli Gemini, questi parametri includono token di output massimi, temperatura, topK e topP. Per i modelli Imagen, sono inclusi formato, generazione di persone, watermarking e così via.
- Utilizza le impostazioni di sicurezza per regolare la probabilità di ricevere risposte che potrebbero essere considerate dannose, tra cui incitamento all'odio e contenuti sessualmente espliciti.
- Imposta le istruzioni di sistema per indirizzare il comportamento del modello. Questa funzionalità è simile a un "preambolo" che viene aggiunto prima che il modello venga esposto ad altre istruzioni dell'utente finale.
Inviare un feedback sulla tua esperienza con Vertex AI in Firebase