Membuat output terstruktur untuk pengalaman hybrid di aplikasi Web

Model Gemini menampilkan respons sebagai teks tidak terstruktur secara default. Namun, beberapa kasus penggunaan memerlukan teks terstruktur (seperti JSON atau enum). Misalnya, Anda mungkin menggunakan respons untuk tugas downstream lain yang memerlukan skema data yang sudah ditetapkan.

Untuk memastikan bahwa output yang dihasilkan model selalu mematuhi skema tertentu, Anda dapat menentukan skema, yang berfungsi seperti cetak biru untuk respons model. Kemudian, Anda dapat langsung mengekstrak data dari output model dengan lebih sedikit pascapemrosesan.

Berikut adalah beberapa contoh kasus penggunaan:

  • Pastikan respons model menghasilkan JSON yang valid dan sesuai dengan skema yang Anda berikan.
    Misalnya, model dapat menghasilkan entri terstruktur untuk resep yang selalu menyertakan nama resep, daftar bahan, dan langkah-langkah. Kemudian, Anda dapat lebih mudah mengurai dan menampilkan informasi ini di UI aplikasi Anda.

  • Membatasi cara model merespons selama tugas klasifikasi.
    Misalnya, Anda dapat meminta model menganotasi teks dengan kumpulan label tertentu (misalnya, kumpulan enum tertentu seperti positive dan negative), bukan label yang dihasilkan model (yang dapat memiliki tingkat variabilitas seperti good, positive, negative, atau bad).

Halaman ini menjelaskan cara membuat output terstruktur (seperti JSON dan enum) dalam pengalaman hybrid Anda untuk aplikasi web.

Langsung ke output JSON Langsung ke output enum

Konfigurasi untuk output terstruktur

Pembuatan output terstruktur (seperti JSON dan enum) didukung untuk inferensi menggunakan model yang dihosting di cloud dan model di perangkat.

  • Mode inferensi hybrid: Konfigurasikan inCloudParams dan onDeviceParams agar model merespons dengan output terstruktur, terlepas dari apakah inferensi berjalan di cloud atau di perangkat:

    • Untuk model di perangkat: Tentukan responseConstraint di onDeviceParams menggunakan skema yang dibuat dengan metode bantuan Schema atau skema JSON biasa.

    • Untuk model yang dihosting di cloud: Tentukan responseMimeType (application/json untuk JSON atau text/x.enum untuk enum) dan responseSchema di inCloudParams.

  • Mode inferensi non-hibrid: Hanya gunakan konfigurasi yang berlaku yang dijelaskan di atas.

Sebelum memulai

Klik penyedia Gemini API untuk melihat konten dan kode khusus penyedia di halaman ini.

Pastikan Anda telah menyelesaikan panduan memulai untuk membangun pengalaman hybrid.


Langsung ke output JSON Langsung ke output enum

Output JSON

Contoh berikut mengadaptasi contoh output JSON umum untuk mengakomodasi inferensi hybrid (misalnya, PREFER_ON_DEVICE).

Dalam skenario untuk contoh ini, model menghasilkan daftar profil karakter untuk cerita fantasi, dengan atribut terstruktur seperti nama, usia, spesies, dan aksesori opsional.

Anda dapat menentukan skema respons menggunakan salah satu pendekatan berikut:

  • Metode bantuan Schema Firebase (direkomendasikan): Gunakan metode bantuan (seperti Schema.object() dan Schema.enumString()) untuk menulis skema yang ringkas dan padat langsung dalam kode Anda tanpa boilerplate tambahan.

  • Skema JSON biasa: Gunakan objek Skema JSON standar jika Anda sudah memiliki definisi skema, berbagi skema di seluruh platform atau layanan backend, atau mengimpor skema dari file JSON.

Contoh 1: Menggunakan metode bantuan Schema Firebase

Contoh ini menggunakan metode bantuan Schema (seperti Schema.object, Schema.array, Schema.string, dan Schema.number) yang disediakan oleh Firebase AI Logic SDK untuk menentukan skema objek.

Sebelum mencoba contoh ini, selesaikan bagian Sebelum memulai dalam panduan ini untuk menyiapkan project dan aplikasi Anda.
Di bagian tersebut, Anda juga akan mengklik tombol untuk penyedia Gemini API yang dipilih sehingga Anda dapat melihat konten khusus penyedia di halaman ini.

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()));

Contoh 2: Menggunakan skema JSON biasa

Contoh ini menentukan skema hanya menggunakan JSON.

Sebelum mencoba contoh ini, selesaikan bagian Sebelum memulai dalam panduan ini untuk menyiapkan project dan aplikasi Anda.
Di bagian tersebut, Anda juga akan mengklik tombol untuk penyedia Gemini API yang dipilih sehingga Anda dapat melihat konten khusus penyedia di halaman ini.

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()));

Output enum

Contoh berikut mengadaptasi contoh output enum umum untuk mengakomodasi inferensi hybrid (misalnya, PREFER_ON_DEVICE).

Dalam skenario untuk contoh ini, model mengklasifikasikan deskripsi film dengan memilih satu genre dari daftar opsi yang diizinkan yang telah ditentukan (drama, comedy, atau documentary).

Anda dapat menentukan skema respons menggunakan salah satu pendekatan berikut:

  • Metode bantuan Schema Firebase (direkomendasikan): Gunakan metode bantuan (seperti Schema.object() dan Schema.enumString()) untuk menulis skema yang ringkas dan padat langsung dalam kode Anda tanpa boilerplate tambahan.

  • Skema JSON biasa: Gunakan objek Skema JSON standar jika Anda sudah memiliki definisi skema, berbagi skema di berbagai platform atau layanan backend, atau mengimpor skema dari file JSON.

Contoh 1: Menggunakan metode bantuan Schema Firebase

Contoh ini menggunakan metode bantuan Schema.enumString yang disediakan oleh Firebase AI Logic SDK untuk menentukan nilai enum yang diizinkan.

Sebelum mencoba contoh ini, selesaikan bagian Sebelum memulai dalam panduan ini untuk menyiapkan project dan aplikasi Anda.
Di bagian tersebut, Anda juga akan mengklik tombol untuk penyedia Gemini API yang dipilih sehingga Anda dapat melihat konten khusus penyedia di halaman ini.

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());

Contoh 2: Menggunakan skema JSON biasa

Contoh ini menentukan skema enum hanya menggunakan JSON.

Sebelum mencoba contoh ini, selesaikan bagian Sebelum memulai dalam panduan ini untuk menyiapkan project dan aplikasi Anda.
Di bagian tersebut, Anda juga akan mengklik tombol untuk penyedia Gemini API yang dipilih sehingga Anda dapat melihat konten khusus penyedia di halaman ini.

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());


Berikan masukan tentang pengalaman Anda menggunakan Firebase AI Logic