De forma predeterminada, Gemini API muestra las respuestas como texto no estructurado. Sin embargo, algunos casos de uso requieren texto estructurado, como JSON. Por ejemplo, es posible que uses la respuesta para otras tareas posteriores que requieran un esquema de datos establecido.
Para garantizar que el resultado generado por el modelo siempre cumpla con un esquema específico, puedes definir un esquema de respuesta , que funciona como un modelo para las respuestas del modelo. Luego, puedes extraer datos directamente del resultado del modelo con menos procesamiento posterior.
Estos son algunos ejemplos:
Asegúrate de que la respuesta de un modelo genere un JSON válido y cumpla con el esquema que proporcionaste.
Por ejemplo, el modelo puede generar entradas estructuradas para recetas que siempre incluyan el nombre de la receta, la lista de ingredientes y los pasos. Luego, puedes analizar y mostrar esta información con mayor facilidad en la IU de tu app.Restringe la forma en que un modelo puede responder durante las tareas de clasificación.
Por ejemplo, puedes hacer que el modelo anote texto con un conjunto específico de etiquetas (por ejemplo, un conjunto específico de enumeraciones comopositiveynegative), en lugar de las etiquetas que produce el modelo (que podrían tener un grado de variabilidad comogood,positive,negativeobad).
En esta guía, se muestra cómo generar resultados JSON proporcionando un responseSchema en una llamada a generateContent. Se enfoca en la entrada de solo texto, pero Gemini también puede producir respuestas estructuradas a solicitudes multimodales que incluyen imágenes, videos y audio como entrada.
En la parte inferior de esta página, hay más ejemplos, como cómo generar valores de enumeración como resultado.
Antes de comenzar
|
Haz clic en tu proveedor de Gemini API para ver el contenido específico del proveedor y el código en esta página. |
Si aún no lo hiciste, completa la
guía de introducción, en la que se describe cómo
configurar tu proyecto de Firebase, conectar tu app a Firebase, agregar el SDK,
inicializar el servicio de backend para el proveedor de Gemini API que elijas y
crear una instancia de GenerativeModel.
Para probar y, luego, iterar tus instrucciones, te recomendamos que uses Google AI Studio.
Paso 1: Define un esquema de respuesta
Define un esquema de respuesta para especificar la estructura del resultado de un modelo, los nombres de los campos y el tipo de datos esperado para cada campo.
Cuando un modelo genera su respuesta, usa el nombre del campo y el contexto de tu instrucción. Para asegurarte de que tu intención sea clara, te recomendamos que uses una estructura clara, nombres de campo inequívocos e incluso descripciones según sea necesario.
Consideraciones para los esquemas de respuesta
Ten en cuenta lo siguiente cuando escribas tu esquema de respuesta:
El tamaño del esquema de respuesta se considera para el límite de tokens de entrada.
La función de esquema de respuesta admite los siguientes tipos de MIME de respuesta:
application/json: Muestra JSON como se define en el esquema de respuesta (útil para los requisitos de salida estructurada).text/x.enum: Muestra un valor de enumeración como se define en el esquema de respuesta (útil para las tareas de clasificación).
La función de esquema de respuesta admite los siguientes campos de esquema:
enum
items
maxItems
nullable
properties
required
Si usas un campo no compatible, el modelo puede controlar tu solicitud, pero ignora el campo. Ten en cuenta que la lista anterior es un subconjunto del objeto de esquema de OpenAPI 3.0.
De forma predeterminada, para los Firebase AI Logic SDK, todos los campos se consideran obligatorios, a menos que los especifiques como opcionales en un
optionalPropertiesarray. Para estos campos opcionales, el modelo puede propagar los campos o omitirlos. Ten en cuenta que esto es lo opuesto al comportamiento predeterminado de los dos Gemini API proveedores si usas sus SDK de servidor o su API directamente.
Paso 2: Genera resultados JSON con tu esquema de respuesta
|
Antes de probar este ejemplo, completa la sección
Antes de comenzar de esta guía
para configurar tu proyecto y tu app. En esa sección, también harás clic en un botón para el Gemini API proveedor que elijas, de modo que veas contenido específico del proveedor en esta página. |
En el siguiente ejemplo, se muestra cómo generar resultados JSON estructurados.
Cuando crees la instancia de GenerativeModel, especifica el responseMimeType adecuado (en este ejemplo, application/json), así como el responseSchema que deseas que use el modelo.
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-3-flash-preview",
// 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
En Kotlin, los métodos de este SDK son funciones de suspensión y deben llamarse desde un alcance de corrutina.
// 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-3-flash-preview",
// 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
En Java, los métodos de transmisión de este SDK muestran un tipoPublisher de la biblioteca de 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-3-flash-preview",
/* 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-3-flash-preview",
// 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-3-flash-preview',
// 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-3-flash-preview",
// 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.");
Obtén información para elegir un modelo adecuada para tu caso de uso y tu app.
Ejemplos adicionales
Estos son algunos ejemplos adicionales de cómo puedes usar y generar resultados estructurados.Genera valores de enumeración como resultado
|
Antes de probar este ejemplo, completa la sección
Antes de comenzar de esta guía
para configurar tu proyecto y tu app. En esa sección, también harás clic en un botón para el Gemini API proveedor que elijas, de modo que veas contenido específico del proveedor en esta página. |
En el siguiente ejemplo, se muestra cómo usar un esquema de respuesta para una tarea de clasificación. Se le pide al modelo que identifique el género de una película según su descripción. El resultado es un valor de enumeración de texto sin formato que el modelo selecciona de una lista de valores que se definen en el esquema de respuesta proporcionado.
Para realizar esta tarea de clasificación estructurada, debes especificar durante la inicialización del modelo el responseMimeType adecuado (en este ejemplo, text/x.enum), así como el responseSchema que deseas que use el modelo.
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-3-flash-preview",
// 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
En Kotlin, los métodos de este SDK son funciones de suspensión y deben llamarse desde un alcance de corrutina.
// 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-3-flash-preview",
// 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
En Java, los métodos de transmisión de este SDK muestran un tipoPublisher de la biblioteca de 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-3-flash-preview",
/* 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-3-flash-preview",
// 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-3-flash-preview',
// 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-3-flash-preview",
// 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.");
Obtén información para elegir un modelo adecuada para tu caso de uso y tu app.
Otras opciones para controlar la generación de contenido
- Obtén más información sobre el diseño de instrucciones para que puedas influir en el modelo para generar resultados específicos para tus necesidades.
- Configura los parámetros del modelo para controlar cómo el modelo genera una respuesta. Para los modelos Gemini, estos parámetros incluyen tokens de salida máximos, temperatura, topK y topP. Para los modelos Imagen, estos incluyen relación de aspecto, generación de personas, marcas de agua, etcétera.
- Usa la configuración de seguridad para ajustar la probabilidad de obtener respuestas que puedan considerarse dañinas, incluido el discurso de odio y el contenido sexualmente explícito.
- Establece instrucciones del sistema para dirigir el comportamiento del modelo. Esta función es como un preámbulo que agregas antes de que el modelo se exponga a otras instrucciones del usuario final.
Envía comentarios sobre tu experiencia con Firebase AI Logic