generować uporządkowane dane wyjściowe (np. w formacie JSON i enumeracji) za pomocą interfejsu Gemini API;

Zapytanie Gemini API domyślnie zwraca odpowiedzi jako tekst nieustrukturyzowany. Niektóre przypadki użycia wymagają jednak tekstu ustrukturyzowanego, np. w formacie JSON. Możesz na przykład używać odpowiedzi do innych zadań, które wymagają ustalonego schematu danych.

Aby wygenerowane przez model dane wyjściowe zawsze były zgodne z określonym schematem, możesz zdefiniować schemat odpowiedzi, który działa jak szablon odpowiedzi modelu. Dzięki temu możesz wyodrębnić dane bezpośrednio z wyjścia modelu, co wymaga mniej przetwarzania w pościepce.

Oto przykłady:

  • Upewnij się, że odpowiedź modelu zwraca prawidłowy format JSON i jest zgodna ze schematem dostarczonym przez Ciebie.
    Na przykład model może generować uporządkowane wpisy dotyczące przepisów, które zawsze zawierają nazwę przepisu, listę składników i sposób przygotowania. Dzięki temu łatwiej będzie Ci analizować te informacje i wyświetlać je w interfejsie aplikacji.

  • Ogranicz, jak model może reagować podczas zadań klasyfikacji.
    Możesz na przykład zlecić modelowi dodanie do tekstu określonych etykiet (np. określonego zbioru typów danych, takich jak positivenegative), a nie etykiet wygenerowanych przez model (które mogą się różnić, np. good, positive, negative lub bad).

Z tego przewodnika dowiesz się, jak wygenerować dane wyjściowe w formacie JSON, podając parametr responseSchema w wywołaniu funkcji generateContent. Model koncentruje się na danych wejściowych w postaci tekstu, ale może też generować uporządkowane odpowiedzi na żądania multimodalne, które zawierają obrazy, filmy i dźwięk.

W dolnej części tej strony znajdziesz więcej przykładów, np. jak generować wartości wyliczenia jako dane wyjściowe.

Zanim zaczniesz

Kliknij dostawcę Gemini API, aby wyświetlić na tej stronie treści i kod związane z tym dostawcą.

Jeśli jeszcze tego nie zrobisz, przeczytaj przewodnik dla początkujących, w którym znajdziesz instrukcje konfigurowania projektu Firebase, łączenia aplikacji z Firebase, dodawania pakietu SDK, inicjowania usługi backendowej wybranego dostawcy Gemini API oraz tworzenia instancji GenerativeModel.

Aby przetestować prompty i przeprowadzić ich iterację, a także uzyskać wygenerowany fragment kodu, zalecamy użycie Google AI Studio.

Krok 1. Zdefiniuj schemat odpowiedzi

Zdefiniuj schemat odpowiedzi, aby określić strukturę danych wyjściowych modelu, nazwy pól i oczekiwaną formę danych w każdym polu.

Podczas generowania odpowiedzi model używa nazwy pola i kontekstu z promptu. Aby mieć pewność, że Twój zamiar jest jasny, zalecamy użycie przejrzystej struktury, jednoznacznych nazw pól, a w razie potrzeby – opisów.

Uwagi dotyczące schematów odpowiedzi

Podczas pisania schematu odpowiedzi pamiętaj o tych kwestiach:

  • Rozmiar schematu odpowiedzi wlicza się do limitu tokenów wejściowych.

  • Funkcja schematu odpowiedzi obsługuje te typy MIME odpowiedzi:

    • application/json: dane wyjściowe w formacie JSON zgodnie ze schematem odpowiedzi (przydatne w przypadku wymagań dotyczących danych uporządkowanych).

    • text/x.enum: zwraca wartość enum zdefiniowaną w schemacie odpowiedzi (przydatne w zadaniach klasyfikacji).

  • Funkcja schematu odpowiedzi obsługuje te pola schematu:

    enum
    items
    maxItems
    nullable
    properties
    required

    Jeśli użyjesz pola, które nie jest obsługiwane, model może nadal obsłużyć Twoje żądanie, ale zignoruje to pole. Pamiętaj, że powyższa lista jest podzbiorem obiektu schematu OpenAPI 3.0.

  • Domyślnie w SDK Firebase AI Logic wszystkie pola są uważane za wymagane, chyba że w tablicy optionalProperties zostaną określone jako opcjonalne. W przypadku tych pól opcjonalnych model może wypełnić pola lub je pominąć. Pamiętaj, że jest to działanie przeciwne do domyślnego działania tych dwóchGemini API dostawców, jeśli używasz ich pakietów SDK serwera lub interfejsów API bezpośrednio.

