Gemini API 預設會以非結構化文字的形式傳回回覆。不過,某些用途需要結構化文字,例如 JSON。舉例來說,您可能會將回覆用於其他需要既定資料架構的下游工作。使用 Firebase AI Logic 時,您可以直接從行動或網頁應用程式 (例如 Apple (Swift)、Android (Kotlin/Java)、網頁 (JavaScript)、Flutter (Dart) 或 Unity 應用程式) 要求結構化輸出內容。
為確保模型生成的輸出內容一律符合特定結構定義,您可以定義回覆結構定義,做為模型回覆的藍圖。接著,您就能直接從模型輸出內容擷取資料,減少後續處理作業。
例如:
確保模型回覆產生有效的 JSON,並符合您提供的結構定義。
舉例來說,模型可以為食譜生成結構化項目,一律包含食譜名稱、食材清單和步驟。這樣一來,您就能更輕鬆地在應用程式 UI 中剖析及顯示這項資訊。限制模型在分類任務中的回應方式。
舉例來說,您可以讓模型使用一組特定標籤 (例如positive和negative等特定列舉) 為文字加上註解,而不是使用模型產生的標籤 (可能會有good、positive、negative或bad等變化)。
本指南說明如何在呼叫 generateContent 時提供 responseSchema,藉此生成 JSON 輸出內容。本節著重於純文字輸入,但 Gemini 也能針對包含圖片、影片和音訊的多模態要求,生成結構化回覆。
本頁底部提供更多範例,例如如何產生列舉值做為輸出內容。
事前準備
|
按一下您的Gemini API供應商,即可在這個頁面查看供應商專屬內容和程式碼。 |
如果尚未完成入門指南,請先完成。指南說明如何設定 Firebase 專案、將應用程式連結至 Firebase、新增 SDK、為所選 Gemini API 供應商初始化後端服務,以及建立 GenerativeModel 執行個體。
如要測試及反覆調整提示,建議使用 Google AI Studio。
支援這項功能的模型
gemini-4-carbongemini-4-argongemini-3.8-flashgemini-3.5-flash-lite(以及舊版gemini-3.1-flash-lite)
舊版一般用途 Gemini 3.x Flash 模型支援這項功能,但由於即將停用和/或自動轉送至新版模型,因此不建議使用。
步驟 1:定義回覆結構定義
定義回覆結構定義,指定模型輸出的結構、欄位名稱,以及每個欄位的預期資料類型。
模型生成回覆時,會使用提示中的欄位名稱和脈絡。為確保意圖明確,建議您使用清楚的結構、明確的欄位名稱,甚至視需要提供說明。
回覆結構定義的注意事項
編寫回覆結構定義時,請注意下列事項:
回覆結構定義的大小會計入輸入詞元限制。
回覆結構定義功能支援下列回覆 MIME 類型:
application/json:按照回覆結構定義輸出 JSON (適用於結構化輸出內容需求)text/x.enum:輸出回覆結構定義中定義的列舉值 (適用於分類工作)
回覆結構定義功能支援下列結構定義欄位:
enum
items
maxItems
nullable
properties
required
如果使用不支援的欄位,模型仍可處理要求,但會忽略該欄位。請注意,上述清單是 OpenAPI 3.0 結構定義物件的一部分。
根據預設,對於 Firebase AI Logic SDK,除非您在
optionalProperties陣列中將欄位指定為選填,否則所有欄位都會視為必填。對於這些選項欄位,模型可以填入欄位或略過。請注意,如果您直接使用這兩家 Gemini API 供應商的伺服器 SDK 或 API,這項行為與預設行為相反。
步驟 2:使用回覆結構定義生成 JSON 輸出內容
|
嘗試這個範例前,請先完成本指南的「事前準備」部分,設定專案和應用程式。 在該部分中,您也需要點選所選Gemini API供應商的按鈕,這樣這個頁面才會顯示供應商專屬內容。 |
以下範例說明如何生成結構化 JSON 輸出內容。
建立 GenerativeModel 執行個體時,請指定適當的 responseMimeType (在本範例中為 application/json),以及要讓模型使用的 responseSchema。
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
如果是 Kotlin,這個 SDK 中的方法是暫停函式,需要從協同程式範圍呼叫。
// 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
如果是 Java,這個 SDK 中的串流方法會從 Reactive Streams 程式庫傳回Publisher 類型。
// 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.");
瞭解如何根據用途和應用程式,選擇合適的模型。
其他範例
以下列舉更多範例,說明如何使用及生成結構化輸出內容。產生列舉值做為輸出內容
|
嘗試這個範例前,請先完成本指南的「事前準備」部分,設定專案和應用程式。 在該部分中,您也需要點選所選Gemini API供應商的按鈕,這樣這個頁面才會顯示供應商專屬內容。 |
以下範例說明如何將回覆結構定義用於分類工作。模型必須根據電影說明,判斷電影類型。輸出內容是模型從提供的回覆結構定義中,從定義的值清單中選取的一個純文字列舉值。
如要執行這項結構化分類工作,您必須在模型初始化期間指定適當的 responseMimeType (在本例中為 text/x.enum),以及要讓模型使用的 responseSchema。
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
如果是 Kotlin,這個 SDK 中的方法是暫停函式,需要從協同程式範圍呼叫。
// 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
如果是 Java,這個 SDK 中的串流方法會從 Reactive Streams 程式庫傳回Publisher 類型。
// 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.");
瞭解如何根據用途和應用程式,選擇合適的模型。
其他內容生成控制選項
- 進一步瞭解提示設計,引導模型生成符合您特定需求的輸出內容。
- 設定模型參數,控制模型生成回覆的方式,例如輸出詞元數量上限、輸出詞元重複的機率等。
- 使用安全設定,調整模型產生有害回覆的可能性,包括仇恨言論和情色露骨內容。
- 設定系統指令,引導模型行為。這項功能就像是前導提示,在模型接收使用者進一步指示前,先加入這項提示。
提供「Firebase AI Logic」使用體驗的意見回饋