Gemini API restituisce le risposte come testo non strutturato per impostazione predefinita. Tuttavia, alcuni casi d'uso richiedono testo strutturato, come JSON. Ad esempio, potresti utilizzare la risposta per altre attività downstream che richiedono uno schema di dati stabilito.
Per garantire che l'output generato dal modello rispetti sempre uno schema specifico, puoi definire uno schema di risposta che funziona come un progetto per le risposte del modello. Puoi quindi estrarre direttamente i dati dall'output del modello con una minore post-elaborazione.
Ecco alcuni esempi:
Assicurati che la risposta di un modello produca un 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, puoi 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 fare in modo che il modello annoti il testo con un insieme specifico di etichette (ad esempio, un insieme specifico di enum comepositiveenegative), anziché con le etichette prodotte dal modello (che potrebbero avere un grado di variabilità comegood,positive,negativeobad).
Questa guida mostra come generare l'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.
In fondo a questa pagina sono riportati altri esempi, come la generazione di valori enum come output.
Prima di iniziare
|
Fai clic sul tuo provider Gemini API per visualizzare i contenuti e il codice specifici del provider in questa pagina. |
Se non l'hai già fatto, completa la guida introduttiva, che descrive come configurare il progetto Firebase, connettere 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 perfezionare i prompt, ti consigliamo di utilizzare Google AI Studio.
Modelli che supportano questa funzionalità
gemini-4-argongemini-3.8-flash(e i modelli precedentigemini-3.7-flash,gemini-3.6-flashegemini-3.5-flash)gemini-3.5-flash-lite(e il precedentegemini-3.1-flash-lite)
Anche i modelli gemini-3.1-pro-preview e Gemini 2.5 per uso generico (deprecati) supportano questa funzionalità.
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 del campo e il contesto del prompt. Per assicurarti che l'intent sia chiaro, ti consigliamo di utilizzare una struttura chiara, nomi di campi non ambigui e persino descrizioni, se necessario.
Considerazioni per gli schemi di risposta
Tieni presente quanto segue quando scrivi lo schema di risposta:
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: genera 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 richiesta, ma ignora il campo. Tieni presente che l'elenco riportato sopra è un sottoinsieme dell'oggetto schema 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ò compilarli o saltarli. Tieni presente che questo è l'opposto del comportamento predefinito dei due provider Gemini API se utilizzi i loro SDK server o la loro API direttamente.
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, farai anche clic su un pulsante per il provider Gemini API scelto, in modo da visualizzare i contenuti specifici del provider in questa pagina. |
L'esempio seguente 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 venga utilizzato dal modello.
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
Per Kotlin, i metodi in questo SDK sono funzioni di sospensione 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_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
Per Java, i metodi di streaming in questo SDK restituiscono un tipoPublisher dalla 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 */ "<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);
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_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.");
Scopri come scegliere un modello adatta al tuo caso d'uso e alla tua app.
Altri esempi
Ecco alcuni esempi aggiuntivi di come puoi utilizzare e generare output strutturati.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, farai anche clic su un pulsante per il provider Gemini API scelto, in modo da visualizzare i contenuti specifici del provider 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 singolo valore enum in testo normale che il modello seleziona da un elenco di valori definiti nello schema di risposta fornito.
Per eseguire questa attività di classificazione strutturata, durante l'inizializzazione del modello devi specificare il responseMimeType appropriato (in questo esempio, text/x.enum) e il responseSchema che vuoi che il modello utilizzi.
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
Per Kotlin, i metodi in questo SDK sono funzioni di sospensione 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_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
Per Java, i metodi di streaming in questo SDK restituiscono un tipoPublisher dalla 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 */ "<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);
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_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.");
Scopri come scegliere un modello adatta al tuo caso d'uso e alla tua app.
Altre opzioni per controllare la generazione di contenuti
- Scopri di più sulla progettazione dei prompt per influenzare il modello in modo che generi un output specifico per le tue esigenze.
- Configura i parametri del modello per controllare il modo in cui il modello genera una risposta, ad esempio i token di output massimi, la probabilità di token di output ripetuti 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 guidare il comportamento del modello. Questa funzionalità è come un preambolo che aggiungi prima che il modello venga esposto a ulteriori istruzioni dell'utente finale.
Invia un feedback sulla tua esperienza con Firebase AI Logic