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 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 adalah beberapa contoh kasus penggunaan:
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 sepertipositivedannegative), bukan label yang dihasilkan model (yang dapat memiliki tingkat variabilitas sepertigood,positive,negative, ataubad).
Halaman ini menjelaskan cara membuat output terstruktur (seperti JSON dan enum) dalam pengalaman hybrid untuk aplikasi web.
Buka output JSON Buka output enum
Konfigurasi untuk output terstruktur
Pembuatan output terstruktur (seperti JSON dan enum) didukung untuk inferensi menggunakan model yang dihosting di cloud dan di perangkat.
Mode inferensi hybrid: Konfigurasi
inCloudParamsdanonDeviceParamsagar model merespons dengan output terstruktur, terlepas dari apakah inferensi berjalan di cloud atau di perangkat:Untuk model di perangkat: Tentukan
responseConstraintdionDeviceParamsmenggunakan skema yang dibuat dengan metode bantuanSchemaatau skema JSON biasa.Untuk model yang dihosting di cloud: Tentukan
responseMimeType(application/jsonuntuk JSON atautext/x.enumuntuk enum) danresponseSchemadiinCloudParams.
Mode inferensi non-hibrida: 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.
Buka output JSON Buka 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 membuat 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 helper
SchemaFirebase (direkomendasikan): Gunakan metode helper (sepertiSchema.object()danSchema.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, membagikan skema di seluruh platform atau layanan backend, atau mengimpor skema dari file JSON.
Contoh 1: Menggunakan metode helper Schema Firebase
Contoh ini menggunakan metode helper Schema (seperti Schema.object,
Schema.array, Schema.string, dan Schema.number) yang disediakan oleh
Firebase AI Logic SDK untuk menentukan skema objek.
|
Sebelum mencoba sampel 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 Anda pilih 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 sampel 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 Anda pilih 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 sebelumnya
(drama, comedy, atau documentary).
Anda dapat menentukan skema respons menggunakan salah satu pendekatan berikut:
Metode helper
SchemaFirebase (direkomendasikan): Gunakan metode helper (sepertiSchema.object()danSchema.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, membagikan skema di seluruh platform atau layanan backend, atau mengimpor skema dari file JSON.
Contoh 1: Menggunakan metode helper Schema Firebase
Contoh ini menggunakan metode helper Schema.enumString yang disediakan oleh
SDK Firebase AI Logic untuk menentukan nilai enum yang diizinkan.
|
Sebelum mencoba sampel 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 Anda pilih 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 menggunakan JSON saja.
|
Sebelum mencoba sampel 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 Anda pilih 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());
Memberikan masukan tentang pengalaman Anda dengan Firebase AI Logic