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

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

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

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

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

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

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

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

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

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

  • โหมดการอนุมานแบบผสม: กำหนดค่าทั้ง inCloudParams และ onDeviceParams เพื่อให้โมเดลตอบกลับด้วยเอาต์พุตที่มีโครงสร้าง ไม่ว่าการอนุมานจะทำงานในระบบคลาวด์หรือในอุปกรณ์ก็ตาม

    • สำหรับโมเดลในอุปกรณ์: ระบุ responseConstraint ใน onDeviceParams โดยใช้สคีมาที่สร้างด้วยเมธอดตัวช่วย Schema หรือสคีมา JSON ธรรมดา

    • สำหรับโมเดลที่โฮสต์ในระบบคลาวด์: ระบุ responseMimeType (application/json สำหรับ JSON หรือ text/x.enum สำหรับ Enum) และ responseSchema ใน inCloudParams

  • โหมดการอนุมานที่ไม่ใช่แบบไฮบริด: ใช้เฉพาะการกำหนดค่าที่เกี่ยวข้องที่อธิบายไว้ข้างต้น

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

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

ตรวจสอบว่าคุณได้ทำตามคู่มือเริ่มต้นใช้งานสำหรับการสร้างประสบการณ์แบบผสมแล้ว


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

เอาต์พุต JSON

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

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

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

  • เมธอดตัวช่วยของ Firebase Schema (แนะนำ): ใช้เมธอดตัวช่วย (เช่น Schema.object() และ Schema.enumString()) เพื่อเขียนสคีมาที่กระชับและกะทัดรัดลงในโค้ดโดยตรงโดยไม่ต้องใช้โค้ดสำเร็จรูปเพิ่มเติม

  • สคีมา JSON แบบธรรมดา: ใช้ออบเจ็กต์สคีมา JSON มาตรฐานหากคุณมีคำจำกัดความสคีมาอยู่แล้ว แชร์สคีมาข้ามแพลตฟอร์มหรือบริการแบ็กเอนด์ หรือนำเข้าสคีมาจากไฟล์ JSON

ตัวอย่างที่ 1: การใช้เมธอดตัวช่วย Schema ของ Firebase

ตัวอย่างนี้ใช้เมธอดตัวช่วย Schema (เช่น Schema.object, Schema.array, Schema.string และ Schema.number) ที่ SDK Firebase AI Logic มีให้เพื่อกำหนดสคีมาออบเจ็กต์

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

import { initializeApp } from "firebase/app";
import {
  getAI,
  getGenerativeModel,
  GoogleAIBackend,
  InferenceMode,
  Schema
} from "firebase/ai";

// TODO(developer): Replace the following with your app's Firebase configuration.
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize FirebaseApp.
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Define a schema using the `Schema` helper methods.
// Optional properties are specified in optionalProperties.
const jsonSchema = Schema.object({
  properties: {
    characters: Schema.array({
      items: Schema.object({
        properties: {
          name: Schema.string(),
          age: Schema.number(),
          species: Schema.string(),
          accessory: Schema.string()
        },
        optionalProperties: ["accessory"]
      })
    })
  }
});

// Create a GenerativeModel instance configured to use a hybrid inference mode (like PREFER_ON_DEVICE).
const model = getGenerativeModel(ai, {
  mode: InferenceMode.INFERENCE_MODE,
  // For cloud-hosted models, specify MIME type and response schema.
  inCloudParams: {
    model: "CLOUD_MODEL_NAME",
    generationConfig: {
      responseMimeType: "application/json",
      responseSchema: jsonSchema
    }
  },
  // For on-device models, pass the schema as the response constraint.
  onDeviceParams: {
    promptOptions: {
      responseConstraint: jsonSchema
    }
  }
});

const prompt = "Create profiles for some characters for a fantasy story.";

// Generate the structured output.
const result = await model.generateContent(prompt);

// Access the generated JSON string conforming to the schema from response.text().
console.log(result.response.text());

// Parse the JSON string into a JavaScript object.
console.log(JSON.parse(result.response.text()));

ตัวอย่างที่ 2: การใช้สคีมา JSON แบบธรรมดา

ตัวอย่างนี้กำหนดสคีมาโดยใช้ JSON เท่านั้น

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

import { initializeApp } from "firebase/app";
import {
  getAI,
  getGenerativeModel,
  GoogleAIBackend,
  InferenceMode
} from "firebase/ai";

// TODO(developer): Replace the following with your app's Firebase configuration.
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize FirebaseApp.
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Define the schema as a plain JSON object.
// Properties are required by default unless omitted from the required array.
const jsonSchema = {
  type: "object",
  properties: {
    characters: {
      type: "array",
      items: {
        type: "object",
        properties: {
          name: {
            type: "string",
            nullable: false
          },
          age: {
            type: "number",
            nullable: false
          },
          species: {
            type: "string",
            nullable: false
          },
          accessory: {
            type: "string",
            nullable: true
          }
        },
        nullable: false,
        required: [
          "name",
          "age",
          "species"
        ]
      },
      nullable: false
    }
  },
  nullable: false,
  required: [
    "characters"
  ]
};

