Gemini API بهطور پیشفرض پاسخها را بهصورت نوشتار بدون ساختار برمیگرداند. بااینحال، برخیاز موارد استفاده به نوشتار ساختاریافته، مانند JSON، نیاز دارند. برای مثال، ممکن است از پاسخ برای سایر کارهای پاییندستی که به طرحواره دادههای تثبیتشده نیاز دارند استفاده کنید.
برای اطمینان از اینکه برونداد تولیدشده مدل همیشه از طرحواره خاصی پیروی میکند، میتوانید طرحواره پاسخ تعریف کنید که مانند طرحی برای پاسخهای مدل عمل میکند. سپس میتوانید مستقیماً دادهها را از خروجی مدل با پسپردازش کمتر استخراج کنید.
چند نمونه در زیر آمده است:
مطمئن شوید که پاسخ مدل JSON معتبر تولید میکند و با طرحواره ارائهشده شما مطابقت دارد.
برای مثال، مدل میتواند ورودیهای ساختاریافتهای برای دستورهای پخت تولید کند که همیشه شامل نام دستور پخت، فهرست مواد اولیه، و مراحل باشد. سپس میتوانید این اطلاعات را راحتتر در میانای کاربر برنامهتان تجزیه و نمایش دهید.محدود کردن نحوه پاسخ دادن مدل درطول تکالیف طبقهبندی.
برای مثال، میتوانید از مدل بخواهید نوشتار را با مجموعه خاصی از برچسبها (مثلاً مجموعه خاصی از شمارشها مانندpositiveوnegative) حاشیهنویسی کند، نه برچسبهایی که مدل تولید میکند (که ممکن است درجاتی از تنوع مانندgood،positive،negative، یاbadداشته باشند).
این راهنما به شما نشان میدهد که چگونه با ارائه responseSchema
در تماس با generateContent، خروجی JSON تولید کنید. این آموزش بر ورودیهای فقط نوشتاری تمرکز دارد، اما Gemini میتواند
پاسخهای ساختاریافتهای نیز برای درخواستهای چندحالته که شامل تصاویر،
ویدیوها، و صدا بهعنوان ورودی هستند تولید کند.
در پایین این صفحه، نمونههای بیشتری وجود دارد، مانند نحوه تولید مقادیر enum بهعنوان خروجی.
قبل از شروع
|
روی ارائهدهنده Gemini API کلیک کنید تا محتوا و کد مختص ارائهدهنده را در این صفحه ببینید. |
اگر قبلاً این کار را نکردهاید،
راهنمای شروع به کار را تکمیل کنید که نحوه
راهاندازی پروژه Firebase، اتصال برنامه به Firebase، افزودن کیت توسعه نرمافزار،
مقداردهی اولیه سرویس پسبک برای ارائهدهنده 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 با کاربرد عمومی (که
منسوخ شدهاند) نیز از این قابلیت پشتیبانی میکنند.
مرحله ۱: تعریف طرحواره پاسخ
طرحواره پاسخ را برای مشخص کردن ساختار خروجی مدل، نام فیلدها، و نوع داده موردانتظار برای هر فیلد تعریف کنید.
وقتی مدلی پاسخ خود را تولید میکند، از نام فیلد و بافت پیامواره شما استفاده میکند. برای اطمینان از اینکه قصد شما واضح است، توصیه میکنیم از ساختار واضح، نامهای فیلد بدون ابهام، و حتی شرح درصورت نیاز استفاده کنید.
ملاحظات مربوط به طرحوارههای پاسخ
هنگام نوشتن طرحواره پاسخ، موارد زیر را درنظر داشته باشید:
اندازه طرحواره پاسخ جزو حد نشانه ورودی محاسبه میشود.
ویژگی طرحواره پاسخ از انواع MIME پاسخ زیر پشتیبانی میکند:
application/json: خروجی JSON همانطور که در طرحواره پاسخ تعریف شده است (برای الزامات خروجی ساختاریافته مفید است)text/x.enum: یک مقدار enum را همانطور که در طرحواره پاسخ تعریف شده است برونداد میکند (برای کارهای طبقهبندی مفید است)
ویژگی طرحواره پاسخ از فیلدهای طرحواره زیر پشتیبانی میکند:
enum
items
maxItems
nullable
properties
required
اگر از فیلد پشتیبانینشده استفاده کنید، مدل همچنان میتواند درخواستتان را مدیریت کند، اما فیلد را نادیده میگیرد. توجه داشته باشید که فهرست بالا زیرمجموعهای از شیء طرحواره OpenAPI 3.0 است.
بهطور پیشفرض، برای کیتهای توسعه نرمافزار Firebase AI Logic، همه فیلدها الزامی درنظر گرفته میشوند مگراینکه آنها را بهعنوان اختیاری در یک آرایه
optionalPropertiesمشخص کنید. برای این فیلدهای اختیاری، مدل میتواند فیلدها را پر کند یا از آنها رد شود. توجه داشته باشید که این برخلاف رفتار پیشفرض دو Gemini API ارائهدهنده است اگر از کیتهای توسعه نرمافزار سرور یا میانای برنامهسازی کاربردی آنها مستقیماً استفاده کنید.
مرحله ۲: تولید خروجی 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، روشهای موجود در این کیت توسعه نرمافزار توابع تعلیق هستند و باید از دامنه 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، روشهای جاریسازی در این کیت توسعه نرمافزار نوع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 کلیک خواهید کرد تا محتوای مختص ارائهدهنده را در این صفحه ببینید. |
مثال زیر نحوه استفاده از طرحواره پاسخ را برای تکلیف طبقهبندی نشان میدهد. از مدل خواسته میشود ژانر فیلمی را براساس شرح آن شناسایی کند. خروجی یک مقدار شمارشی نوشتار ساده است که مدل از فهرستی از مقادیر تعریفشده در طرحواره پاسخ ارائهشده انتخاب میکند.
برای انجام این تکلیف طبقهبندی ساختاریافته، باید درطول مقداردهی اولیه مدل،
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، روشهای موجود در این کیت توسعه نرمافزار توابع تعلیق هستند و باید از دامنه 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، روشهای جاریسازی در این کیت توسعه نرمافزار نوع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 بازخورد ارائه دهید