Model Gemini menampilkan respons sebagai teks tidak terstruktur secara default. Namun, beberapa kasus penggunaan memerlukan teks terstruktur (seperti JSON atau enum). Misalnya, Anda mungkin menggunakan respons untuk tugas downstream lain yang memerlukan skema data yang sudah ditetapkan.
Untuk memastikan bahwa output yang dihasilkan model selalu mematuhi skema tertentu, Anda dapat menentukan skema, yang berfungsi seperti cetak biru untuk respons model. Kemudian, Anda dapat langsung mengekstrak data dari output model dengan lebih sedikit pascapemrosesan.
Berikut adalah beberapa contoh kasus penggunaan:
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.Membatasi cara model merespons selama tugas klasifikasi.
Misalnya, Anda dapat meminta model menganotasi teks dengan kumpulan label tertentu (misalnya, kumpulan enum tertentu sepertipositivedannegative), bukan label yang dihasilkan model (yang dapat memiliki tingkat variabilitas sepertigood,positive,negative, ataubad).
Halaman ini menjelaskan cara membuat output terstruktur (seperti JSON dan enum) dalam pengalaman hybrid Anda untuk aplikasi Android.
Langsung ke output JSON Langsung ke output enum
Konfigurasi untuk output terstruktur
Pembuatan output terstruktur (seperti JSON dan enum) didukung untuk inferensi di perangkat dan yang dihosting di cloud.
Untuk menghasilkan output terstruktur, teruskan skema Anda langsung ke
generateObject().
Persyaratan skema bergantung pada mode inferensi yang Anda konfigurasi:
Untuk inferensi di perangkat dan hybrid (
ONLY_ON_DEVICE,PREFER_ON_DEVICE, danPREFER_IN_CLOUD):- Memerlukan penggunaan anotasi
@Generablepadadata classKotlin dengan pemroses KSP; skema manual dan anotasienum classlangsung tidak didukung. - Saat inferensi berjalan di perangkat, SDK akan otomatis menerjemahkan skema menjadi batasan untuk model di perangkat (menggunakan ML Kit Prompt API).
- Jika permintaan hybrid beralih ke inferensi cloud, SDK akan otomatis
menetapkan
responseMimeTypekeapplication/jsondan meneruskan skema ke model Gemini yang dihosting di cloud.
- Memerlukan penggunaan anotasi
Untuk inferensi khusus cloud (
ONLY_IN_CLOUD):- Mendukung anotasi
@Generable(direkomendasikan) dan skema manual (yang dibuat menggunakan metode helperJsonSchema). - SDK akan otomatis menetapkan
responseMimeTypekeapplication/jsondan meneruskan skema ke model Gemini yang dihosting di cloud.
- Mendukung anotasi
Sebelum memulai
|
Klik penyedia Gemini API untuk melihat konten dan kode khusus penyedia di halaman ini. |
Sebelum membuat output terstruktur, pastikan Anda telah menyelesaikan penyiapan berikut:
Selesaikan panduan memulai untuk membangun pengalaman hybrid, yang mencakup penyiapan project Firebase, download model di perangkat, dan konfigurasi App Check.
Konfigurasikan plugin Kotlin Symbol Processing (KSP) dan tambahkan dependensi Firebase AI KSP ke aplikasi Anda.
Dalam file Gradle modul (level aplikasi) (seperti
<project>/<app-module>/build.gradle.kts), tambahkan plugin KSP, plugin Kotlin Serialization, dan dependensi yang diperlukan:plugins { // ... other plugins id("com.google.gms.google-services") id("com.google.devtools.ksp") version "LATEST_VERSION" id("org.jetbrains.kotlin.plugin.serialization") version "LATEST_VERSION" } dependencies { // ... other androidx dependencies // Add the dependencies for the Firebase AI Logic and App Check libraries. implementation("com.google.firebase:firebase-ai:18.1.0") implementation("com.google.firebase:firebase-ai-ondevice:16.0.0-beta07") implementation("com.google.firebase:firebase-appcheck-debug:20.0.0") // Add the Firebase AI KSP processor for schema generation. ksp("com.google.firebase:firebase-ai-ksp-processor:17.0.0") // (Optional) Add kotlinx.serialization JSON library for object decoding. implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:LATEST_VERSION") }
Langsung ke output JSON Langsung ke output enum
Output JSON
Contoh berikut mengadaptasi
contoh output JSON umum
untuk mengakomodasi inferensi hybrid (misalnya, PREFER_ON_DEVICE).
Dalam skenario untuk contoh ini, model menghasilkan daftar profil karakter untuk cerita fantasi, dengan atribut terstruktur seperti nama, usia, spesies, dan aksesori opsional.
Anda dapat menentukan skema respons menggunakan salah satu pendekatan berikut:
Anotasi KSP (
@Generabledan@Guide)- Didukung untuk semua mode inferensi, dan diperlukan untuk inferensi di perangkat dan hybrid (khususnya,
ONLY_ON_DEVICE,PREFER_ON_DEVICE, danPREFER_IN_CLOUD). - Tentukan class data Kotlin untuk otomatis membuat skema pada waktu kompilasi
dan mendeserialisasi respons langsung ke objek yang diketik dengan kuat menggunakan
getObject().
- Didukung untuk semua mode inferensi, dan diperlukan untuk inferensi di perangkat dan hybrid (khususnya,
Metode bantuan
JsonSchemamanual- Hanya didukung untuk inferensi berbasis cloud (khususnya,
ONLY_IN_CLOUD). - Buat
JsonSchemasecara manual dalam kode tanpa menggunakan pemroses KSP, dan baca string JSON mentah dariresponse.response.text.
- Hanya didukung untuk inferensi berbasis cloud (khususnya,
Contoh 1: Menggunakan anotasi @Generable dan @Guide dengan KSP
Tentukan data class Kotlin yang dianotasi dengan @Serializable dan @Generable.
Gunakan anotasi @Guide pada properti untuk memberikan deskripsi, batas nilai, atau batasan item kepada model.
Pendekatan ini didukung untuk semua mode inferensi, dan diperlukan untuk
pengalaman di perangkat dan hybrid (khususnya, ONLY_ON_DEVICE,
PREFER_ON_DEVICE, dan PREFER_IN_CLOUD).
|
Sebelum mencoba contoh ini, selesaikan bagian
Sebelum memulai dalam panduan ini
untuk menyiapkan project dan aplikasi Anda. Di bagian tersebut, Anda juga akan mengklik tombol untuk penyedia Gemini API yang dipilih sehingga Anda dapat melihat konten khusus penyedia di halaman ini. |
import com.google.firebase.Firebase
import com.google.firebase.ai.type.GenerativeBackend
import com.google.firebase.ai.InferenceMode
import com.google.firebase.ai.OnDeviceConfig
import com.google.firebase.ai.annotations.Generable
import com.google.firebase.ai.annotations.Guide
import com.google.firebase.ai.ai
import kotlinx.serialization.Serializable
// Define data classes representing the schema, annotated with @Serializable and @Generable.
// You can provide descriptions on @Generable and @Guide to guide the model's output.
@Serializable
@Generable(description = "A character profile for a fantasy story")
data class Character(
val name: String,
val age: Int,
val species: String,
// Use @Guide to add property descriptions, value bounds (minimum/maximum), or formats.
// Properties with default values or nullable types are treated as optional in the schema.
@Guide(description = "An accessory the character wears or carries")
val accessory: String? = null
) {
// An empty companion object is required for KSP to generate the firebaseAISchema() extension.
companion object
}
@Serializable
@Generable(description = "A list of character profiles")
data class CharacterList(
// Use minItems or maxItems to specify collection size bounds for the model.
@Guide(description = "List of characters", minItems = 1)
val characters: List<Character>
) {
// An empty companion object is required for KSP to generate the firebaseAISchema() extension.
companion object
}
// Initialize the Gemini Developer API backend service.
// Create a GenerativeModel instance configured for hybrid inference (like PREFER_ON_DEVICE).
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
.generativeModel(
modelName = "CLOUD_MODEL_NAME",
onDeviceConfig = OnDeviceConfig(mode = InferenceMode.INFERENCE_MODE)
)
// Obtain the schema generated by KSP via the firebaseAISchema() extension.
val schema = CharacterList.firebaseAISchema()
val prompt = "Create profiles for some characters for a fantasy story."
// Generate the structured object (the SDK applies the schema to on-device or cloud models).
val response = model.generateObject(schema, prompt)
// Access the strongly-typed deserialized object directly via getObject().
val characterList: CharacterList? = response.getObject()
characterList?.characters?.forEach { character ->
println("Name: ${character.name}, Species: ${character.species}, Age: ${character.age}")
println("Accessory: ${character.accessory ?: "None"}")
}
Contoh 2: Menggunakan metode bantuan JsonSchema manual
Jika aplikasi Anda hanya menggunakan inferensi berbasis cloud (khususnya,
ONLY_IN_CLOUD), Anda dapat membuat
JsonSchema secara manual
menggunakan metode bantuan yang disediakan oleh Firebase AI Logic SDK.
|
Sebelum mencoba contoh ini, selesaikan bagian
Sebelum memulai dalam panduan ini
untuk menyiapkan project dan aplikasi Anda. Di bagian tersebut, Anda juga akan mengklik tombol untuk penyedia Gemini API yang dipilih sehingga Anda dapat melihat konten khusus penyedia di halaman ini. |
import com.google.firebase.Firebase
import com.google.firebase.ai.type.GenerativeBackend
import com.google.firebase.ai.InferenceMode
import com.google.firebase.ai.OnDeviceConfig
import com.google.firebase.ai.ai
import com.google.firebase.ai.type.JsonSchema
// Define the schema manually using JsonSchema helper methods.
// Properties are required by default unless specified in optionalProperties.
val jsonSchema = JsonSchema.obj(
properties = mapOf(
"characters" to JsonSchema.array(
items = JsonSchema.obj(
properties = mapOf(
"name" to JsonSchema.string(),
"accessory" to JsonSchema.string(),
"age" to JsonSchema.integer(),
"species" to JsonSchema.string()
),
optionalProperties = listOf("accessory")
)
)
)
)
// Initialize the Gemini Developer API backend service.
// Manual schemas are only supported for cloud-based inference (specifically, ONLY_IN_CLOUD).
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
.generativeModel(
modelName = "CLOUD_MODEL_NAME",
onDeviceConfig = OnDeviceConfig(mode = InferenceMode.ONLY_IN_CLOUD)
)
// Call generateObject() with the manual schema and prompt.
val response = model.generateObject(
jsonSchema,
"Create profiles for some characters for a fantasy story."
)
// Access the generated JSON string conforming to the schema from response.response.text.
println(response.response.text)
Output enum
Contoh berikut mengadaptasi
contoh output enum umum
untuk mengakomodasi inferensi hybrid (misalnya, PREFER_ON_DEVICE).
Dalam skenario untuk contoh ini, model mengklasifikasikan deskripsi film dengan
memilih satu genre dari daftar opsi yang diizinkan yang telah ditentukan
(drama, comedy, atau documentary).
Anda dapat menentukan skema respons menggunakan salah satu pendekatan berikut:
-
- Didukung untuk semua mode inferensi, dan diperlukan untuk inferensi di perangkat dan hybrid (khususnya,
ONLY_ON_DEVICE,PREFER_ON_DEVICE, danPREFER_IN_CLOUD). - Tentukan enum yang digabungkan dalam
data classKotlin untuk otomatis membuat skema dan mendeserialisasi respons langsung ke objek yang diketik dengan kuat menggunakangetObject().
- Didukung untuk semua mode inferensi, dan diperlukan untuk inferensi di perangkat dan hybrid (khususnya,
Metode bantuan
JsonSchemamanual- Hanya didukung untuk inferensi berbasis cloud (khususnya,
ONLY_IN_CLOUD). - Buat enum
JsonSchemasecara manual menggunakanJsonSchema.enumeration()tanpa menggunakan pemroses KSP, dan baca string yang dipilih dariresponse.response.text.
- Hanya didukung untuk inferensi berbasis cloud (khususnya,
Contoh 1: Menggunakan anotasi @Generable dengan KSP
Tentukan enum class yang mewakili nilai yang diizinkan, dan gabungkan sebagai
properti di dalam data class Kotlin yang dianotasi dengan @Serializable dan
@Generable.
Pendekatan ini didukung untuk semua mode inferensi, dan diperlukan untuk
pengalaman di perangkat dan hybrid (khususnya, ONLY_ON_DEVICE,
PREFER_ON_DEVICE, dan PREFER_IN_CLOUD).
|
Sebelum mencoba contoh ini, selesaikan bagian
Sebelum memulai dalam panduan ini
untuk menyiapkan project dan aplikasi Anda. Di bagian tersebut, Anda juga akan mengklik tombol untuk penyedia Gemini API yang dipilih sehingga Anda dapat melihat konten khusus penyedia di halaman ini. |
import com.google.firebase.Firebase
import com.google.firebase.ai.type.GenerativeBackend
import com.google.firebase.ai.InferenceMode
import com.google.firebase.ai.OnDeviceConfig
import com.google.firebase.ai.annotations.Generable
import com.google.firebase.ai.annotations.Guide
import com.google.firebase.ai.ai
import kotlinx.serialization.Serializable
// Define an enum class representing the allowed options.
@Serializable
enum class FilmGenre {
DRAMA,
COMEDY,
DOCUMENTARY
}
// Wrap the enum in a data class annotated with @Serializable and @Generable.
// On-device inference requires an @Generable data class.
// Direct enum annotations are not supported on-device.
@Serializable
@Generable(description = "The classification result for the film")
data class FilmClassification(
@Guide(description = "The genre of the film")
val genre: FilmGenre
) {
// An empty companion object is required for KSP to generate the firebaseAISchema() extension.
companion object
}
// Initialize the Gemini Developer API backend service.
// Create a GenerativeModel instance configured for hybrid inference (like PREFER_ON_DEVICE).
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
.generativeModel(
modelName = "CLOUD_MODEL_NAME",
onDeviceConfig = OnDeviceConfig(mode = InferenceMode.INFERENCE_MODE)
)
// Obtain the schema generated by KSP via the firebaseAISchema() extension.
val schema = FilmClassification.firebaseAISchema()
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.
"""
// Generate the structured object (the SDK applies the schema to on-device or cloud models).
val response = model.generateObject(schema, prompt)
// Access the strongly-typed deserialized object and enum value directly via getObject().
val classification: FilmClassification? = response.getObject()
val genre: FilmGenre? = classification?.genre
println("Selected genre: $genre")
Contoh 2: Menggunakan metode bantuan JsonSchema manual
Jika aplikasi Anda hanya menggunakan inferensi berbasis cloud (khususnya,
ONLY_IN_CLOUD), Anda dapat membuat enum
JsonSchema
secara manual menggunakan metode bantuan yang disediakan oleh Firebase AI Logic SDK.
|
Sebelum mencoba contoh ini, selesaikan bagian
Sebelum memulai dalam panduan ini
untuk menyiapkan project dan aplikasi Anda. Di bagian tersebut, Anda juga akan mengklik tombol untuk penyedia Gemini API yang dipilih sehingga Anda dapat melihat konten khusus penyedia di halaman ini. |
import com.google.firebase.Firebase
import com.google.firebase.ai.type.GenerativeBackend
import com.google.firebase.ai.InferenceMode
import com.google.firebase.ai.OnDeviceConfig
import com.google.firebase.ai.ai
import com.google.firebase.ai.type.JsonSchema
// Define an enum schema with allowed string values and a description.
val enumSchema = JsonSchema.enumeration(
values = listOf("drama", "comedy", "documentary"),
description = "The genre of the film"
)
// Initialize the Gemini Developer API backend service.
// Manual schemas are only supported for cloud-based inference (specifically, ONLY_IN_CLOUD).
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
.generativeModel(
modelName = "CLOUD_MODEL_NAME",
onDeviceConfig = OnDeviceConfig(mode = InferenceMode.ONLY_IN_CLOUD)
)
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.
"""
// Call generateObject() with the enum schema and prompt.
val response = model.generateObject(enumSchema, prompt)
// Access the selected enum value string from response.response.text.
println(response.response.text)
Berikan masukan tentang pengalaman Anda menggunakan Firebase AI Logic