To avoid service disruption, update to anewer model (for example,
gemini-2.5-flash-lite
).Learn more. Generate structured output (like JSON and enums) using the Gemini API Stay organized with collections Save and categorize content based on your preferences.
TheGemini API returns responses as unstructured text by default. However,some use cases require structured text, like JSON. For example, you might beusing the response for other downstream tasks that require an established dataschema.
To ensure that the model's generated output always adheres to a specific schema,you can define aresponse schemawhich works like a blueprint for model responses. You can then directly extractdata from the model's output with less post-processing.
Here are some examples:
Ensure that a model's response produces valid JSON and conforms to yourprovided schema.
For example, the model can generate structured entries for recipes that alwaysinclude the recipe name, list of ingredients, and steps. You can then moreeasily parse and display this information in the UI of your app.Constrain how a model can respond during classification tasks.
For example, you can have the model annotate text with a specific set oflabels (for instance, a specific set of enums likepositive
andnegative
),rather than labels that the model produces (which could have a degree ofvariability likegood
,positive
,negative
, orbad
).
This guide shows you how to generate JSON output by providing aresponseSchema
in a call togenerateContent
. It focuses on text-only input, but Gemini canalso produce structured responses to multimodal requests that include images,videos, and audio as input.
At the bottom of this page are more examples, like how togenerate enum values as output.
Before you begin
Click yourGemini API provider to view provider-specific content and code on this page. |
If you haven't already, complete thegetting started guide, which describes how toset up your Firebase project, connect your app to Firebase, add the SDK,initialize the backend service for your chosenGemini API provider, andcreate aGenerativeModel
instance.
This guide assumes you're using the latestFirebase AI Logic SDKs. If you're still using the "Vertex AI in Firebase" SDKs, see themigration guide.
For testing and iterating on your prompts, we recommend usingGoogle AI Studio.Step 1: Define a response schema
Define a response schema to specify the structure of a model's output, the fieldnames, and the expected data type for each field.
When a model generates its response, it uses the field name and context fromyour prompt. To make sure that your intent is clear, we recommend using aclear structure, unambiguous field names, and even descriptions as needed.
Considerations for response schemas
Keep the following in mind when writing your response schema:
The size of the response schema counts towards the input token limit.
The response schema feature supports the following response MIME types:
application/json
: output JSON as defined in the response schema(useful for structured output requirements)text/x.enum
: output an enum value as defined in the response schema(useful for classification tasks)
The response schema feature supports the following schema fields:
enum
items
maxItems
nullable
properties
required
If you use an unsupported field, the model can still handle your request, butit ignores the field. Note that the list above is a subset of the OpenAPI 3.0schema object.
By default, forFirebase AI Logic SDKs, all fields are consideredrequired unless you specify them as optional in an
optionalProperties
array. For these optional fields, the model can populate the fields or skipthem. Note that this is opposite from the default behavior of the twoGemini API providers if you use their server SDKs or their API directly.
Step 2: Generate JSON output using your response schema
Before trying this sample, complete theBefore you begin section of this guide to set up your project and app. In that section, you'll also click a button for your chosenGemini API provider so that you see provider-specific content on this page. |
The following example shows how to generate structured JSON output.
When you create theGenerativeModel
instance, specify the appropriateresponseMimeType
(in this example,application/json
) as well as theresponseSchema
that you want the model to use.
Swift
importFirebaseAI// Provide a JSON schema object using a standard format.// Later, pass this schema object into `responseSchema` in the generation config.letjsonSchema=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 serviceletai=FirebaseAI.firebaseAI(backend:.googleAI())// Create a `GenerativeModel` instance with a model that supports your use caseletmodel=ai.generativeModel(modelName:"gemini-2.5-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))letprompt="For use in a children's card game, generate 10 animal-based characters."letresponse=tryawaitmodel.generateContent(prompt)print(response.text??"No text in response.")
Kotlin
For Kotlin, the methods in this SDK are suspend functions and need to be calledfrom aCoroutine scope.// Provide a JSON schema object using a standard format.// Later, pass this schema object into `responseSchema` in the generation config.valjsonSchema=Schema.obj(mapOf("characters"toSchema.array(Schema.obj(mapOf("name"toSchema.string(),"age"toSchema.integer(),"species"toSchema.string(),"accessory"toSchema.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 casevalmodel=Firebase.ai(backend=GenerativeBackend.googleAI()).generativeModel(modelName="gemini-2.5-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})valprompt="For use in a children's card game, generate 10 animal-based characters."valresponse=generativeModel.generateContent(prompt)print(response.text)
Java
For Java, the streaming methods in this SDK return aPublisher
type from theReactive Streams library.// Provide a JSON schema object using a standard format.// Later, pass this schema object into `responseSchema` in the generation config.SchemajsonSchema=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.BuilderconfigBuilder=newGenerationConfig.Builder();configBuilder.responseMimeType="application/json";configBuilder.responseSchema=jsonSchema;GenerationConfiggenerationConfig=configBuilder.build();// Initialize the Gemini Developer API backend service// Create a `GenerativeModel` instance with a model that supports your use caseGenerativeModelai=FirebaseAI.getInstance(GenerativeBackend.googleAI()).generativeModel(/* modelName */"gemini-2.5-flash",/* generationConfig */generationConfig);GenerativeModelFuturesmodel=GenerativeModelFutures.from(ai);Contentcontent=newContent.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.Executorexecutor=Executors.newSingleThreadExecutor();ListenableFuture<GenerateContentResponse>response=model.generateContent(content);Futures.addCallback(response,newFutureCallback<GenerateContentResponse>(){@OverridepublicvoidonSuccess(GenerateContentResponseresult){StringresultText=result.getText();System.out.println(resultText);}@OverridepublicvoidonFailure(Throwablet){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-objectconstfirebaseConfig={// ...};// Initialize FirebaseAppconstfirebaseApp=initializeApp(firebaseConfig);// Initialize the Gemini Developer API backend serviceconstai=getAI(firebaseApp,{backend:newGoogleAIBackend()});// Provide a JSON schema object using a standard format.// Later, pass this schema object into `responseSchema` in the generation config.constjsonSchema=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 caseconstmodel=getGenerativeModel(ai,{model:"gemini-2.5-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},});letprompt="For use in a children's card game, generate 10 animal-based characters.";letresult=awaitmodel.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.finaljsonSchema=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 FirebaseAppawaitFirebase.initializeApp(options:DefaultFirebaseOptions.currentPlatform,);// Initialize the Gemini Developer API backend service// Create a `GenerativeModel` instance with a model that supports your use casefinalmodel=FirebaseAI.googleAI().generativeModel(model:'gemini-2.5-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));finalprompt="For use in a children's card game, generate 10 animal-based characters.";finalresponse=awaitmodel.generateContent([Content.text(prompt)]);print(response.text);
Unity
usingFirebase;usingFirebase.AI;// Provide a JSON schema object using a standard format.// Later, pass this schema object into `responseSchema` in the generation config.varjsonSchema=Schema.Object(properties:newSystem.Collections.Generic.Dictionary<string,Schema>{{"characters",Schema.Array(items:Schema.Object(properties:newSystem.Collections.Generic.Dictionary<string,Schema>{{"name",Schema.String()},{"age",Schema.Int()},{"species",Schema.String()},{"accessory",Schema.Enum(newstring[]{"hat","belt","shoes"})},},optionalProperties:newstring[]{"accessory"}))},});// Initialize the Gemini Developer API backend service// Create a `GenerativeModel` instance with a model that supports your use casevarmodel=FirebaseAI.DefaultInstance.GetGenerativeModel(modelName:"gemini-2.5-flash",// In the generation config, set the `responseMimeType` to `application/json`// and pass the JSON schema object into `responseSchema`.generationConfig:newGenerationConfig(responseMimeType:"application/json",responseSchema:jsonSchema));varprompt="For use in a children's card game, generate 10 animal-based characters.";varresponse=awaitmodel.GenerateContentAsync(prompt);UnityEngine.Debug.Log(response.Text??"No text in response.");
Learn how to choose amodelappropriate for your use case and app.
Additional examples
Here are some additional examples of how you can use and generate structuredoutput.Generate enum values as output
Before trying this sample, complete theBefore you begin section of this guide to set up your project and app. In that section, you'll also click a button for your chosenGemini API provider so that you see provider-specific content on this page. |
The following example shows how to use a response schema for a classificationtask. The model is asked to identify the genre of a movie based on itsdescription. The output is one plain-text enum value that the model selects froma list of values that are defined in the provided response schema.
To perform this structured classification task, you need to specify during modelinitialization the appropriateresponseMimeType
(in this example,text/x.enum
) as well as theresponseSchema
that you want the model to use.
Swift
importFirebaseAI// Provide an enum schema object using a standard format.// Later, pass this schema object into `responseSchema` in the generation config.letenumSchema=Schema.enumeration(values:["drama","comedy","documentary"])// Initialize the Gemini Developer API backend serviceletai=FirebaseAI.firebaseAI(backend:.googleAI())// Create a `GenerativeModel` instance with a model that supports your use caseletmodel=ai.generativeModel(modelName:"gemini-2.5-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))letprompt="""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 insightsinto various aspects of reality."""letresponse=tryawaitmodel.generateContent(prompt)print(response.text??"No text in response.")
Kotlin
For Kotlin, the methods in this SDK are suspend functions and need to be calledfrom aCoroutine scope.// Provide an enum schema object using a standard format.// Later, pass this schema object into `responseSchema` in the generation config.valenumSchema=Schema.enumeration(listOf("drama","comedy","documentary"))// Initialize the Gemini Developer API backend service// Create a `GenerativeModel` instance with a model that supports your use casevalmodel=Firebase.ai(backend=GenerativeBackend.googleAI()).generativeModel(modelName="gemini-2.5-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})valprompt=""" 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. """valresponse=generativeModel.generateContent(prompt)print(response.text)
Java
For Java, the streaming methods in this SDK return aPublisher
type from theReactive Streams library.// Provide an enum schema object using a standard format.// Later, pass this schema object into `responseSchema` in the generation config.SchemaenumSchema=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.BuilderconfigBuilder=newGenerationConfig.Builder();configBuilder.responseMimeType="text/x.enum";configBuilder.responseSchema=enumSchema;GenerationConfiggenerationConfig=configBuilder.build();// Initialize the Gemini Developer API backend service// Create a `GenerativeModel` instance with a model that supports your use caseGenerativeModelai=FirebaseAI.getInstance(GenerativeBackend.googleAI()).generativeModel(/* modelName */"gemini-2.5-flash",/* generationConfig */generationConfig);GenerativeModelFuturesmodel=GenerativeModelFutures.from(ai);Stringprompt="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.";Contentcontent=newContent.Builder().addText(prompt).build();// For illustrative purposes only. You should use an executor that fits your needs.Executorexecutor=Executors.newSingleThreadExecutor();ListenableFuture<GenerateContentResponse>response=model.generateContent(content);Futures.addCallback(response,newFutureCallback<GenerateContentResponse>(){@OverridepublicvoidonSuccess(GenerateContentResponseresult){StringresultText=result.getText();System.out.println(resultText);}@OverridepublicvoidonFailure(Throwablet){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-objectconstfirebaseConfig={// ...};// Initialize FirebaseAppconstfirebaseApp=initializeApp(firebaseConfig);// Initialize the Gemini Developer API backend serviceconstai=getAI(firebaseApp,{backend:newGoogleAIBackend()});// Provide an enum schema object using a standard format.// Later, pass this schema object into `responseSchema` in the generation config.constenumSchema=Schema.enumString({enum:["drama","comedy","documentary"],});// Create a `GenerativeModel` instance with a model that supports your use caseconstmodel=getGenerativeModel(ai,{model:"gemini-2.5-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,},});letprompt=`The film aims to educate and inform viewers about real-lifesubjects, events, or people. It offers a factual record of a particular topicby combining interviews, historical footage, and narration. The primary purposeof a film is to present information and provide insights into various aspectsof reality.`;letresult=awaitmodel.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.finalenumSchema=Schema.enumString(enumValues:['drama','comedy','documentary']);// Initialize FirebaseAppawaitFirebase.initializeApp(options:DefaultFirebaseOptions.currentPlatform,);// Initialize the Gemini Developer API backend service// Create a `GenerativeModel` instance with a model that supports your use casefinalmodel=FirebaseAI.googleAI().generativeModel(model:'gemini-2.5-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));finalprompt=""" 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. """;finalresponse=awaitmodel.generateContent([Content.text(prompt)]);print(response.text);
Unity
usingFirebase;usingFirebase.AI;// Provide an enum schema object using a standard format.// Later, pass this schema object into `responseSchema` in the generation config.varenumSchema=Schema.Enum(newstring[]{"drama","comedy","documentary"});// Initialize the Gemini Developer API backend service// Create a `GenerativeModel` instance with a model that supports your use casevarmodel=FirebaseAI.DefaultInstance.GetGenerativeModel(modelName:"gemini-2.5-flash",// In the generation config, set the `responseMimeType` to `text/x.enum`// and pass the enum schema object into `responseSchema`.generationConfig:newGenerationConfig(responseMimeType:"text/x.enum",responseSchema:enumSchema));varprompt=@"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 insightsinto various aspects of reality.";varresponse=awaitmodel.GenerateContentAsync(prompt);UnityEngine.Debug.Log(response.Text??"No text in response.");
Learn how to choose amodelappropriate for your use case and app.
Other options to control content generation
- Learn more aboutprompt design so that you can influence the model to generate output specific to your needs.
- Configuremodel parameters to control how the model generates a response. ForGemini models, these parameters include max output tokens, temperature, topK, and topP. ForImagen models, these include aspect ratio, person generation, watermarking, etc.
- Usesafety settings to adjust the likelihood of getting responses that may be considered harmful, including hate speech and sexually explicit content.
- Setsystem instructions to steer the behavior of the model. This feature is like a preamble that you add before the model gets exposed to any further instructions from the end user.
Give feedback about your experience withFirebase AI Logic
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-10-03 UTC.