// Create a GenerativeModel instance configured to use a hybrid inference mode (like PREFER_ON_DEVICE).
const model = getGenerativeModel(ai, {
  mode: InferenceMode.INFERENCE_MODE,
  // For cloud-hosted models, specify MIME type and response schema.
  inCloudParams: {
    model: "CLOUD_MODEL_NAME",
    generationConfig: {
      responseMimeType: "application/json",
      responseSchema: jsonSchema
    }
  },
  // For on-device models, pass the schema as the response constraint.
  onDeviceParams: {
    promptOptions: {
      responseConstraint: jsonSchema
    }
  }
});

const prompt = "Create profiles for some characters for a fantasy story.";

// Generate the structured output.
const result = await model.generateContent(prompt);

// Access the generated JSON string conforming to the schema from response.text().
console.log(result.response.text());

// Parse the JSON string into a JavaScript object.
console.log(JSON.parse(result.response.text()));

เอาต์พุต Enum

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

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

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

  • เมธอดตัวช่วยของ Firebase Schema (แนะนำ): ใช้เมธอดตัวช่วย (เช่น Schema.object() และ Schema.enumString()) เพื่อเขียนสคีมาที่กระชับและกะทัดรัดลงในโค้ดโดยตรงโดยไม่ต้องใช้โค้ดสำเร็จรูปเพิ่มเติม

  • สคีมา JSON แบบธรรมดา: ใช้ออบเจ็กต์สคีมา JSON มาตรฐานหากคุณมีคำจำกัดความสคีมาอยู่แล้ว แชร์สคีมาข้ามแพลตฟอร์มหรือบริการแบ็กเอนด์ หรือนำเข้าสคีมาจากไฟล์ JSON

ตัวอย่างที่ 1: การใช้เมธอดตัวช่วย Schema ของ Firebase

ตัวอย่างนี้ใช้เมธอดตัวช่วย Schema.enumString ที่ได้จาก SDK Firebase AI Logic เพื่อกำหนดค่า enum ที่อนุญาต

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

import { initializeApp } from "firebase/app";
import {
  getAI,
  getGenerativeModel,
  GoogleAIBackend,
  InferenceMode,
  Schema
} from "firebase/ai";

// TODO(developer): Replace the following with your app's Firebase configuration.
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize FirebaseApp.
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Define an enum schema using the `Schema` helper method with allowed string values.
const enumSchema = Schema.enumString({
  enum: ["drama", "comedy", "documentary"]
});

// Create a GenerativeModel instance configured to use a hybrid inference mode (like PREFER_ON_DEVICE).
const model = getGenerativeModel(ai, {
  mode: InferenceMode.INFERENCE_MODE,
  // For cloud-hosted models, specify MIME type and response schema.
  inCloudParams: {
    model: "CLOUD_MODEL_NAME",
    generationConfig: {
      responseMimeType: "text/x.enum",
      responseSchema: enumSchema
    }
  },
  // For on-device models, pass the enum schema as the response constraint.
  onDeviceParams: {
    promptOptions: {
      responseConstraint: enumSchema
    }
  }
});

const 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 enum output.
const result = await model.generateContent(prompt);

// Access the selected enum value string from response.text().
console.log(result.response.text());

ตัวอย่างที่ 2: การใช้สคีมา JSON แบบธรรมดา

ตัวอย่างนี้กำหนดสคีมา enum โดยใช้ JSON เท่านั้น

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

import { initializeApp } from "firebase/app";
import {
  getAI,
  getGenerativeModel,
  GoogleAIBackend,
  InferenceMode
} from "firebase/ai";

// TODO(developer): Replace the following with your app's Firebase configuration.
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize FirebaseApp.
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Define the enum schema as a plain JSON object.
const enumSchema = {
  type: "string",
  enum: ["drama", "comedy", "documentary"]
};

// Create a GenerativeModel instance configured to use a hybrid inference mode (like PREFER_ON_DEVICE).
const model = getGenerativeModel(ai, {
  mode: InferenceMode.INFERENCE_MODE,
  // For cloud-hosted models, specify MIME type and response schema.
  inCloudParams: {
    model: "CLOUD_MODEL_NAME",
    generationConfig: {
      responseMimeType: "text/x.enum",
      responseSchema: enumSchema
    }
  },
  // For on-device models, pass the enum schema as the response constraint.
  onDeviceParams: {
    promptOptions: {
      responseConstraint: enumSchema
    }
  }
});

const 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 enum output.
const result = await model.generateContent(prompt);

// Access the selected enum value string from response.text().
console.log(result.response.text());


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