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. Misalnya, Anda mungkin menggunakan respons untuk tugas downstream lainnya yang memerlukan skema data yang sudah ditetapkan.

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

Berikut beberapa contohnya:

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

  • Membatasi cara model dapat merespons selama tugas klasifikasi.
    Misalnya, Anda dapat membuat model menganotasi teks dengan serangkaian label tertentu (misalnya, serangkaian 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 untuk aplikasi web.

Sebelum memulai

Pastikan Anda telah menyelesaikan panduan memulai untuk membangun pengalaman hybrid.

Menetapkan konfigurasi untuk output terstruktur

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

Untuk inferensi hybrid, gunakan inCloudParams dan onDeviceParams untuk mengonfigurasi model agar merespons dengan output terstruktur. Untuk mode lainnya, gunakan hanya konfigurasi yang berlaku.

  • Untuk inCloudParams: Tentukan responseMimeType yang sesuai (misalnya, application/json) serta responseSchema yang ingin Anda gunakan oleh model.

  • Untuk onDeviceParams: Tentukan responseConstraint yang ingin digunakan model.

Output JSON

Contoh berikut mengadaptasi contoh output JSON umum untuk mengakomodasi inferensi hybrid (dalam contoh ini, PREFER_ON_DEVICE):

Contoh 1: Menggunakan metode helper Schema Firebase

Contoh ini menggunakan metode helper yang disediakan oleh Firebase AI Logic SDK untuk membuat definisi skema lebih ringkas.

import {
  getAI,
  getGenerativeModel,
  Schema
} from "firebase/ai";

// This schema can also be defined as a plain JSON object.
// See next snippet for an example of a plain JSON schema.
const jsonSchema = Schema.object({
 properties: {
    characters: Schema.array({
      items: Schema.object({
        properties: {
          name: Schema.string(),
          accessory: Schema.string(),
          age: Schema.number(),
          species: Schema.string(),
        },
        optionalProperties: ["accessory"],
      }),
    }),
  }
});

const model = getGenerativeModel(ai, {
  mode: InferenceMode.PREFER_ON_DEVICE,
  inCloudParams: {
    generationConfig: {
      model: "gemini-3.1-flash-lite",
      responseMimeType: "application/json",
      responseSchema: jsonSchema
    },
  }
  onDeviceParams: {
    promptOptions: {
      responseConstraint: jsonSchema
    }
  }
});

const result = await model
  .generateContent(
    "Create profiles for some characters for a fantasy story.");

console.log(result.response.text());
console.log(JSON.parse(result.response.text()));

// ...

Contoh 2: Menggunakan skema JSON biasa

Contoh ini menentukan skema hanya menggunakan JSON dan menampilkan hasil yang sama.

import {
  getAI,
  getGenerativeModel,
  Schema
} from "firebase/ai";

// The JSON schema defined as a plain JSON object.
const jsonSchema = {
    "type": "object",
    "properties": {
        "characters": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "name": {
                        "type": "string",
                        "nullable": false
                    },
                    "accessory": {
                        "type": "string",
                        "nullable": false
                    },
                    "age": {
                        "type": "number",
                        "nullable": false
                    },
                    "species": {
                        "type": "string",
                        "nullable": false
                    }
                },
                "nullable": false,
                "required": [
                    "name",
                    "age",
                    "species"
                ]
            },
            "nullable": false
        }
    },
    "nullable": false,
    "required": [
        "characters"
    ]
};

const model = getGenerativeModel(ai, {
  mode: InferenceMode.PREFER_ON_DEVICE,
  inCloudParams: {
    generationConfig: {
      model: "gemini-3.1-flash-lite",
      responseMimeType: "application/json",
      responseSchema: jsonSchema
    },
  }
  onDeviceParams: {
    promptOptions: {
      responseConstraint: jsonSchema
    }
  }
});

const result = await model
  .generateContent(
    "Create profiles for some characters for a fantasy story.");

console.log(result.response.text());
console.log(JSON.parse(result.response.text()));

Output enum

Contoh berikut mengadaptasi contoh output enum umum untuk mengakomodasi inferensi hybrid (dalam contoh ini, PREFER_ON_DEVICE):

import {
  getAI,
  getGenerativeModel,
  Schema
} from "firebase/ai";

// enumSchema can also be defined as a plain JSON schema instead of
// using the `Schema` helper methods, just as in the JSON output example.
const enumSchema = Schema.enumString({
  enum: ["drama", "comedy", "documentary"],
});

const model = getGenerativeModel(ai, {
  mode: InferenceMode.PREFER_ON_DEVICE,
  inCloudParams: {
    generationConfig: {
      responseMimeType: "text/x.enum",
      responseSchema: enumSchema
    },
  }
  onDeviceParams: {
    promptOptions: {
      responseConstraint: enumSchema
    }
  }
});

// ...