สร้างเอาต์พุตที่มีโครงสร้างสำหรับประสบการณ์การใช้งานแบบไฮบริดในแอป Android


โมเดล Gemini จะแสดงผลคำตอบเป็นข้อความที่ไม่มีโครงสร้างโดยค่าเริ่มต้น อย่างไรก็ตาม กรณีการใช้งานบางกรณีต้องใช้ข้อความที่มีโครงสร้าง (เช่น JSON หรือ Enum) เช่น คุณอาจใช้คำตอบสำหรับงานอื่นๆ ที่อยู่ปลายน้ำซึ่งต้องใช้สคีมาข้อมูลที่กำหนดไว้

เพื่อให้แน่ใจว่าเอาต์พุตที่โมเดลสร้างขึ้นเป็นไปตามสคีมาที่เฉพาะเจาะจงเสมอ คุณสามารถกำหนดสคีมา ซึ่งทำงานเหมือนพิมพ์เขียวสำหรับการตอบกลับของโมเดล จากนั้นคุณจะดึงข้อมูลจากเอาต์พุตของโมเดลได้โดยตรงโดยใช้การประมวลผลหลังการประมวลผลน้อยลง

ตัวอย่างกรณีการใช้งานมีดังนี้

  • ตรวจสอบว่าคำตอบของโมเดลสร้าง JSON ที่ถูกต้องและเป็นไปตามสคีมาที่คุณระบุ
    ตัวอย่างเช่น โมเดลสามารถสร้างรายการที่มีโครงสร้างสำหรับสูตรอาหารซึ่งประกอบด้วยชื่อสูตรอาหาร รายการส่วนผสม และขั้นตอนต่างๆ เสมอ จากนั้นคุณจะแยกวิเคราะห์และแสดงข้อมูลนี้ใน UI ของแอปได้ง่ายขึ้น

  • จำกัดวิธีที่โมเดลสามารถตอบกลับระหว่างงานการแยกประเภท
    ตัวอย่างเช่น คุณสามารถให้โมเดลใส่คำอธิบายประกอบข้อความด้วยชุดป้ายกำกับที่เฉพาะเจาะจง (เช่น ชุด Enum ที่เฉพาะเจาะจงอย่าง positive และ negative) แทนป้ายกำกับที่โมเดลสร้างขึ้น (ซึ่งอาจมีความแปรปรวนในระดับหนึ่ง เช่น good, positive, negative หรือ bad)

หน้านี้อธิบายวิธีสร้างเอาต์พุตที่มีโครงสร้าง (เช่น JSON และ Enum) ในประสบการณ์แบบผสมสำหรับแอป Android

ข้ามไปยังเอาต์พุต JSON ข้ามไปยังเอาต์พุต enum

การกำหนดค่าสำหรับเอาต์พุตที่มีโครงสร้าง

ระบบรองรับการสร้างเอาต์พุตที่มีโครงสร้าง (เช่น JSON และ Enum) สำหรับทั้งการอนุมานในอุปกรณ์และการอนุมานที่โฮสต์ในระบบคลาวด์

หากต้องการสร้างเอาต์พุตที่มีโครงสร้าง ให้ส่งสคีมาไปยัง generateObject() โดยตรง ข้อกำหนดของสคีมาจะขึ้นอยู่กับโหมดการอนุมานที่กำหนดค่าไว้ ดังนี้

  • สำหรับการอนุมานในอุปกรณ์และแบบผสม (ONLY_ON_DEVICE, PREFER_ON_DEVICE และ PREFER_IN_CLOUD)

    • ต้องใช้คำอธิบายประกอบ @Generable ใน Kotlin data class กับโปรเซสเซอร์ KSP โดยระบบไม่รองรับสคีมาที่สร้างด้วยตนเองและคำอธิบายประกอบ enum class โดยตรง
    • เมื่อการอนุมานทำงานในอุปกรณ์ SDK จะแปลสคีมาเป็นข้อจำกัดสำหรับโมเดลในอุปกรณ์โดยอัตโนมัติ (โดยใช้ ML Kit Prompt API)
    • หากคำขอแบบผสมกลับไปใช้การอนุมานในระบบคลาวด์ SDK จะตั้งค่า responseMimeType เป็น application/json โดยอัตโนมัติ และส่งสคีมาไปยังโมเดล Gemini ที่โฮสต์ในระบบคลาวด์
  • สำหรับการอนุมานในระบบคลาวด์เท่านั้น (ONLY_IN_CLOUD):

    • รองรับทั้งคำอธิบายประกอบ @Generable (แนะนำ) และสคีมาที่กำหนดเอง (สร้างโดยใช้เมธอดตัวช่วย JsonSchema)
    • SDK จะตั้งค่า responseMimeType เป็น application/json โดยอัตโนมัติ และส่งสคีมาไปยังโมเดล Gemini ที่โฮสต์ในระบบคลาวด์

