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 funzioni come un 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 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.
Prima di iniziare
Fai clic sul tuo fornitore Gemini API per visualizzare i contenuti e il codice specifici del fornitore in questa pagina. |
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 di backend per il provider Gemini API scelto e creare un'istanza GenerativeModel
.
Per testare e eseguire l'iterazione sui prompt e persino per ottenere uno snippet di codice generato, ti consigliamo di utilizzare Google AI Studio.
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.
Per impostazione predefinita, per gli SDK Firebase AI Logic 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 è il comportamento opposto a quello predefinito dei due fornitoriGemini API se utilizzi direttamente i loro SDK server o le loro API.
Passaggio 2: genera l'output JSON utilizzando lo schema di risposta
Prima di provare questo esempio, completa la sezione Prima di iniziare di questa guida per configurare il progetto e l'app. In questa sezione, dovrai anche fare clic su un pulsante per il fornitore Gemini API scelto in modo da visualizzare i contenuti specifici del fornitore in questa pagina. |
Il seguente esempio mostra come generare un output JSON strutturato.
Quando crei l'istanza GenerativeModel
, specifica il responseMimeType
appropriato (in questo esempio application/json
) e il responseSchema
che vuoi che il modello utilizzi.
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
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 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
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 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);
Unity
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.");
Scopri come scegliere un modello appropriato per il tuo caso d'uso e la tua app.
Altri esempi
Ecco alcuni esempi aggiuntivi di come puoi utilizzare e generare output strutturato.Genera valori enum come output
Prima di provare questo esempio, completa la sezione Prima di iniziare di questa guida per configurare il progetto e l'app. In questa sezione, dovrai anche fare clic su un pulsante per il fornitore Gemini API scelto per visualizzare i contenuti specifici del fornitore in questa pagina. |
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 enum 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 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
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 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
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 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);
Unity
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.");
Scopri come scegliere un modello appropriato 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, inclusi 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 Firebase AI Logic