כברירת מחדל, 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-3.1-pro-preview-
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 2.5 לשימוש כללי תומכים ביכולת הזו, אבל כולם הוצאו משימוש.
שלב 1: הגדרת סכמת תשובה
מגדירים סכימת תגובה כדי לציין את המבנה של הפלט של המודל, את שמות השדות ואת סוג הנתונים הצפוי לכל שדה.
כשמודל יוצר את התשובה שלו, הוא משתמש בשם השדה ובהקשר מההנחיה. כדי לוודא שהכוונה שלכם ברורה, מומלץ להשתמש במבנה ברור, בשמות שדות חד-משמעיים ואפילו בתיאורים לפי הצורך.
שיקולים לגבי סכֵימות תשובה
כשכותבים את סכימת התגובה, חשוב לזכור את הדברים הבאים:
גודל סכמת התגובה נכלל במגבלת האסימונים של הקלט.
התכונה 'סכימת תגובה' תומכת בסוגי ה-MIME הבאים של תגובות:
application/json: פלט JSON כפי שמוגדר בסכימת התגובה (שימושי לדרישות של פלט מובנה)
text/x.enum: פלט של ערך enum כפי שמוגדר בסכימת התגובה (שימושי למשימות סיווג)
תכונת סכימת התגובה תומכת בשדות הסכימה הבאים:
enum
items
maxItems
nullable
properties
required
אם משתמשים בשדה שלא נתמך, המודל עדיין יכול לטפל בבקשה, אבל הוא מתעלם מהשדה. הערה: הרשימה שלמעלה היא קבוצת משנה של אובייקט הסכימה OpenAPI 3.0.
כברירת מחדל, כשמדובר ב-Firebase AI Logic SDK, כל השדות נחשבים שדות חובה, אלא אם מציינים אותם כשדות אופציונליים במערך
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?