כברירת מחדל, מודלים של Gemini מחזירים תשובות כטקסט לא מובנה. עם זאת, יש תרחישי שימוש שבהם נדרש טקסט מובנה (כמו JSON או enums). לדוגמה, יכול להיות שאתם משתמשים בתשובה למשימות אחרות בהמשך התהליך שדורשות סכימת נתונים מוגדרת.
כדי לוודא שהפלט שנוצר על ידי המודל תמיד תואם לסכימה ספציפית, אתם יכולים להגדיר סכימה, שפועלת כמו תוכנית לתשובות של המודל. לאחר מכן, אפשר לחלץ נתונים ישירות מהפלט של המודל עם פחות עיבוד לאחר מכן.
הנה מספר תרחישים לדוגמה:
לוודא שהתשובה של המודל היא JSON תקין ותואמת לסכימה שסיפקתם.
לדוגמה, המודל יכול ליצור רשומות מובנות למתכונים שתמיד כוללות את שם המתכון, רשימת המצרכים והשלבים. לאחר מכן, תוכלו לנתח ולהציג את המידע הזה בקלות רבה יותר בממשק המשתמש של האפליקציה.הגבלת האופן שבו מודל יכול להגיב במהלך משימות סיווג
לדוגמה, אתם יכולים לבקש מהמודל להוסיף הערות לטקסט עם קבוצה ספציפית של תוויות (למשל, קבוצה ספציפית של סוגי מנייה כמוpositiveו-negative), במקום תוויות שהמודל יוצר (שיכולות להיות עם מידה מסוימת של שונות כמוgood,positive,negativeאוbad).
בדף הזה מוסבר איך ליצור פלט מובנה (כמו JSON וספירות) בחוויות היברידיות באפליקציות אינטרנט.
הגדרות לפלט מובנה
יצירת פלט מובנה (כמו JSON ו-enums) נתמכת להסקת מסקנות באמצעות מודלים שמארחים בענן ומודלים במכשיר.
מצבי הסקה היברידיים: מגדירים את
inCloudParamsואתonDeviceParamsכך שהמודל יגיב עם פלט מובנה, בלי קשר לשאלה אם ההסקה פועלת בענן או במכשיר:למודלים במכשיר: מציינים את
responseConstraintב-onDeviceParamsבאמצעות סכימה שנוצרה עם שיטות העזר שלSchemaאו סכימת JSON רגילה.למודלים שמתארחים בענן: מציינים את
responseMimeType(application/jsonל-JSON אוtext/x.enumל-enums) ואתresponseSchemaב-inCloudParams.
מצבי הסקה לא היברידיים: משתמשים רק בהגדרה הרלוונטית שמתוארת למעלה.
לפני שמתחילים
|
לוחצים על הספק Gemini API כדי לראות בדף הזה תוכן וקוד שספציפיים לספק. |
חשוב לוודא שהשלמתם את המדריך למתחילים ליצירת חוויות היברידיות.
פלט JSON
בדוגמאות הבאות מותאמת דוגמת הפלט הכללית של JSON כדי להתאים להסקת מסקנות היברידית (לדוגמה, PREFER_ON_DEVICE).
בתרחיש של הדוגמאות האלה, המודל יוצר רשימה של פרופילים של דמויות לסיפור פנטזיה, עם מאפיינים מובנים כמו שם, גיל, מין ואביזרים אופציונליים.
אפשר להגדיר את סכימות התגובה באמצעות אחת מהגישות הבאות:
שימוש בשיטות עזר של
SchemaFirebase (מומלץ): שימוש בשיטות עזר (כמוSchema.object()ו-Schema.enumString()) כדי לכתוב סכימות תמציתיות וקומפקטיות ישירות בקוד, בלי להשתמש בקוד חוזר.סכימת JSON רגילה: משתמשים באובייקט JSON Schema רגיל אם כבר יש לכם הגדרות סכימה קיימות, אם אתם משתפים סכימות בין פלטפורמות או שירותי קצה עורפי, או אם אתם מייבאים סכימות מקובצי JSON.
דוגמה 1: שימוש בשיטות העזר של Firebase Schema
בדוגמה הזו נעשה שימוש בשיטות עזר של Schema (כמו Schema.object, Schema.array, Schema.string ו-Schema.number) שסופקו על ידי Firebase AI Logic SDK כדי להגדיר את סכימת האובייקט.
|
לפני שמנסים את הדוגמה הזו, צריך להשלים את השלבים שבקטע לפני שמתחילים במדריך הזה כדי להגדיר את הפרויקט והאפליקציה. בקטע הזה, צריך גם ללחוץ על לחצן של ספק 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 Schema רגיל אם כבר יש לכם הגדרות סכימה קיימות, אם אתם משתפים סכימות בין פלטפורמות או שירותי קצה עורפי, או אם אתם מייבאים סכימות מקובצי JSON.
דוגמה 1: שימוש בשיטות העזר של Firebase Schema
בדוגמה הזו נעשה שימוש בשיטת העזר Schema.enumString שסופקה על ידי Firebase AI Logic SDK כדי להגדיר ערכי enum מותרים.
|
לפני שמנסים את הדוגמה הזו, צריך להשלים את השלבים שבקטע לפני שמתחילים במדריך הזה כדי להגדיר את הפרויקט והאפליקציה. בקטע הזה, צריך גם ללחוץ על לחצן של ספק 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?