כברירת מחדל, הפונקציה Gemini API מחזירה תשובות כטקסט לא מובנה. עם זאת, בחלק מתרחישי השימוש נדרשים טקסטים מובְנים, כמו JSON. לדוגמה, יכול להיות שאתם משתמשים בתגובה למשימות אחרות במורד הזרם שדורשות סכימה מוגדרת של נתונים.
כדי לוודא שהפלט שנוצר על ידי המודל תמיד עומד בסכימה מסוימת, אפשר להגדיר סכימת תגובה שעובדת כמו תוכנית עבודה לתשובות של המודל. לאחר מכן תוכלו לחלץ נתונים ישירות מהפלט של המודל עם פחות עיבוד נתונים לאחר העיבוד.
הנה כמה דוגמאות:
מוודאים שהתגובה של המודל יוצרת קובץ JSON תקין ועומדת בדרישות של הסכימה שסיפקתם.
לדוגמה, המודל יכול ליצור רשומות מובנות של מתכונים, שכוללות תמיד את שם המתכון, רשימת המצרכים והשלבים. כך תוכלו לנתח את המידע הזה בקלות רבה יותר ולהציג אותו בממשק המשתמש של האפליקציה.הגבלת האופן שבו מודל יכול להגיב במשימות סיווג
לדוגמה, אפשר להגדיר שהמודל יתווסף לטקסט הערות עם קבוצה ספציפית של תוויות (למשל, קבוצה ספציפית של ערכים מוגדרים מראש כמוpositive
ו-negative
), במקום תוויות שהמודל יוצר (שיכולות להיות עם מידה מסוימת של השתנות, כמוgood
, positive
, negative
אוbad
).
במדריך הזה מוסבר איך ליצור פלט JSON על ידי העברת responseSchema
בקריאה ל-generateContent
. הוא מתמקד בקלט של טקסט בלבד, אבל Gemini יכול גם ליצור תשובות מובנות לבקשות מולטי-מודאליות שכוללות תמונות, סרטונים ואודיו כקלט.
בתחתית הדף הזה מפורטות דוגמאות נוספות, למשל איך ליצור ערכים של enum כפלט.
לפני שמתחילים
לוחצים על ספק Gemini API כדי להציג בדף הזה תוכן וקוד ספציפיים לספק. |
אם עדיין לא עשיתם זאת, כדאי לעיין במדריך למתחילים, שבו מוסבר איך מגדירים את פרויקט Firebase, מחברים את האפליקציה ל-Firebase, מוסיפים את ה-SDK, מאתחלים את שירות הקצה העורפי של ספק Gemini API שבחרתם ויוצרים מכונה של GenerativeModel
.
כדי לבדוק את ההנחיות ולבצע בהן שינויים, ואפילו לקבל קטע קוד שנוצר, מומלץ להשתמש ב-Google AI Studio.
שלב 1: מגדירים סכימה של תגובה
מגדירים סכימה של תגובה כדי לציין את המבנה של הפלט של המודל, את שמות השדות ואת סוג הנתונים הצפוי לכל שדה.
כשמודל יוצר תשובה, הוא משתמש בשם השדה ובהקשר מההנחיה. כדי לוודא שהכוונה שלכם ברורה, מומלץ להשתמש במבנה ברור, בשמות שדות ברורים ואפילו בתיאורים לפי הצורך.
שיקולים לגבי סכימות תגובה
כשכותבים את הסכימה של התשובה, חשוב לזכור את הדברים הבאים:
הגודל של הסכימה של התשובה נספר במסגרת המגבלה על אסימוני הקלט.
התכונה response schema תומכת בסוגי ה-MIME הבאים של תגובות:
application/json
: פלט JSON כפי שמוגדר בסכימת התגובה (שימושי לדרישות של פלט מובנה)text/x.enum
: הפלט הוא ערך enum כפי שמוגדר בסכימת התגובה (שימושי למשימות סיווג)
התכונה 'סכימה של תגובה' תומכת בשדות הסכימה הבאים:
enum
items
maxItems
nullable
properties
required
אם משתמשים בשדה שלא נתמך, המודל עדיין יכול לטפל בבקשה, אבל הוא מתעלם מהשדה. שימו לב שהרשימה שלמעלה היא קבוצת משנה של אובייקט הסכימה של OpenAPI 3.0.
כברירת מחדל, ב-SDKs של Firebase AI Logic, כל השדות נחשבים חובה, אלא אם מציינים אותם כאופציונליים במערך
optionalProperties
. בשדות האופציונליים האלה, המודל יכול לאכלס את השדות או לדלג עליהם. חשוב לזכור שההתנהגות הזו שונה מברירת המחדל של שני הספקים של Gemini API אם משתמשים ב-SDK של השרת או ב-API שלהם ישירות.
שלב 2: יוצרים פלט JSON באמצעות הסכימה של התגובה
לפני שמנסים את הדוגמה הזו, צריך להשלים את הקטע לפני שמתחילים במדריך הזה כדי להגדיר את הפרויקט והאפליקציה. בקטע הזה צריך גם ללחוץ על הלחצן של ספק ה-Gemini API שבחרתם כדי להציג תוכן ספציפי לספק בדף הזה. |
הדוגמה הבאה מראה איך ליצור פלט JSON מובנה.
כשיוצרים את המכונה GenerativeModel
, מציינים את הערך המתאים של responseMimeType
(בדוגמה הזו, application/json
) וגם את הערך של responseSchema
שבו רוצים להשתמש במודל.
Swift
import FirebaseAI
// Provide a JSON schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
let jsonSchema = Schema.object(
properties: [
"characters": Schema.array(
items: .object(
properties: [
"name": .string(),
"age": .integer(),
"species": .string(),
"accessory": .enumeration(values: ["hat", "belt", "shoes"]),
],
optionalProperties: ["accessory"]
)
),
]
)
// Initialize the Gemini Developer API backend service
let ai = FirebaseAI.firebaseAI(backend: .googleAI())
// Create a `GenerativeModel` instance with a model that supports your use case
let model = ai.generativeModel(
modelName: "gemini-2.0-flash",
// In the generation config, set the `responseMimeType` to `application/json`
// and pass the JSON schema object into `responseSchema`.
generationConfig: GenerationConfig(
responseMIMEType: "application/json",
responseSchema: jsonSchema
)
)
let prompt = "For use in a children's card game, generate 10 animal-based characters."
let response = try await model.generateContent(prompt)
print(response.text ?? "No text in response.")
Kotlin
ב-Kotlin, השיטות ב-SDK הזה הן פונקציות השהיה (suspend) וצריך לקרוא להן מהיקף של פונקציית אירוע (coroutine).
// Provide a JSON schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
val jsonSchema = Schema.obj(
mapOf("characters" to Schema.array(
Schema.obj(
mapOf(
"name" to Schema.string(),
"age" to Schema.integer(),
"species" to Schema.string(),
"accessory" to Schema.enumeration(listOf("hat", "belt", "shoes")),
),
optionalProperties = listOf("accessory")
)
))
)
// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
modelName = "gemini-2.0-flash",
// In the generation config, set the `responseMimeType` to `application/json`
// and pass the JSON schema object into `responseSchema`.
generationConfig = generationConfig {
responseMimeType = "application/json"
responseSchema = jsonSchema
})
val prompt = "For use in a children's card game, generate 10 animal-based characters."
val response = generativeModel.generateContent(prompt)
print(response.text)
Java
ב-Java, שיטות הסטרימינג ב-SDK הזה מחזירות את הטיפוסPublisher
מספריית Reactive Streams.
// Provide a JSON schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
Schema jsonSchema = Schema.obj(
/* properties */
Map.of(
"characters", Schema.array(
/* items */ Schema.obj(
/* properties */
Map.of("name", Schema.str(),
"age", Schema.numInt(),
"species", Schema.str(),
"accessory",
Schema.enumeration(
List.of("hat", "belt", "shoes")))
))),
List.of("accessory"));
// In the generation config, set the `responseMimeType` to `application/json`
// and pass the JSON schema object into `responseSchema`.
GenerationConfig.Builder configBuilder = new GenerationConfig.Builder();
configBuilder.responseMimeType = "application/json";
configBuilder.responseSchema = jsonSchema;
GenerationConfig generationConfig = configBuilder.build();
// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.generativeModel(
/* modelName */ "gemini-2.0-flash",
/* generationConfig */ generationConfig);
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
Content content = new Content.Builder()
.addText("For use in a children's card game, generate 10 animal-based characters.")
.build();
// For illustrative purposes only. You should use an executor that fits your needs.
Executor executor = Executors.newSingleThreadExecutor();
ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(
response,
new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
String resultText = result.getText();
System.out.println(resultText);
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
},
executor);
Web
import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend, 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() });
// Provide a JSON schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
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"],
}),
}),
}
});
// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(ai, {
model: "gemini-2.0-flash",
// In the generation config, set the `responseMimeType` to `application/json`
// and pass the JSON schema object into `responseSchema`.
generationConfig: {
responseMimeType: "application/json",
responseSchema: jsonSchema
},
});
let prompt = "For use in a children's card game, generate 10 animal-based characters.";
let result = await model.generateContent(prompt)
console.log(result.response.text());
Dart
import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
// Provide a JSON schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
final jsonSchema = Schema.object(
properties: {
'characters': Schema.array(
items: Schema.object(
properties: {
'name': Schema.string(),
'age': Schema.integer(),
'species': Schema.string(),
'accessory':
Schema.enumString(enumValues: ['hat', 'belt', 'shoes']),
},
),
),
},
optionalProperties: ['accessory'],
);
// Initialize FirebaseApp
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
final model =
FirebaseAI.googleAI().generativeModel(
model: 'gemini-2.0-flash',
// In the generation config, set the `responseMimeType` to `application/json`
// and pass the JSON schema object into `responseSchema`.
generationConfig: GenerationConfig(
responseMimeType: 'application/json', responseSchema: jsonSchema));
final prompt = "For use in a children's card game, generate 10 animal-based characters.";
final response = await model.generateContent([Content.text(prompt)]);
print(response.text);
Unity
using Firebase;
using Firebase.AI;
// Provide a JSON schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
var jsonSchema = Schema.Object(
properties: new System.Collections.Generic.Dictionary<string, Schema> {
{ "characters", Schema.Array(
items: Schema.Object(
properties: new System.Collections.Generic.Dictionary<string, Schema> {
{ "name", Schema.String() },
{ "age", Schema.Int() },
{ "species", Schema.String() },
{ "accessory", Schema.Enum(new string[] { "hat", "belt", "shoes" }) },
},
optionalProperties: new string[] { "accessory" }
)
) },
}
);
// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
var model = FirebaseAI.DefaultInstance.GetGenerativeModel(
modelName: "gemini-2.0-flash",
// In the generation config, set the `responseMimeType` to `application/json`
// and pass the JSON schema object into `responseSchema`.
generationConfig: new GenerationConfig(
responseMimeType: "application/json",
responseSchema: jsonSchema
)
);
var prompt = "For use in a children's card game, generate 10 animal-based characters.";
var response = await model.GenerateContentAsync(prompt);
UnityEngine.Debug.Log(response.Text ?? "No text in response.");
איך בוחרים מודל שמתאים לתרחיש לדוגמה ולאפליקציה שלכם
דוגמאות נוספות
כאן מפורטות כמה דוגמאות נוספות לאופן שבו אפשר להשתמש בפלט מובנה וליצור אותו.יצירת ערכי enum כפלט
לפני שמנסים את הדוגמה הזו, צריך להשלים את הקטע לפני שמתחילים במדריך הזה כדי להגדיר את הפרויקט והאפליקציה. בקטע הזה צריך גם ללחוץ על הלחצן של ספק ה-Gemini API שבחרתם כדי להציג תוכן ספציפי לספק בדף הזה. |
בדוגמה הבאה מוסבר איך משתמשים בסכימת תגובה למשימות סיווג. המודל מתבקש לזהות את הז'אנר של סרט על סמך התיאור שלו. הפלט הוא ערך enum אחד בטקסט ללא סימון (plain text) שהמודל בוחר מתוך רשימה של ערכים שמוגדרים בסכימת התגובה שצוינה.
כדי לבצע את המשימה הזו של סיווג מובנה, צריך לציין במהלך האינטוליזציה של המודל את responseMimeType
המתאים (בדוגמה הזו, text/x.enum
) ואת responseSchema
שבו רוצים שהמודל ישתמש.
Swift
import FirebaseAI
// Provide an enum schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
let enumSchema = Schema.enumeration(values: ["drama", "comedy", "documentary"])
// Initialize the Gemini Developer API backend service
let ai = FirebaseAI.firebaseAI(backend: .googleAI())
// Create a `GenerativeModel` instance with a model that supports your use case
let model = ai.generativeModel(
modelName: "gemini-2.0-flash",
// In the generation config, set the `responseMimeType` to `text/x.enum`
// and pass the enum schema object into `responseSchema`.
generationConfig: GenerationConfig(
responseMIMEType: "text/x.enum",
responseSchema: enumSchema
)
)
let 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.
"""
let response = try await model.generateContent(prompt)
print(response.text ?? "No text in response.")
Kotlin
ב-Kotlin, השיטות ב-SDK הזה הן פונקציות השהיה (suspend) וצריך לקרוא להן מהיקף של פונקציית אירוע (coroutine).
// Provide an enum schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
val enumSchema = Schema.enumeration(listOf("drama", "comedy", "documentary"))
// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
modelName = "gemini-2.0-flash",
// In the generation config, set the `responseMimeType` to `text/x.enum`
// and pass the enum schema object into `responseSchema`.
generationConfig = generationConfig {
responseMimeType = "text/x.enum"
responseSchema = enumSchema
})
val 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.
"""
val response = generativeModel.generateContent(prompt)
print(response.text)
Java
ב-Java, שיטות הסטרימינג ב-SDK הזה מחזירות את הטיפוסPublisher
מספריית Reactive Streams.
// Provide an enum schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
Schema enumSchema = Schema.enumeration(List.of("drama", "comedy", "documentary"));
// In the generation config, set the `responseMimeType` to `text/x.enum`
// and pass the enum schema object into `responseSchema`.
GenerationConfig.Builder configBuilder = new GenerationConfig.Builder();
configBuilder.responseMimeType = "text/x.enum";
configBuilder.responseSchema = enumSchema;
GenerationConfig generationConfig = configBuilder.build();
// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.generativeModel(
/* modelName */ "gemini-2.0-flash",
/* generationConfig */ generationConfig);
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
String 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.";
Content content = new Content.Builder().addText(prompt).build();
// For illustrative purposes only. You should use an executor that fits your needs.
Executor executor = Executors.newSingleThreadExecutor();
ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(
response,
new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
String resultText = result.getText();
System.out.println(resultText);
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
},
executor);
Web
import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend, 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() });
// Provide an enum schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
const enumSchema = Schema.enumString({
enum: ["drama", "comedy", "documentary"],
});
// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(ai, {
model: "gemini-2.0-flash",
// In the generation config, set the `responseMimeType` to `text/x.enum`
// and pass the JSON schema object into `responseSchema`.
generationConfig: {
responseMimeType: "text/x.enum",
responseSchema: enumSchema,
},
});
let 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.`;
let result = await model.generateContent(prompt);
console.log(result.response.text());
Dart
import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
// Provide an enum schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
final enumSchema = Schema.enumString(enumValues: ['drama', 'comedy', 'documentary']);
// Initialize FirebaseApp
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
final model =
FirebaseAI.googleAI().generativeModel(
model: 'gemini-2.0-flash',
// In the generation config, set the `responseMimeType` to `text/x.enum`
// and pass the enum schema object into `responseSchema`.
generationConfig: GenerationConfig(
responseMimeType: 'text/x.enum', responseSchema: enumSchema));
final 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.
""";
final response = await model.generateContent([Content.text(prompt)]);
print(response.text);
Unity
using Firebase;
using Firebase.AI;
// Provide an enum schema object using a standard format.
// Later, pass this schema object into `responseSchema` in the generation config.
var enumSchema = Schema.Enum(new string[] { "drama", "comedy", "documentary" });
// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
var model = FirebaseAI.DefaultInstance.GetGenerativeModel(
modelName: "gemini-2.0-flash",
// In the generation config, set the `responseMimeType` to `text/x.enum`
// and pass the enum schema object into `responseSchema`.
generationConfig: new GenerationConfig(
responseMimeType: "text/x.enum",
responseSchema: enumSchema
)
);
var 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.
";
var response = await model.GenerateContentAsync(prompt);
UnityEngine.Debug.Log(response.Text ?? "No text in response.");
איך בוחרים מודל שמתאים לתרחיש לדוגמה ולאפליקציה שלכם
אפשרויות נוספות לשליטה ביצירת תוכן
- מידע נוסף על עיצוב הנחיות כדי שתוכלו להשפיע על המודל כך שיניב פלט ספציפי לצרכים שלכם.
- מגדירים פרמטרים של מודל כדי לקבוע איך המודל ייצור תשובה. במודלים מסוג Gemini, הפרמטרים האלה כוללים את מספר האסימונים המקסימלי בפלט, הטמפרטורה, topK ו-topP. במודלים מסוג Imagen, האפשרויות האלה כוללות יחס גובה-רוחב, יצירת אנשים, הוספת סימני מים וכו'.
- אתם יכולים להשתמש בהגדרות הבטיחות כדי לשנות את הסבירות לקבלת תשובות שעשויות להיחשב כמזיקות, כולל דברי שטנה ותוכן מיני בוטה.
- מגדירים הוראות מערכת כדי להשפיע על התנהגות המודל. התכונה הזו היא כמו מבוא שמוסיפים לפני שהמודל נחשף להוראות נוספות ממשתמש הקצה.
שליחת משוב על חוויית השימוש ב-Firebase AI Logic