Gemini API'sini kullanarak yapılandırılmış çıkış (JSON ve enum gibi) oluşturma

Gemini API, varsayılan olarak yanıtları yapılandırılmamış metin şeklinde döndürür. Ancak bazı kullanım alanları, JSON gibi yapılandırılmış metin gerektirir. Örneğin, yanıtı, oluşturulmuş bir veri şeması gerektiren diğer aşağı akış görevlerinde kullanıyor olabilirsiniz.

Modelin oluşturduğu çıkışın her zaman belirli bir şemaya uymasını sağlamak için model yanıtları için bir plan gibi çalışan bir yanıt şeması tanımlayabilirsiniz. Ardından, modelin çıkışından verileri daha az son işlemeyle doğrudan çıkarabilirsiniz.

Aşağıda bazı örnekler verilmiştir:

  • Modelin yanıtının geçerli JSON oluşturduğundan 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.

  • Bir modelin sınıflandırma görevleri sırasında nasıl yanıt verebileceğini kısıtlama.
    Örneğin, modelin ürettiği etiketler (good, positive, negative veya bad gibi bir dereceye kadar değişkenlik gösterebilir) yerine, modelin metni belirli bir etiket grubuyla (örneğin, positive ve negative gibi belirli bir enum grubu) açıklamasını sağlayabilirsiniz.

Bu kılavuzda, generateContent çağrısında responseSchema sağlayarak nasıl JSON çıkışı oluşturacağınız gösterilmektedir. Yalnızca metin girişine odaklanır ancak Gemini, giriş olarak resim, video ve ses içeren çok formatlı isteklere yapılandırılmış yanıtlar da üretebilir.

Bu sayfanın en altında, enum değerlerini çıkış olarak oluşturma gibi daha fazla örnek verilmiştir.

Başlamadan önce

Bu sayfada sağlayıcıya özel içerikleri ve kodu görüntülemek için Gemini API sağlayıcınızı tıklayın.

Henüz yapmadıysanız başlangıç kılavuzunu tamamlayın. Bu kılavuzda Firebase projenizi ayarlama, uygulamanızı Firebase'e bağlama, SDK'yı ekleme, seçtiğiniz Gemini API sağlayıcısı için arka uç hizmetini başlatma ve GenerativeModel örneği oluşturma hakkında bilgi verilmektedir.

İstemlerinizi test etmek ve yinelemek, hatta oluşturulmuş bir kod snippet'i almak için Google AI Studio'ı kullanmanızı öneririz.

1. adım: Yanıt şeması tanımlayın

Modelin çıkışının 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 olduğundan emin olmak için net bir yapı, net 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ışı (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 çıkışı yapın (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 yine de 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ında, bir optionalProperties dizisinde isteğe bağlı olarak belirtmediğiniz sürece tüm alanlar zorunlu kabul edilir. Bu isteğe bağlı alanlar için model, alanları doldurabilir veya atlayabilir. Bu davranışın, sunucu SDK'larını veya API'lerini doğrudan kullanırsanız iki Gemini API sağlayıcının varsayılan davranışının tersi olduğunu unutmayın.

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ı için bir düğmeyi de 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 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

Kotlin'de 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-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

Java'da, bu SDK'daki akış yöntemleri Reactive Streams kitaplığından bir Publisher 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 */ "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);

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-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.");

Kullanım alanınıza ve uygulamanıza uygun bir model seçmeyi öğrenin.

Diğer örnekler

Yapılandırılmış çıkışı nasıl kullanıp oluşturabileceğinize dair bazı ek örnekleri burada bulabilirsiniz.

Çıkış olarak enum değerleri 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ı için bir düğmeyi de 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, bir filmin açıklamasını temel alarak türünü belirlemesi istenir. Çıkış, modelin sağlanan yanıt şemasında tanımlanan değerler listesinden seçtiği bir düz metin numaralandırma 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 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

Kotlin'de 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-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

Java'da, bu SDK'daki akış yöntemleri Reactive Streams kitaplığından bir Publisher 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 */ "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);

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-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.");

Kullanım alanınıza ve uygulamanıza uygun bir model seçmeyi öğrenin.

İçerik oluşturmayı kontrol etme ile ilgili diğer seçenekler

  • İstem tasarımı hakkında daha fazla bilgi edinin böylece modeli, ihtiyaçlarınıza özel çıkışlar oluşturması için etkileyebilirsiniz.
  • Modelin nasıl yanıt oluşturacağını kontrol etmek için model parametrelerini yapılandırın. Gemini modellerinde bu parametreler arasında maksimum çıkış jetonları, sıcaklık, topK ve topP yer alır. Imagen modellerinde en-boy oranı, kişi oluşturma, filigran vb. yer alır.
  • Nefret söylemi ve müstehcen içerik gibi 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ı ayarlayın. Bu özellik, modelin son kullanıcının başka talimatlarına maruz kalmadan önce eklediğiniz bir giriş gibidir.


Firebase AI Logic ile ilgili deneyiminiz hakkında geri bildirim verme