Gemini モデルは、デフォルトでレスポンスを非構造化テキストとして返します。ただし、一部のユースケースでは、構造化テキスト(JSON や列挙型など)が必要です。たとえば、確立されたデータ スキーマを必要とする他のダウンストリーム タスクにレスポンスを使用している場合があります。
モデルの生成済み出力が常に特定のスキーマに準拠するようにするには、スキーマを定義します。これは、モデルのレスポンスのブループリントのように機能します。これにより、後処理をあまり行わずにモデルの出力からデータを直接抽出できます。
次のような処理が例として挙げられます。
モデルのレスポンスが有効な JSON を生成し、指定されたスキーマに準拠していることを確認します。
たとえば、モデルはレシピ名、材料リスト、手順を常に含むレシピの構造化されたエントリを生成できます。これにより、アプリの UI でこの情報をより簡単に解析して表示できます。分類タスク中にモデルが応答する方法を制限します。
たとえば、モデルが生成するラベル(good、positive、negative、badなど、ある程度のばらつきがある可能性がある)ではなく、特定のラベルセット(positiveやnegativeなどの特定の列挙型セットなど)でテキストにアノテーションを付けるようにモデルを設定できます。
このページでは、ウェブアプリのハイブリッド エクスペリエンスで構造化された出力(JSON や列挙型など)を生成する方法について説明します。
構造化出力の構成
クラウドホスト型モデルとオンデバイス モデルの両方を使用した推論で、構造化された出力(JSON や列挙型など)の生成がサポートされています。
ハイブリッド推論モード: 推論がクラウドで実行されるかデバイス上で実行されるかにかかわらず、モデルが構造化された出力で応答するように、
inCloudParamsとonDeviceParamsの両方を構成します。オンデバイス モデルの場合:
Schemaヘルパー メソッドで作成されたスキーマまたはプレーンな JSON スキーマを使用して、onDeviceParamsのresponseConstraintを指定します。クラウドホスト型モデルの場合:
inCloudParamsでresponseMimeType(JSON の場合はapplication/json、列挙型の場合はtext/x.enum)とresponseSchemaを指定します。
非ハイブリッド推論モード: 上記の該当する構成のみを使用します。
始める前に
|
Gemini API プロバイダをクリックして、このページでプロバイダ固有のコンテンツとコードを表示します。 |
ハイブリッド エクスペリエンスの構築に関するスタートガイドを完了していることを確認します。
JSON 出力
次の例では、一般的な JSON 出力の例をハイブリッド推論(PREFER_ON_DEVICE など)に対応するように変更しています。
これらの例のシナリオでは、モデルはファンタジー ストーリーのキャラクター プロファイルのリストを生成します。これには、名前、年齢、種族、オプションのアクセサリーなどの構造化された属性が含まれます。
レスポンス スキーマは、次のいずれかの方法で定義できます。
Firebase
Schemaヘルパー メソッド (推奨): ヘルパー メソッド(Schema.object()やSchema.enumString()など)を使用して、追加のボイラープレートなしで、簡潔でコンパクトなスキーマをコードに直接記述します。プレーン JSON スキーマ: 既存のスキーマ定義がある場合、プラットフォームやバックエンド サービス間でスキーマを共有する場合、JSON ファイルからスキーマをインポートする場合は、標準の JSON スキーマ オブジェクトを使用します。
例 1: Firebase Schema ヘルパー メソッドを使用する
この例では、Firebase AI Logic SDK が提供する Schema ヘルパー メソッド(Schema.object、Schema.array、Schema.string、Schema.number など)を使用して、オブジェクト スキーマを定義します。
|
このサンプルを試す前に、このガイドの始める前にのセクションを完了して、プロジェクトとアプリを設定してください。 このセクションでは、選択した 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()));
列挙型の出力
次の例では、一般的な列挙型出力の例をハイブリッド推論(PREFER_ON_DEVICE など)に対応するように変更しています。
これらの例のシナリオでは、モデルは、許可されているオプション(drama、comedy、documentary)の事前定義されたリストから 1 つのジャンルを選択して、映画の説明を分類します。
レスポンス スキーマは、次のいずれかの方法で定義できます。
Firebase
Schemaヘルパー メソッド (推奨): ヘルパー メソッド(Schema.object()やSchema.enumString()など)を使用して、追加のボイラープレートなしで、簡潔でコンパクトなスキーマをコードに直接記述します。プレーン JSON スキーマ: 既存のスキーマ定義がある場合、プラットフォームやバックエンド サービス間でスキーマを共有する場合、JSON ファイルからスキーマをインポートする場合は、標準の JSON スキーマ オブジェクトを使用します。
例 1: Firebase Schema ヘルパー メソッドを使用する
この例では、Firebase AI Logic SDK で提供される Schema.enumString ヘルパー メソッドを使用して、許可される列挙型の値を定義します。
|
このサンプルを試す前に、このガイドの始める前にのセクションを完了して、プロジェクトとアプリを設定してください。 このセクションでは、選択した 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 スキーマを使用する
この例では、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 の使用感についてフィードバックを送信する