כברירת מחדל, Gemini API מחזיר תשובות כטקסט לא מובנה. עם זאת, במקרים מסוימים נדרש טקסט מובנה, כמו JSON. לדוגמה, יכול להיות שאתם משתמשים בתשובה למשימות אחרות בהמשך שדורשות סכימת נתונים מוגדרת.
כדי לוודא שהפלט שהמודל יוצר תמיד תואם לסכימה ספציפית, אתם יכולים להגדיר סכימת תשובה שפועלת כמו תוכנית לתשובות של המודל. כך תוכלו לחלץ נתונים ישירות מהפלט של המודל, עם פחות עיבוד לאחר מכן.
הנה כמה דוגמאות:
מוודאים שהתשובה של המודל יוצרת קובץ JSON תקין ותואמת לסכימה שסיפקתם.
לדוגמה, המודל יכול ליצור רשומות מובְנות של מתכונים שתמיד כוללות את שם המתכון, רשימת המרכיבים והשלבים. כך תוכלו לנתח את המידע הזה ולהציג אותו בקלות רבה יותר בממשק המשתמש של האפליקציה.להגביל את האופן שבו המודל יכול להגיב במהלך משימות סיווג.
לדוגמה, אתם יכולים לבקש מהמודל להוסיף הערות לטקסט עם קבוצה ספציפית של תוויות (למשל, קבוצה ספציפית של ערכי enum כמוpositiveו-negative), במקום תוויות שהמודל מייצר (שיכולות להיות במידה מסוימת של שונות כמוgood,positive,negativeאוbad).
במדריך הזה מוסבר איך ליצור פלט JSON באמצעות ציון responseSchema בקריאה ל-generateContent. הוא מתמקד בקלט של טקסט בלבד, אבל Gemini יכול גם ליצור תשובות מובנות לבקשות מולטי-מודאליות שכוללות תמונות, סרטונים ואודיו כקלט.
בתחתית הדף הזה יש דוגמאות נוספות, כמו יצירת ערכי enum כפלט.
לפני שמתחילים
|
כדי לראות תוכן וקוד שספציפיים לספק, לוחצים על הספק Gemini API בדף הזה. |
אם עדיין לא עשיתם את זה, אתם צריכים לפעול לפי המדריך לתחילת הדרך, שבו מוסבר איך להגדיר את הפרויקט ב-Firebase, לקשר את האפליקציה ל-Firebase, להוסיף את ה-SDK, להפעיל את שירות הקצה העורפי של ספק ה-Gemini API שבחרתם וליצור מכונה של GenerativeModel.
כדי לבדוק את ההנחיות ולשפר אותן, מומלץ להשתמש ב-Google AI Studio.
מודלים שתומכים ביכולת הזו
gemini-4-argon-
gemini-3.8-flash(והגרסאות הישנות יותרgemini-3.7-flash,gemini-3.6-flashו-gemini-3.5-flash) -
gemini-3.5-flash-lite(והגרסה הישנה יותרgemini-3.1-flash-lite)
גם המודלים gemini-3.1-pro-preview ו-Gemini 2.5 לשימוש כללי (שיצאו משימוש) תומכים ביכולת הזו.
שלב 1: מגדירים סכֵימת תשובה
מגדירים סכֵימת תשובה כדי לציין את מבנה הפלט של המודל, את שמות השדות ואת סוג הנתונים הצפוי בכל שדה.
כשהמודל יוצר את התשובה, הוא משתמש בשם השדה ובהקשר מההנחיה. כדי לוודא שהכוונה שלכם ברורה, מומלץ להשתמש במבנה ברור, בשמות שדות חד-משמעיים ואפילו בתיאורים לפי הצורך.
שיקולים לגבי סכמות תשובה
כשכותבים סכֵימת תשובה, חשוב לזכור את הדברים הבאים:
גודל סכמת התשובה נכלל במגבלת הטוקנים לקלט.
תכונת סכמת התשובה תומכת בסוגי ה-MIME הבאים של תשובות:
application/json: פלט JSON כמו שמוגדר בסכֵימת התשובה (שימושי לדרישות של פלט מובנה)
text/x.enum: פלט של ערך טיפוס בן מנייה (enum) כמו שמוגדר בסכֵימת התשובה (שימושי למשימות סיווג)
התכונה "סכֵימת תשובה" תומכת בשדות הסכימה הבאים:
enum
items
maxItems
nullable
properties
required
אם תשתמשו בשדה לא נתמך, המודל עדיין יוכל לטפל בבקשה, אבל הוא יתעלם מהשדה. שימו לב שהרשימה שלמעלה היא קבוצת משנה של אובייקט הסכימה של OpenAPI 3.0.
כברירת מחדל, בערכות ה-SDK של Firebase AI Logic, כל השדות נחשבים חובה, אלא אם מציינים אותם כאופציונליים במערך
optionalProperties. בשדות האופציונליים האלה, המודל יכול לאכלס את השדות או לדלג עליהם. חשוב לזכור שזה הפוך מפעולת ברירת המחדל של שני הספקים של Gemini API אם משתמשים ב-SDK של השרת שלהם או ב-API שלהם ישירות.
שלב 2: יוצרים פלט JSON באמצעות סכמת התשובה
|
לפני שמנסים את הדוגמה הזו, צריך להשלים את השלבים בקטע לפני שמתחילים במדריך הזה כדי להגדיר את הפרויקט והאפליקציה. בקטע הזה צריך גם ללחוץ על כפתור של ספק Gemini API שבחרתם כדי לראות בדף הזה תוכן שספציפי לספק. |
בדוגמה הבאה מוסבר איך ליצור פלט JSON מובנה.
כשיוצרים את המכונה של GenerativeModel, מציינים את ה-responseMimeType המתאים (בדוגמה הזו, application/json) ואת ה-responseSchema שרוצים שהמודל ישתמש בו.
Swift
import FirebaseAILogic
// 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_MODEL_NAME",
// 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 הזה הן פונקציות השהיה וצריך לקרוא להן מהיקף 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_MODEL_NAME",
// 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 */ "<var>GEMINI_MODEL_NAME</var>",
/* 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_MODEL_NAME",
// 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_MODEL_NAME',
// 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_MODEL_NAME",
// 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 אחד בטקסט פשוט שהמודל בוחר מתוך רשימת ערכים שמוגדרים בסכמת התשובה שסופקה.
כדי לבצע את משימת הסיווג המובנה הזו, צריך לציין במהלך אתחול המודל את ה-responseMimeType המתאים (בדוגמה הזו, text/x.enum) ואת ה-responseSchema שבו רוצים שהמודל ישתמש.
Swift
import FirebaseAILogic
// 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_MODEL_NAME",
// 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 הזה הן פונקציות השהיה וצריך לקרוא להן מהיקף 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_MODEL_NAME",
// 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 */ "<var>GEMINI_MODEL_NAME</var>",
/* 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_MODEL_NAME",
// 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_MODEL_NAME',
// 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_MODEL_NAME",
// 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.");
איך בוחרים מודל שמתאימים לתרחיש לדוגמה ולאפליקציה.
אפשרויות אחרות לשליטה ביצירת תוכן
- מידע נוסף על עיצוב הנחיות כדי להשפיע על המודל ליצור פלט שמתאים לצרכים הספציפיים שלכם.
- להגדיר פרמטרים של המודל כדי לקבוע איך המודל ייצור תשובה, למשל מספר הטוקנים המקסימלי בפלט, הסבירות של טוקנים חוזרים בפלט וכו'.
- אתם יכולים להשתמש בהגדרות הבטיחות כדי לשנות את הסבירות לקבלת תשובות שעלולות להיחשב כמזיקות, כולל דברי שטנה ותוכן מיני בוטה.
- להגדיר הוראות מערכת כדי לכוון את ההתנהגות של המודל. התכונה הזו היא כמו הוראות מקדימות שמוסיפים לפני שהמודל נחשף להוראות נוספות ממשתמש הקצה.
שליחת משוב על חוויית השימוש ב-Firebase AI Logic