Membuat output terstruktur untuk pengalaman hybrid di aplikasi Android


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 output yang dihasilkan model selalu mematuhi skema tertentu, Anda dapat menentukan skema, yang berfungsi seperti cetak biru untuk respons model. Kemudian, Anda dapat mengekstrak data langsung dari output model dengan lebih sedikit pasca-pemrosesan.

Berikut adalah beberapa contoh kasus penggunaan:

  • Pastikan respons model menghasilkan JSON yang valid dan sesuai dengan skema yang Anda berikan.
    Misalnya, model dapat membuat entri terstruktur untuk resep yang selalu mencakup nama resep, daftar bahan, dan langkah-langkah. Kemudian, Anda dapat mengurai dan menampilkan informasi ini dengan lebih mudah di UI aplikasi Anda.

  • Membatasi cara model dapat merespons selama tugas klasifikasi.
    Misalnya, Anda dapat membuat model menganotasi teks dengan serangkaian label tertentu (misalnya, serangkaian enum tertentu seperti positive dan negative), bukan label yang dihasilkan model (yang dapat memiliki tingkat variabilitas seperti good, positive, negative, atau bad).

Halaman ini menjelaskan cara membuat output terstruktur (seperti JSON dan enum) dalam pengalaman hybrid untuk aplikasi Android.

Buka output JSON Buka 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 dikonfigurasi:

  • Untuk inferensi di perangkat dan hybrid (ONLY_ON_DEVICE, PREFER_ON_DEVICE, dan PREFER_IN_CLOUD):

    • Memerlukan penggunaan anotasi @Generable pada data class Kotlin dengan pemroses KSP; skema manual dan anotasi enum class langsung 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 kembali ke inferensi cloud, SDK akan otomatis menetapkan responseMimeType ke application/json dan meneruskan skema ke model Gemini yang dihosting di cloud.
  • Untuk inferensi khusus cloud (ONLY_IN_CLOUD):

    • Mendukung anotasi @Generable (direkomendasikan) dan skema manual (dibuat menggunakan metode helper JsonSchema).
    • SDK otomatis menyetel responseMimeType ke application/json dan meneruskan skema ke model Gemini yang dihosting di cloud.

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:

  1. Selesaikan panduan memulai untuk membangun pengalaman hybrid, yang mencakup penyiapan project Firebase, mendownload model di perangkat, dan mengonfigurasi App Check.

  2. Konfigurasi 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:17.17.0")
       implementation("com.google.firebase:firebase-ai-ondevice:16.0.0-beta05")
       implementation("com.google.firebase:firebase-appcheck-debug:19.4.1")
    
       // Add the Firebase AI KSP processor for schema generation.
       ksp("com.google.firebase:firebase-ai-ksp-processor:16.0.2")
    
       // (Optional) Add kotlinx.serialization JSON library for object decoding.
       implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:LATEST_VERSION")
    }


Buka output JSON Buka 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 membuat 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 (@Generable dan @Guide)

    • Didukung untuk semua mode inferensi, dan diperlukan untuk inferensi di perangkat dan hybrid (khususnya, ONLY_ON_DEVICE, PREFER_ON_DEVICE, dan PREFER_IN_CLOUD).
    • Tentukan class data Kotlin untuk membuat skema secara otomatis pada waktu kompilasi dan mendeserialisasi respons langsung ke objek yang memiliki jenis yang kuat menggunakan getObject().
  • Metode bantuan JsonSchema manual

    • Didukung hanya untuk inferensi berbasis cloud (khususnya, ONLY_IN_CLOUD).
    • Buat JsonSchema secara manual dalam kode tanpa menggunakan pemroses KSP, dan baca string JSON mentah dari response.response.text.

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 model, batas nilai, atau batasan item.

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 sampel 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 Anda pilih sehingga Anda dapat melihat konten khusus penyedia di halaman ini.

Untuk Kotlin, metode dalam SDK ini adalah fungsi penangguhan dan perlu dipanggil dari cakupan Coroutine.
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 helper JsonSchema manual

Jika aplikasi Anda hanya menggunakan inferensi berbasis cloud (khususnya, ONLY_IN_CLOUD), Anda dapat membuat JsonSchema secara manual menggunakan metode helper yang disediakan oleh Firebase AI Logic SDK.

Sebelum mencoba sampel 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 Anda pilih sehingga Anda dapat melihat konten khusus penyedia di halaman ini.

Untuk Kotlin, metode dalam SDK ini adalah fungsi penangguhan dan perlu dipanggil dari cakupan Coroutine.
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 sebelumnya (drama, comedy, atau documentary).

Anda dapat menentukan skema respons menggunakan salah satu pendekatan berikut:

  • Anotasi KSP (@Generable)

    • Didukung untuk semua mode inferensi, dan diperlukan untuk inferensi di perangkat dan hybrid (khususnya, ONLY_ON_DEVICE, PREFER_ON_DEVICE, dan PREFER_IN_CLOUD).
    • Tentukan enum yang di-wrap dalam data class Kotlin untuk otomatis membuat skema dan mendeserialisasi respons langsung ke objek yang memiliki jenis yang kuat menggunakan getObject().
  • Metode bantuan JsonSchema manual

    • Didukung hanya untuk inferensi berbasis cloud (khususnya, ONLY_IN_CLOUD).
    • Buat enum JsonSchema secara manual menggunakan JsonSchema.enumeration() tanpa menggunakan prosesor KSP, dan baca string yang dipilih dari response.response.text.

Contoh 1: Menggunakan anotasi @Generable dengan KSP

Tentukan enum class yang merepresentasikan nilai yang diizinkan, dan bungkus 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 sampel 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 Anda pilih sehingga Anda dapat melihat konten khusus penyedia di halaman ini.

Untuk Kotlin, metode dalam SDK ini adalah fungsi penangguhan dan perlu dipanggil dari cakupan Coroutine.
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 helper JsonSchema manual

Jika aplikasi Anda hanya menggunakan inferensi berbasis cloud (khususnya, ONLY_IN_CLOUD), Anda dapat membuat enum JsonSchema secara manual menggunakan metode helper yang disediakan oleh Firebase AI Logic SDK.

Sebelum mencoba sampel 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 Anda pilih sehingga Anda dapat melihat konten khusus penyedia di halaman ini.

Untuk Kotlin, metode dalam SDK ini adalah fungsi penangguhan dan perlu dipanggil dari cakupan Coroutine.
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)


Memberikan masukan tentang pengalaman Anda dengan Firebase AI Logic