Krok 2. Wygeneruj dane wyjściowe w formacie JSON, korzystając ze schematu odpowiedzi

Zanim użyjesz tego szablonu, zapoznaj się z sekcją Zanim zaczniesz tego przewodnika, aby skonfigurować projekt i aplikację.
W tej sekcji kliknij też przycisk wybranegoGemini API dostawcy, aby wyświetlić na tej stronie treści związane z tym dostawcą.

Poniższy przykład pokazuje, jak wygenerować uporządkowane dane wyjściowe w formacie JSON.

Podczas tworzenia instancji GenerativeModel określ odpowiednie responseMimeType (w tym przykładzie application/json) oraz responseSchema, których ma używać model.

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.0-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

W przypadku Kotlina metody w tym pakiecie SDK są funkcjami zawieszającymi i muszą być wywoływane z zakresu współbieżności.

// 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.0-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

W przypadku Javy metody strumieniowania w tym pakiecie SDK zwracają typ Publisherbiblioteki Reaktywne strumienie.

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

Dowiedz się, jak wybrać model odpowiedni do Twojego przypadku użycia i aplikacji.

Dodatkowe przykłady

Oto kilka dodatkowych przykładów użycia i generowania danych wyjściowych w formacie ustrukturyzowanym.

Generowanie wartości typu wyliczeniowego jako danych wyjściowych

Zanim użyjesz tego szablonu, zapoznaj się z sekcją Zanim zaczniesz tego przewodnika, aby skonfigurować projekt i aplikację.
W tej sekcji kliknij też przycisk wybranegoGemini API dostawcy, aby wyświetlić na tej stronie treści związane z tym dostawcą.

Ten przykład pokazuje, jak używać schematu odpowiedzi w przypadku zadania polegającego na klasyfikacji. Model ma rozpoznać gatunek filmu na podstawie jego opisu. Wyjściem jest jedna wartość typu enum w prostym tekście, którą model wybiera z listy wartości zdefiniowanych w dostarczonym schemacie odpowiedzi.

Aby wykonać to zadanie klasyfikacji uporządkowanej, musisz podczas inicjalizacji modelu podać odpowiednią funkcję responseMimeType (w tym przykładzie text/x.enum) oraz funkcję responseSchema, której ma używać model.

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.0-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

W przypadku Kotlina metody w tym pakiecie SDK są funkcjami zawieszającymi i muszą być wywoływane z zakresu współbieżności.

// 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.0-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

W przypadku Javy metody strumieniowania w tym pakiecie SDK zwracają typ Publisherbiblioteki Reaktywne strumienie.

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

Dowiedz się, jak wybrać model odpowiedni do Twojego przypadku użycia i aplikacji.

Inne opcje kontrolowania generowania treści

  • Dowiedz się więcej o projektowaniu promptów, aby móc wpływać na model w celu generowania wyników odpowiadających Twoim potrzebom.
  • Skonfiguruj parametry modelu, aby kontrolować, jak model wygeneruje odpowiedź. W przypadku modeli Gemini te parametry to maksymalna liczba tokenów wyjściowych, temperatura, topK i topP. W przypadku modeli Imagen obejmują one format obrazu, generowanie osób, znak wodny itp.
  • Użyj ustawień bezpieczeństwa, aby dostosować prawdopodobieństwo otrzymania odpowiedzi, które mogą być uznane za szkodliwe, w tym wypowiedzi szerzące nienawiść i treści o charakterze jednoznacznie seksualnym.
  • Ustaw instrukcje systemowe, aby kierować działaniem modelu. Ta funkcja jest jak wstęp, który dodajesz przed udostępnieniem modelu użytkownikowi.


Prześlij opinię o swoich wrażeniach związanych z usługą Firebase AI Logic