ก่อนเริ่มต้น

คลิกผู้ให้บริการ Gemini API เพื่อดูเนื้อหาและโค้ดเฉพาะของผู้ให้บริการในหน้านี้

ก่อนสร้างเอาต์พุตที่มีโครงสร้าง โปรดตรวจสอบว่าคุณได้ตั้งค่าต่อไปนี้เรียบร้อยแล้ว

  1. ทำตามคู่มือเริ่มต้นใช้งานสำหรับการสร้างประสบการณ์แบบผสม ซึ่งครอบคลุมการตั้งค่าโปรเจ็กต์ Firebase, การดาวน์โหลดโมเดลในอุปกรณ์ และการกำหนดค่า App Check

  2. กำหนดค่าปลั๊กอิน Kotlin Symbol Processing (KSP) และเพิ่มทรัพยากร Dependency Firebase AI KSP ลงในแอป

    ในไฟล์ Gradle ของโมดูล (ระดับแอป) (เช่น <project>/<app-module>/build.gradle.kts) ให้เพิ่มปลั๊กอิน KSP, ปลั๊กอิน Kotlin Serialization และทรัพยากร Dependency ที่จำเป็น ดังนี้

    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")
    }


ข้ามไปยังเอาต์พุต JSON ข้ามไปยังเอาต์พุต enum

เอาต์พุต JSON

ตัวอย่างต่อไปนี้จะปรับตัวอย่างเอาต์พุต JSON ทั่วไปเพื่อรองรับการอนุมานแบบผสม (เช่น PREFER_ON_DEVICE)

ในสถานการณ์สำหรับตัวอย่างเหล่านี้ โมเดลจะสร้างรายการโปรไฟล์ตัวละครสำหรับเรื่องราวแฟนตาซี โดยมีแอตทริบิวต์ที่มีโครงสร้าง เช่น ชื่อ อายุ สายพันธุ์ และเครื่องประดับที่ไม่บังคับ

คุณสามารถกำหนดสคีมาการตอบกลับได้โดยใช้วิธีใดวิธีหนึ่งต่อไปนี้

  • คำอธิบายประกอบ KSP (@Generable และ @Guide)

    • รองรับโหมดการอนุมานทั้งหมด และจำเป็นสำหรับการอนุมานในอุปกรณ์และแบบผสม (โดยเฉพาะ ONLY_ON_DEVICE, PREFER_ON_DEVICE และ PREFER_IN_CLOUD)
    • กำหนดคลาสข้อมูล Kotlin เพื่อสร้างสคีมาโดยอัตโนมัติที่เวลาคอมไพล์และดีซีเรียลไลซ์การตอบกลับเป็นออบเจ็กต์ที่มีประเภทชัดเจนโดยตรงโดยใช้ getObject()
  • เมธอดตัวช่วย JsonSchema แบบกำหนดเอง

    • รองรับเฉพาะการอนุมานในระบบคลาวด์ (โดยเฉพาะ ONLY_IN_CLOUD)
    • สร้าง JsonSchema ในโค้ดด้วยตนเองโดยไม่ต้องใช้โปรเซสเซอร์ KSP และอ่านสตริง JSON ดิบจาก response.response.text

ตัวอย่างที่ 1: การใช้คำอธิบายประกอบ @Generable และ @Guide กับ KSP

กำหนด data class ของ Kotlin ที่กำกับเนื้อหาด้วย @Serializable และ @Generable ใช้คำอธิบายประกอบ @Guide ในพร็อพเพอร์ตี้เพื่อให้คำอธิบาย ขอบเขตค่า หรือข้อจำกัดของรายการแก่โมเดล

แนวทางนี้รองรับโหมดการอนุมานทั้งหมด และจำเป็นสำหรับประสบการณ์การใช้งานในอุปกรณ์และแบบผสม (โดยเฉพาะ ONLY_ON_DEVICE, PREFER_ON_DEVICE และ PREFER_IN_CLOUD)

ก่อนลองใช้ตัวอย่างนี้ ให้ทำตามส่วนก่อนเริ่มต้นของคู่มือนี้เพื่อตั้งค่าโปรเจ็กต์และแอป
ในส่วนนั้น คุณจะต้องคลิกปุ่มสำหรับผู้ให้บริการ Gemini API ที่เลือกด้วยเพื่อให้เห็นเนื้อหาเฉพาะผู้ให้บริการในหน้านี้

สำหรับ Kotlin เมธอดใน SDK นี้เป็นฟังก์ชันระงับและต้องเรียกใช้จากขอบเขต 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"}")
}

ตัวอย่างที่ 2: การใช้เมธอดตัวช่วย JsonSchema ด้วยตนเอง

หากแอปใช้เฉพาะการอนุมานในระบบคลาวด์ (โดยเฉพาะ ONLY_IN_CLOUD) คุณสามารถสร้าง JsonSchema ด้วยตนเองโดยใช้วิธีการตัวช่วยที่ SDK ของ Firebase AI Logic มีให้

