Gemini API menampilkan respons sebagai teks tidak terstruktur secara default. Namun, beberapa kasus penggunaan memerlukan teks terstruktur, seperti JSON. Misalnya, Anda mungkin menggunakan respons untuk tugas downstream lainnya yang memerlukan skema data yang sudah ditetapkan.
Untuk memastikan bahwa output yang dihasilkan model selalu mematuhi skema tertentu, Anda dapat menentukan skema respons yang berfungsi seperti cetak biru untuk respons model. Kemudian, Anda dapat langsung mengekstrak data dari output model dengan lebih sedikit pascapemrosesan.
Berikut beberapa contohnya:
Pastikan respons model menghasilkan JSON yang valid dan sesuai dengan skema yang Anda berikan.
Misalnya, model dapat menghasilkan entri terstruktur untuk resep yang selalu menyertakan nama resep, daftar bahan, dan langkah-langkah. Kemudian, Anda dapat lebih mudah mengurai dan menampilkan informasi ini di UI aplikasi Anda.Batasi cara model merespons selama tugas klasifikasi.
Misalnya, Anda dapat meminta model menganotasi teks dengan kumpulan label tertentu (misalnya, kumpulan enum tertentu sepertipositive
dannegative
), bukan label yang dihasilkan model (yang dapat memiliki tingkat variabilitas sepertigood
,positive
,negative
, ataubad
).
Panduan ini menunjukkan cara membuat output JSON dengan memberikan responseSchema
dalam panggilan ke generateContent
. Model ini berfokus pada input teks saja, tetapi Gemini juga dapat
menghasilkan respons terstruktur untuk permintaan multimodal yang menyertakan gambar,
video, dan audio sebagai input.
Di bagian bawah halaman ini terdapat contoh lainnya, seperti cara membuat nilai enum sebagai output.
Sebelum memulai
Klik penyedia Gemini API untuk melihat konten dan kode khusus penyedia di halaman ini. |
Jika Anda belum melakukannya, selesaikan panduan memulai, yang menjelaskan cara menyiapkan project Firebase, menghubungkan aplikasi ke Firebase, menambahkan SDK, menginisialisasi layanan backend untuk penyedia Gemini API yang Anda pilih, dan membuat instance GenerativeModel
.
Untuk menguji dan melakukan iterasi pada perintah Anda, bahkan mendapatkan cuplikan kode yang dihasilkan, sebaiknya gunakan Google AI Studio.
Langkah 1: Tentukan skema respons
Tentukan skema respons untuk menentukan struktur output model, nama kolom, dan jenis data yang diharapkan untuk setiap kolom.
Saat menghasilkan respons, model menggunakan nama kolom dan konteks dari perintah Anda. Untuk memastikan intent Anda jelas, sebaiknya gunakan struktur yang jelas, nama kolom yang tidak ambigu, dan bahkan deskripsi sesuai kebutuhan.
Pertimbangan untuk skema respons
Perhatikan hal-hal berikut saat menulis skema respons:
Ukuran skema respons dihitung dalam batas token input.
Fitur skema respons mendukung jenis MIME respons berikut:
application/json
: JSON output seperti yang ditentukan dalam skema respons (berguna untuk persyaratan output terstruktur)text/x.enum
: menampilkan nilai enum seperti yang ditentukan dalam skema respons (berguna untuk tugas klasifikasi)
Fitur skema respons mendukung kolom skema berikut:
enum
items
maxItems
nullable
properties
required
Jika Anda menggunakan kolom yang tidak didukung, model masih dapat menangani permintaan Anda, tetapi kolom tersebut akan diabaikan. Perhatikan bahwa daftar di atas adalah subset dari objek skema OpenAPI 3.0.
Secara default, untuk SDK Firebase AI Logic, semua kolom dianggap wajib kecuali jika Anda menentukannya sebagai opsional dalam array
optionalProperties
. Untuk kolom opsional ini, model dapat mengisi kolom atau melewatinya. Perhatikan bahwa hal ini berlawanan dengan perilaku default dari kedua penyedia Gemini API jika Anda menggunakan SDK server atau API mereka secara langsung.
Langkah 2: Buat output JSON menggunakan skema respons Anda
Sebelum mencoba contoh ini, selesaikan bagian
Sebelum memulai dalam panduan ini
untuk menyiapkan project dan aplikasi. Di bagian tersebut, Anda juga akan mengklik tombol untuk penyedia Gemini API yang dipilih sehingga Anda melihat konten khusus penyedia di halaman ini. |
Contoh berikut menunjukkan cara membuat output JSON terstruktur.
Saat membuat instance GenerativeModel
, tentukan responseMimeType
yang sesuai (dalam contoh ini, application/json
) serta
responseSchema
yang ingin Anda gunakan model.
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
Untuk Kotlin, metode dalam SDK ini adalah fungsi penangguhan dan perlu dipanggil dari Cakupan 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
Untuk Java, metode streaming di SDK ini menampilkan jenisPublisher
dari library 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.");
Pelajari cara memilih model yang sesuai untuk kasus penggunaan dan aplikasi Anda.
Contoh tambahan
Berikut beberapa contoh tambahan tentang cara menggunakan dan membuat output terstruktur.Membuat nilai enum sebagai output
Sebelum mencoba contoh ini, selesaikan bagian
Sebelum memulai dalam panduan ini
untuk menyiapkan project dan aplikasi. Di bagian tersebut, Anda juga akan mengklik tombol untuk penyedia Gemini API yang dipilih sehingga Anda melihat konten khusus penyedia di halaman ini. |
Contoh berikut menunjukkan cara menggunakan skema respons untuk tugas klasifikasi. Model diminta untuk mengidentifikasi genre film berdasarkan deskripsinya. Outputnya adalah satu nilai enum teks biasa yang dipilih model dari daftar nilai yang ditentukan dalam skema respons yang disediakan.
Untuk melakukan tugas klasifikasi terstruktur ini, Anda perlu menentukan selama inisialisasi
model responseMimeType
yang sesuai (dalam contoh ini,
text/x.enum
) serta responseSchema
yang ingin digunakan model.
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
Untuk Kotlin, metode dalam SDK ini adalah fungsi penangguhan dan perlu dipanggil dari Cakupan 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
Untuk Java, metode streaming di SDK ini menampilkan jenisPublisher
dari library 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.");
Pelajari cara memilih model yang sesuai untuk kasus penggunaan dan aplikasi Anda.
Opsi lain untuk mengontrol pembuatan konten
- Pelajari lebih lanjut desain perintah agar Anda dapat memengaruhi model untuk menghasilkan output yang spesifik untuk kebutuhan Anda.
- Konfigurasikan parameter model untuk mengontrol cara model menghasilkan respons. Untuk model Gemini, parameter ini mencakup token output maksimum, suhu, topK, dan topP. Untuk model Imagen, hal ini mencakup rasio aspek, pembuatan orang, watermark, dsb.
- Gunakan setelan keamanan untuk menyesuaikan kemungkinan mendapatkan respons yang mungkin dianggap berbahaya, termasuk ujaran kebencian dan konten seksual vulgar.
- Tetapkan petunjuk sistem untuk mengarahkan perilaku model. Fitur ini seperti preamble yang Anda tambahkan sebelum model diekspos ke petunjuk lebih lanjut dari pengguna akhir.
Berikan masukan tentang pengalaman Anda dengan Firebase AI Logic