API مربوط به Gemini به طور پیشفرض پاسخها را به صورت متن بدون ساختار برمیگرداند. با این حال، برخی از موارد استفاده به متن ساختاریافته مانند JSON نیاز دارند. به عنوان مثال، ممکن است از این پاسخ برای سایر وظایف پاییندستی که به یک طرح داده مشخص نیاز دارند، استفاده کنید.
برای اطمینان از اینکه خروجی تولید شده مدل همیشه از یک طرح خاص پیروی میکند، میتوانید یک طرح پاسخ تعریف کنید که مانند یک طرح اولیه برای پاسخهای مدل عمل میکند. سپس میتوانید مستقیماً دادهها را از خروجی مدل با پردازش کمتر پس از تولید استخراج کنید.
در اینجا چند مثال آورده شده است:
اطمینان حاصل کنید که پاسخ مدل، JSON معتبری تولید میکند و با طرحواره ارائه شده شما مطابقت دارد.
برای مثال، این مدل میتواند ورودیهای ساختاریافتهای برای دستور پختها ایجاد کند که همیشه شامل نام دستور پخت، لیست مواد تشکیلدهنده و مراحل پخت باشد. سپس میتوانید این اطلاعات را راحتتر تجزیه و در رابط کاربری برنامه خود نمایش دهید.نحوه پاسخگویی یک مدل در طول وظایف طبقهبندی را محدود کنید.
برای مثال، میتوانید کاری کنید که مدل، متن را با مجموعهای خاص از برچسبها (مثلاً مجموعهای خاص از enumها مانندpositiveوnegative) حاشیهنویسی کند، نه با برچسبهایی که مدل تولید میکند (که میتوانند درجهای از تغییرپذیری مانندgood،positive،negativeیاbadداشته باشند).
این راهنما به شما نشان میدهد که چگونه با ارائه یک responseSchema در فراخوانی generateContent خروجی JSON تولید کنید. این راهنما بر ورودیهای متنی تمرکز دارد، اما Gemini میتواند پاسخهای ساختاریافتهای را نیز برای درخواستهای چندوجهی که شامل تصاویر، ویدیوها و صدا به عنوان ورودی هستند، تولید کند.
در پایین این صفحه مثالهای بیشتری وجود دارد، مانند نحوه تولید مقادیر enum به عنوان خروجی .
قبل از اینکه شروع کنی
برای مشاهده محتوا و کد مخصوص ارائهدهنده در این صفحه، روی ارائهدهنده API Gemini خود کلیک کنید. |
اگر هنوز این کار را نکردهاید، راهنمای شروع به کار را تکمیل کنید، که نحوه راهاندازی پروژه Firebase، اتصال برنامه به Firebase، افزودن SDK، راهاندازی سرویس backend برای ارائهدهنده API انتخابی Gemini و ایجاد یک نمونه GenerativeModel را شرح میدهد.
مرحله ۱ : تعریف یک طرحواره پاسخ
یک طرحواره پاسخ تعریف کنید تا ساختار خروجی مدل، نام فیلدها و نوع داده مورد انتظار برای هر فیلد را مشخص کند.
وقتی یک مدل پاسخ خود را تولید میکند، از نام فیلد و متن موجود در اعلان شما استفاده میکند. برای اطمینان از اینکه منظور شما واضح است، توصیه میکنیم از یک ساختار واضح، نام فیلدهای بدون ابهام و حتی توضیحات در صورت نیاز استفاده کنید.
ملاحظات مربوط به طرحوارههای پاسخ
هنگام نوشتن طرحواره پاسخ خود، موارد زیر را در نظر داشته باشید:
اندازه طرحواره پاسخ، جزو محدودیت توکن ورودی محسوب میشود.
ویژگی طرحواره پاسخ از انواع MIME پاسخ زیر پشتیبانی میکند:
application/json: خروجی JSON همانطور که در طرح پاسخ تعریف شده است (برای الزامات خروجی ساختاریافته مفید است)text/x.enum: یک مقدار enum مطابق با تعریفشده در طرح پاسخ، خروجی میدهد (برای وظایف طبقهبندی مفید است)
ویژگی طرحواره پاسخ از فیلدهای طرحواره زیر پشتیبانی میکند:
enum
itemsmaxItems
nullableproperties
requiredاگر از یک فیلد پشتیبانی نشده استفاده کنید، مدل همچنان میتواند درخواست شما را مدیریت کند، اما آن فیلد را نادیده میگیرد. توجه داشته باشید که لیست بالا زیرمجموعهای از شیء طرحواره OpenAPI 3.0 است.
به طور پیشفرض، برای Firebase AI Logic SDKها، همه فیلدها الزامی در نظر گرفته میشوند، مگر اینکه آنها را در یک آرایه
optionalPropertiesبه عنوان اختیاری مشخص کنید. برای این فیلدهای اختیاری، مدل میتواند فیلدها را پر کند یا از آنها صرف نظر کند. توجه داشته باشید که این برخلاف رفتار پیشفرض دو ارائهدهنده API Gemini است اگر از SDKهای سرور یا API آنها مستقیماً استفاده کنید.
مرحله ۲ : تولید خروجی JSON با استفاده از طرحواره پاسخ شما
| قبل از امتحان کردن این نمونه، بخش «قبل از شروع» این راهنما را برای راهاندازی پروژه و برنامه خود تکمیل کنید. در آن بخش، شما همچنین میتوانید روی دکمهای برای ارائهدهندهی API Gemini انتخابی خود کلیک کنید تا محتوای خاص ارائهدهنده را در این صفحه مشاهده کنید . |
مثال زیر نحوه تولید خروجی ساختار یافته JSON را نشان میدهد.
هنگام ایجاد نمونه GenerativeModel ، responseMimeType مناسب (در این مثال application/json ) و همچنین responseSchema مورد نظر برای استفاده در مدل را مشخص کنید.
سویفت
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.5-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
برای کاتلین، متدهای موجود در این SDK توابع suspend هستند و باید از یک scope کوروتین فراخوانی شوند.
// 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.5-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
برای جاوا، متدهای استریمینگ در این 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.5-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.5-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.5-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);
وحدت
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.5-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.");
یاد بگیرید که چگونه یک مدل را انتخاب کنیدمناسب برای مورد استفاده و برنامه شما.
مثالهای اضافی
در اینجا چند مثال دیگر از نحوه استفاده و تولید خروجی ساختاریافته آورده شده است.تولید مقادیر شمارشی به عنوان خروجی
| قبل از امتحان کردن این نمونه، بخش «قبل از شروع» این راهنما را برای راهاندازی پروژه و برنامه خود تکمیل کنید. در آن بخش، شما همچنین میتوانید روی دکمهای برای ارائهدهندهی API Gemini انتخابی خود کلیک کنید تا محتوای خاص ارائهدهنده را در این صفحه مشاهده کنید . |
مثال زیر نحوه استفاده از یک طرحواره پاسخ برای یک کار طبقهبندی را نشان میدهد. از مدل خواسته میشود ژانر یک فیلم را بر اساس توضیحات آن شناسایی کند. خروجی یک مقدار شمارشی متن ساده است که مدل از لیستی از مقادیر تعریف شده در طرحواره پاسخ ارائه شده انتخاب میکند.
برای انجام این وظیفه طبقهبندی ساختاریافته، باید در طول مقداردهی اولیه مدل، responseMimeType مناسب (در این مثال، text/x.enum ) و همچنین responseSchema مورد نظر برای استفاده مدل را مشخص کنید.
سویفت
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.5-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
برای کاتلین، متدهای موجود در این SDK توابع suspend هستند و باید از یک scope کوروتین فراخوانی شوند.
// 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.5-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
برای جاوا، متدهای استریمینگ در این 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.5-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.5-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.5-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);
وحدت
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.5-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 بازخورد دهید