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

Gemini API domyślnie zwraca odpowiedzi w formie nieustrukturyzowanego tekstu. W niektórych przypadkach użycia wymagany jest jednak tekst strukturalny, np. JSON. Możesz na przykład używać odpowiedzi do innych zadań podrzędnych, które wymagają ustalonego schematu danych.

Aby mieć pewność, że wygenerowane dane wyjściowe modelu zawsze są zgodne z określonym schematem, możesz zdefiniować schemat odpowiedzi, który działa jak plan odpowiedzi modelu. Dzięki temu możesz bezpośrednio wyodrębniać dane z wyników modelu, co wymaga mniej przetwarzania końcowego.

Oto przykłady:

  • Sprawdź, czy odpowiedź modelu zawiera prawidłowy kod JSON i jest zgodna z podanym przez Ciebie schematem.
    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 kroki. Dzięki temu możesz łatwiej analizować i wyświetlać te informacje w interfejsie aplikacji.

  • Ograniczanie sposobu, w jaki model może odpowiadać podczas zadań klasyfikacji.
    Możesz na przykład poprosić model o oznaczanie tekstu określonym zestawem etykiet (np. określonym zestawem wyliczeń, takim jak positive i negative), a nie etykietami generowanymi przez model (które mogą mieć pewien stopień zmienności, np. good, positive, negative lub bad).

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

Na dole tej strony znajdziesz więcej przykładów, np. jak generować wartości wyliczeniowe jako dane wyjściowe.

Zanim zaczniesz

Kliknij Gemini API dostawcę, aby wyświetlić na tej stronie treści i kod dostawcy.

Jeśli jeszcze tego nie zrobisz, zapoznaj się z przewodnikiem dla początkujących, w którym opisujemy, jak skonfigurować projekt w Firebase, połączyć aplikację z Firebase, dodać pakiet SDK, zainicjować usługę backendu dla wybranego Gemini API dostawcy i utworzyć GenerativeModel instancję.

Do testowania i ulepszania promptów zalecamy używanie Google AI Studio.

Modele obsługujące tę funkcję

  • gemini-3.1-pro-preview
  • gemini-3.8-flash (oraz starsze wersje gemini-3.7-flash, gemini-3.6-flash i gemini-3.5-flash)
  • gemini-3.5-flash-lite (i starszy gemini-3.1-flash-lite)

Ogólne modele Gemini 2.5 obsługują tę funkcję, ale wszystkie zostały wycofane.

Krok 1. Określ schemat odpowiedzi

Zdefiniuj schemat odpowiedzi, aby określić strukturę danych wyjściowych modelu, nazwy pól i oczekiwany typ danych dla każdego pola.

Gdy model generuje odpowiedź, używa nazwy pola i kontekstu z Twojego prompta. Aby mieć pewność, że Twoje intencje są jasne, zalecamy używanie przejrzystej struktury, jednoznacznych nazw pól, a w razie potrzeby także 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: wygeneruj dane wyjściowe w formacie JSON zgodnie ze schematem odpowiedzi (przydatne w przypadku wymagań dotyczących strukturyzowanych danych wyjściowych).

    • text/x.enum: zwraca wartość typu wyliczeniowego zdefiniowaną w schemacie odpowiedzi (przydatne w przypadku zadań klasyfikacji).

  • Funkcja schematu odpowiedzi obsługuje te pola schematu:

    enum
    items
    maxItems
    nullable
    properties
    required

    Jeśli użyjesz nieobsługiwanego pola, model nadal będzie w stanie 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 przypadku Firebase AI Logic pakietów SDK wszystkie pola są uznawane za wymagane, chyba że w optionalProperties tablicy określisz je jako opcjonalne. W przypadku tych pól opcjonalnych model może je wypełnić lub pominąć. Pamiętaj, że jest to odwrotność działania domyślnego tych 2 Gemini APIdostawców, jeśli używasz ich pakietów SDK serwera lub interfejsu API bezpośrednio.

Krok 2. Wygeneruj dane wyjściowe JSON za pomocą schematu odpowiedzi

Zanim wypróbujesz ten przykład, wykonaj czynności opisane w sekcji Zanim zaczniesz tego przewodnika, aby skonfigurować projekt i aplikację.
W tej sekcji klikniesz też przycisk wybranego dostawcyGemini API, aby na tej stronie wyświetlać treści dotyczące tego dostawcy.

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

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

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

W przypadku języka Kotlin metody w tym pakiecie SDK są funkcjami zawieszania i muszą być wywoływane w zakresie współprogramu.

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

W przypadku Javy metody strumieniowania w tym pakiecie SDK zwracają typ Publisher z biblioteki 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.");

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

Dodatkowe przykłady

Oto kilka dodatkowych przykładów użycia i generowania danych strukturalnych.

Generowanie wartości typu wyliczeniowego jako danych wyjściowych

Zanim wypróbujesz ten przykład, wykonaj czynności opisane w sekcji Zanim zaczniesz tego przewodnika, aby skonfigurować projekt i aplikację.
W tej sekcji klikniesz też przycisk wybranego dostawcyGemini API, aby na tej stronie wyświetlać treści dotyczące tego dostawcy.

Poniższy przykład pokazuje, jak używać schematu odpowiedzi w przypadku zadania klasyfikacji. Model ma określić gatunek filmu na podstawie jego opisu. Wynikiem jest jedna wartość wyliczeniowa w formacie zwykłego tekstu, którą model wybiera z listy wartości zdefiniowanych w podanym schemacie odpowiedzi.

Aby wykonać to zadanie klasyfikacji strukturalnej, podczas inicjowania modelu musisz określić odpowiedni parametr responseMimeType (w tym przykładzie text/x.enum) oraz parametr responseSchema, którego ma używać model.

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

W przypadku języka Kotlin metody w tym pakiecie SDK są funkcjami zawieszania i muszą być wywoływane w zakresie współprogramu.

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

W przypadku Javy metody strumieniowania w tym pakiecie SDK zwracają typ Publisher z biblioteki 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.");

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

Inne opcje kontrolowania generowania treści

  • Dowiedz się więcej o projektowaniu promptów, aby wpływać na model i generować dane wyjściowe dostosowane do Twoich potrzeb.
  • Skonfiguruj parametry modelu, aby określić sposób generowania odpowiedzi przez model, np. maksymalną liczbę tokenów wyjściowych, prawdopodobieństwo powtórzenia tokenów wyjściowych 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 sterować zachowaniem modelu. Ta funkcja jest podobna do wprowadzenia, które dodajesz, zanim model zostanie poddany dalszym instrukcjom od użytkownika końcowego.


Prześlij opinię o korzystaniu z usługi Firebase AI Logic