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

Gemini API domyślnie zwraca odpowiedzi w postaci nieuporządkowanego tekstu. Jednak w niektórych przypadkach wymagany jest tekst uporządkowany, 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 dane wyjściowe wygenerowane przez model zawsze są zgodne z określonym schematem, możesz zdefiniować schemat odpowiedzi, który działa jak wzorzec odpowiedzi modelu. Następnie możesz bezpośrednio wyodrębnić dane z danych wyjściowych modelu przy mniejszym przetwarzaniu końcowym.

Oto przykłady:

  • Upewnij się, że odpowiedź modelu generuje prawidłowy kod JSON i jest zgodna z podanym schematem.
    Model może na przykład 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 dodanie do tekstu adnotacji z określonym zestawem etykiet (np. określonym zestawem typów wyliczeniowych, takich jak positive i negative), a nie etykiet, które model generuje (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. Skupia się na danych wejściowych zawierających tylko tekst, ale Gemini może też generować ustrukturyzowane odpowiedzi na żądania multimodalne, które zawierają obrazy, filmy i dźwięk.

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

Zanim zaczniesz

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

Jeśli nie masz jeszcze za sobą przewodnika dla początkujących, zapoznaj się z nim. Dowiesz się z niego, jak skonfigurować projekt w Firebase, połączyć aplikację z Firebase, dodać pakiet SDK, zainicjować usługę backendu dla wybranego dostawcy Gemini API i utworzyć instancję GenerativeModel.

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

Modele obsługujące tę funkcję

  • gemini-4-argon
  • gemini-3.8-flash (oraz starsze modele gemini-3.7-flash, gemini-3.6-flash i gemini-3.5-flash)
  • gemini-3.5-flash-lite (oraz starsze wersje gemini-3.1-flash-lite)

Tę funkcję obsługują też modele gemini-3.1-pro-preview i ogólnego zastosowania Gemini 2.5 (które zostały wycofane).

Krok 1. Zdefiniuj 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 prompta. Aby mieć pewność, że intencja jest jasna, zalecamy używanie przejrzystej struktury, jednoznacznych nazw pól, a w razie potrzeby nawet 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 ustrukturyzowanych 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 mógł obsłużyć Twoją prośbę, ale zignoruje to pole. Pamiętaj, że powyższa lista jest podzbiorem obiektu schematu OpenAPI 3.0.

  • Domyślnie w przypadku pakietów SDK Firebase AI Logic wszystkie pola są traktowane jako wymagane, chyba że określisz je jako opcjonalne w tablicy optionalProperties. W przypadku tych opcjonalnych pól model może je wypełnić lub pominąć. Pamiętaj, że jest to przeciwieństwo domyślnego działania tych 2 dostawców Gemini API, jeśli używasz ich pakietów SDK serwera lub bezpośrednio ich interfejsu API.

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 dostawcy Gemini API, aby wyświetlić na tej stronie treści dotyczące tego dostawcy.

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

Podczas tworzenia instancji GenerativeModel 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 z zakresu 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 wykorzystania i generowania ustrukturyzowanych danych wyjściowych.

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 dostawcy Gemini API, aby wyświetlić na tej stronie treści dotyczące tego dostawcy.

Poniższy przykład pokazuje, jak używać schematu odpowiedzi w zadaniu klasyfikacji. Model ma określić gatunek filmu na podstawie jego opisu. Dane wyjściowe to jedna wartość typu wyliczeniowego w postaci 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 responseMimeType (w tym przykładzie text/x.enum) oraz responseSchema, którego model ma używać.

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 z zakresu 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 móc wpływać na model i generować wyniki dostosowane do Twoich potrzeb.
  • Skonfiguruj parametry modelu, aby kontrolować sposób generowania odpowiedzi przez model, np. maksymalną liczbę tokenów wyjściowych, prawdopodobieństwo powtarzania tokenów wyjściowych itp.
  • Użyj ustawień bezpieczeństwa, aby dostosować prawdopodobieństwo otrzymywania odpowiedzi, które mogą być uznane za szkodliwe, w tym wypowiedzi szerzących nienawiść i treści o charakterze jednoznacznie seksualnym.
  • Ustaw instrukcje systemowe, aby sterować zachowaniem modelu. Ta funkcja działa jak wprowadzenie, które dodajesz, zanim model otrzyma dalsze instrukcje od użytkownika.


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