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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

เอาต์พุต JSON

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

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

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

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

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

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

ตัวอย่างนี้ใช้เมธอดตัวช่วย 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)

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

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

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

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

ตัวอย่างนี้ใช้Schema.enumStringเมธอดตัวช่วยที่ 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 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