ก่อนลองใช้ตัวอย่างนี้ ให้ทำตามส่วนก่อนเริ่มต้นของคู่มือนี้เพื่อตั้งค่าโปรเจ็กต์และแอป
ในส่วนนั้น คุณจะต้องคลิกปุ่มสำหรับผู้ให้บริการ Gemini API ที่เลือกด้วยเพื่อให้เห็นเนื้อหาเฉพาะผู้ให้บริการในหน้านี้

สำหรับ Kotlin เมธอดใน SDK นี้เป็นฟังก์ชันระงับและต้องเรียกใช้จากขอบเขต 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)

เอาต์พุต Enum

ตัวอย่างต่อไปนี้จะปรับตัวอย่างเอาต์พุต enum ทั่วไปเพื่อรองรับการอนุมานแบบผสม (เช่น PREFER_ON_DEVICE)

ในสถานการณ์สำหรับตัวอย่างเหล่านี้ โมเดลจะจัดประเภทคำอธิบายภาพยนตร์โดยเลือกประเภทเดียวจากรายการตัวเลือกที่อนุญาตที่กำหนดไว้ล่วงหน้า (drama, comedy หรือ documentary)

คุณสามารถกำหนดสคีมาการตอบกลับได้โดยใช้วิธีใดวิธีหนึ่งต่อไปนี้

  • คำอธิบายประกอบ KSP (@Generable)

    • รองรับโหมดการอนุมานทั้งหมด และจำเป็นสำหรับการอนุมานในอุปกรณ์และแบบผสม (โดยเฉพาะ ONLY_ON_DEVICE, PREFER_ON_DEVICE และ PREFER_IN_CLOUD)
    • กำหนด enum ที่รวมอยู่ใน Kotlin data class เพื่อสร้างสคีมาโดยอัตโนมัติและดีซีเรียลไลซ์การตอบกลับเป็นออบเจ็กต์ที่มีประเภทชัดเจนโดยตรงโดยใช้ getObject()
  • เมธอดตัวช่วย JsonSchema แบบกำหนดเอง

    • รองรับเฉพาะการอนุมานในระบบคลาวด์ (โดยเฉพาะ ONLY_IN_CLOUD)
    • สร้าง enum JsonSchema ด้วยตนเองโดยใช้ JsonSchema.enumeration() โดยไม่ต้องใช้โปรเซสเซอร์ KSP และอ่านสตริงที่เลือกจาก response.response.text

ตัวอย่างที่ 1: การใช้คำอธิบายประกอบ @Generable กับ KSP

กำหนด enum class ที่แสดงค่าที่อนุญาต และรวมเป็นพร็อพเพอร์ตี้ภายใน Kotlin data class ที่มีคำอธิบายประกอบเป็น @Serializable และ @Generable

แนวทางนี้รองรับโหมดการอนุมานทั้งหมด และจำเป็นสำหรับประสบการณ์การใช้งานในอุปกรณ์และแบบผสม (โดยเฉพาะ ONLY_ON_DEVICE, PREFER_ON_DEVICE และ PREFER_IN_CLOUD)

ก่อนลองใช้ตัวอย่างนี้ ให้ทำตามส่วนก่อนเริ่มต้นของคู่มือนี้เพื่อตั้งค่าโปรเจ็กต์และแอป
ในส่วนนั้น คุณจะต้องคลิกปุ่มสำหรับผู้ให้บริการ Gemini API ที่เลือกด้วยเพื่อให้เห็นเนื้อหาเฉพาะผู้ให้บริการในหน้านี้

สำหรับ Kotlin เมธอดใน SDK นี้เป็นฟังก์ชันระงับและต้องเรียกใช้จากขอบเขต 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")

ตัวอย่างที่ 2: การใช้เมธอดตัวช่วย JsonSchema ด้วยตนเอง

หากแอปใช้เฉพาะการอนุมานในระบบคลาวด์ (โดยเฉพาะ ONLY_IN_CLOUD) คุณสามารถสร้าง enum JsonSchema ด้วยตนเองโดยใช้เมธอดตัวช่วยที่ SDK Firebase AI Logic มีให้

ก่อนลองใช้ตัวอย่างนี้ ให้ทำตามส่วนก่อนเริ่มต้นของคู่มือนี้เพื่อตั้งค่าโปรเจ็กต์และแอป
ในส่วนนั้น คุณจะต้องคลิกปุ่มสำหรับผู้ให้บริการ Gemini API ที่เลือกด้วยเพื่อให้เห็นเนื้อหาเฉพาะผู้ให้บริการในหน้านี้

สำหรับ Kotlin เมธอดใน SDK นี้เป็นฟังก์ชันระงับและต้องเรียกใช้จากขอบเขต 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)


แสดงความคิดเห็นเกี่ยวกับประสบการณ์การใช้งาน Firebase AI Logic