Gemini API, yanıtları varsayılan olarak yapılandırılmamış metin biçiminde döndürür. Ancak bazı kullanım alanları, JSON gibi yapılandırılmış metinler gerektirir. Örneğin, yanıtı, belirli bir veri şeması gerektiren diğer alt görevler için kullanıyor olabilirsiniz.
Modelin ürettiği çıktının her zaman belirli bir şemaya uymasını sağlamak için model yanıtları için şablon görevi gören bir yanıt şeması tanımlayabilirsiniz. Ardından, daha az son işlemle modelin çıkışından doğrudan veri ayıklayabilirsiniz.
Aşağıda bazı örnekler verilmiştir:
Modelin yanıtının geçerli bir JSON ürettiğinden ve sağladığınız şemaya uygun olduğundan emin olun.
Örneğin, model her zaman tarif adını, malzeme listesini ve adımları içeren tarifler için yapılandırılmış girişler oluşturabilir. Ardından, bu bilgileri uygulamanızın kullanıcı arayüzünde daha kolay ayrıştırıp görüntüleyebilirsiniz.Sınıflandırma görevleri sırasında modelin nasıl yanıt verebileceğini kısıtlama
Örneğin, modelin ürettiği etiketler (good,positive,negativeveyabadgibi değişkenlik gösterebilir) yerine, modelin metni belirli bir etiket grubuyla (ör.positivevenegativegibi belirli bir enum grubu) etiketlemesini sağlayabilirsiniz.
Bu kılavuzda, generateContent çağrısında responseSchema sağlayarak JSON çıkışını nasıl oluşturacağınız gösterilmektedir. Bu laboratuvarda yalnızca metin girişine odaklanılsa da Gemini, giriş olarak resim, video ve ses içeren çok formatlı isteklere de yapılandırılmış yanıtlar üretebilir.
Bu sayfanın alt kısmında, enum değerlerini çıkış olarak oluşturma gibi daha fazla örnek bulabilirsiniz.
Başlamadan önce
|
Bu sayfada sağlayıcıya özel içerikleri ve kodları görüntülemek için Gemini API sağlayıcınızı tıklayın. |
Henüz yapmadıysanız başlangıç kılavuzundaki adımları tamamlayın. Bu kılavuzda Firebase projenizi nasıl oluşturacağınız, uygulamanızı Firebase'e nasıl bağlayacağınız, SDK'yı nasıl ekleyeceğiniz, seçtiğiniz Gemini API sağlayıcı için arka uç hizmetini nasıl başlatacağınız ve bir GenerativeModel örneği nasıl oluşturacağınız açıklanmaktadır.
İstemlerinizi test etmek ve yinelemek için Google AI Studio kullanmanızı öneririz.
Bu özelliği destekleyen modeller
gemini-4-argongemini-3.8-flashgemini-3.5-flash-lite(ve daha eskigemini-3.1-flash-lite)
Eski genel kullanımlı Gemini 3.x Flash ve Gemini 2.5 modelleri bu özelliği destekler ancak yaklaşan kapatma tarihleri ve/veya daha yeni modellere otomatik yönlendirme nedeniyle artık kullanılması önerilmez.
1. adım: Yanıt şeması tanımlayın
Modelin çıkış yapısını, alan adlarını ve her alan için beklenen veri türünü belirtmek üzere bir yanıt şeması tanımlayın.
Model, yanıtını oluştururken isteminizdeki alan adını ve bağlamı kullanır. Amacınızın net bir şekilde anlaşılması için net bir yapı, belirsiz olmayan alan adları ve gerektiğinde açıklamalar kullanmanızı öneririz.
Yanıt şemalarıyla ilgili dikkat edilmesi gereken noktalar
Yanıt şemanızı yazarken aşağıdakileri göz önünde bulundurun:
Yanıt şemasının boyutu, giriş jetonu sınırına dahil edilir.
Yanıt şeması özelliği, aşağıdaki yanıt MIME türlerini destekler:
application/json: Yanıt şemasında tanımlandığı şekilde JSON çıkışı oluşturur. (Yapılandırılmış çıkış gereksinimleri için kullanışlıdır.)text/x.enum: Yanıt şemasında tanımlandığı şekilde bir enum değeri döndürür (sınıflandırma görevleri için kullanışlıdır).
Yanıt şeması özelliği aşağıdaki şema alanlarını destekler:
enum
items
maxItems
nullable
properties
required
Desteklenmeyen bir alan kullanırsanız model isteğinizi işleyebilir ancak alanı yoksayar. Yukarıdaki listenin OpenAPI 3.0 şema nesnesinin bir alt kümesi olduğunu unutmayın.
Varsayılan olarak, Firebase AI Logic SDK'ları için tüm alanlar, bir
optionalPropertiesdizisinde isteğe bağlı olarak belirtmediğiniz sürece zorunlu olarak kabul edilir. Model, bu isteğe bağlı alanları doldurabilir veya atlayabilir. Sunucu SDK'larını veya API'lerini doğrudan kullanırsanız bu durumun iki sağlayıcının varsayılan davranışının tam tersi olduğunu unutmayın.Gemini API
2. adım: Yanıt şemanızı kullanarak JSON çıkışı oluşturun
|
Bu örneği denemeden önce projenizi ve uygulamanızı ayarlamak için bu kılavuzun Başlamadan önce bölümünü tamamlayın. Bu bölümde, seçtiğiniz Gemini API sağlayıcıya ait düğmeyi tıklayarak bu sayfada sağlayıcıya özel içerikleri görebilirsiniz. |
Aşağıdaki örnekte, yapılandırılmış JSON çıkışının nasıl oluşturulacağı gösterilmektedir.
GenerativeModel örneğini oluştururken uygun responseMimeType (bu örnekte application/json) ve modelin kullanmasını istediğiniz responseSchema değerini belirtin.
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 için bu SDK'daki yöntemler askıya alma işlevleridir ve Coroutine kapsamından çağrılmaları gerekir.
// 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 için bu SDK'daki akış yöntemleri, Reactive Streams kitaplığından birPublisher türü döndürür.
// 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.");
Kullanım alanınıza ve uygulamanıza uygun bir model seçmeyi öğrenin.
Diğer örnekler
Yapılandırılmış çıkışları nasıl kullanabileceğiniz ve oluşturabileceğinizle ilgili birkaç örnek daha aşağıda verilmiştir.Enum değerlerini çıkış olarak oluşturma
|
Bu örneği denemeden önce projenizi ve uygulamanızı ayarlamak için bu kılavuzun Başlamadan önce bölümünü tamamlayın. Bu bölümde, seçtiğiniz Gemini API sağlayıcıya ait düğmeyi tıklayarak bu sayfada sağlayıcıya özel içerikleri görebilirsiniz. |
Aşağıdaki örnekte, sınıflandırma görevi için yanıt şemasının nasıl kullanılacağı gösterilmektedir. Modelden, açıklamasına göre bir filmin türünü belirlemesi istenir. Çıkış, modelin sağlanan yanıt şemasında tanımlanan değerler listesinden seçtiği tek bir düz metin enum değeridir.
Bu yapılandırılmış sınıflandırma görevini gerçekleştirmek için model başlatma sırasında uygun responseMimeType (bu örnekte text/x.enum) ve modelin kullanmasını istediğiniz responseSchema değerini belirtmeniz gerekir.
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 için bu SDK'daki yöntemler askıya alma işlevleridir ve Coroutine kapsamından çağrılmaları gerekir.
// 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 için bu SDK'daki akış yöntemleri, Reactive Streams kitaplığından birPublisher türü döndürür.
// 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.");
Kullanım alanınıza ve uygulamanıza uygun bir model seçmeyi öğrenin.
İçerik üretimini kontrol etmek için diğer seçenekler
- Modeli, ihtiyaçlarınıza özel çıktılar üretecek şekilde etkilemek için istem tasarımı hakkında daha fazla bilgi edinin.
- Modelin nasıl yanıt üreteceğini kontrol etmek için model parametrelerini yapılandırın (ör. maksimum çıkış jetonu sayısı, tekrarlanan çıkış jetonlarının olasılığı vb.).
- Nefret söylemi ve müstehcen içerik de dahil olmak üzere zararlı olarak kabul edilebilecek yanıtlar alma olasılığını ayarlamak için güvenlik ayarlarını kullanın.
- Modelin davranışını yönlendirmek için sistem talimatları belirleyin. Bu özellik, model son kullanıcıdan başka talimatlar almadan önce eklediğiniz bir ön talimat gibidir.
Firebase AI Logic ile ilgili deneyiminiz hakkında geri bildirimde bulunun