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


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

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

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

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

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

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

ไปที่เอาต์พุต JSON ไปที่เอาต์พุตการแจงนับ

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

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

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

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

    • ต้องใช้คำอธิบายประกอบ @Generable ใน data class ของ Kotlin กับ ตัวประมวลผล 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: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")
    }


ไปที่เอาต์พุต JSON ไปที่เอาต์พุตการแจงนับ

เอาต์พุต 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

กำหนดฟังก์ชัน Kotlin data class ที่มีคำอธิบายประกอบด้วย @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)
    • สร้างการแจงนับด้วยตนเองJsonSchemaโดยใช้ JsonSchema.enumeration() โดยไม่ต้องใช้โปรเซสเซอร์ KSP และอ่านสตริงที่เลือกจาก response.response.text

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

กำหนด enum class ที่แสดงค่าที่อนุญาต แล้วห่อเป็นพร็อพเพอร์ตี้ภายใน data class ของ Kotlin ที่มีคำอธิบายประกอบ @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) คุณจะสร้างการแจงนับด้วยตนเองได้ 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