สร้างเอาต์พุตที่มีโครงสร้างสำหรับประสบการณ์การใช้งานแบบไฮบริดในแอป 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 ใน 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 และทรัพยากร 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.0.0")
       implementation("com.google.firebase:firebase-ai-ondevice:16.0.0-beta06")
       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 นี้เป็นฟังก์ชันระงับและต้องเรียกใช้ จาก ขอบเขตโครูทีน
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 ด้วยตนเองโดยใช้วิธีการช่วยเหลือที่ Firebase AI Logic SDK มีให้

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

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

    • รองรับเฉพาะการอนุมานในระบบคลาวด์ (โดยเฉพาะ ONLY_IN_CLOUD)
    • สร้าง Enum 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 นี้เป็นฟังก์ชันระงับและต้องเรียกใช้ จาก ขอบเขตโครูทีน
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 ด้วยตนเองโดยใช้วิธีการช่วยเหลือที่ Firebase AI Logic SDK มีให้

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

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