Gemini API domyślnie zwraca odpowiedzi w postaci 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:
Upewnij się, że odpowiedź modelu zawiera 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 wyliczeń, takim jakpositive
inegative
), a nie etykietami generowanymi przez model (które mogą mieć pewien stopień zmienności, np.good
,positive
,negative
lubbad
).
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ć strukturalne 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 dostawcę Gemini API, 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 znajdziesz informacje o tym, jak skonfigurować projekt 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, a nawet uzyskiwania wygenerowanego fragmentu kodu zalecamy używanie Google AI Studio.
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 Twojego prompta. Aby mieć pewność, że Twoje intencje są jasne, zalecamy stosowanie 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
: dane wyjściowe JSON zgodnie ze schematem odpowiedzi (przydatne w przypadku wymagań dotyczących danych wyjściowych o strukturze)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 może 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ą wymagane, chyba że w
optionalProperties
tablicy określisz je jako opcjonalne. W przypadku tych opcjonalnych pól model może je wypełnić lub pominąć. Pamiętaj, że jest to odwrotność domyślnego działania tych 2 dostawców, jeśli używasz ich pakietów SDK serwera lub interfejsu API bezpośrednio.Gemini API
Krok 2. Wygeneruj dane wyjściowe JSON za pomocą schematu odpowiedzi
Zanim wypróbujesz ten przykład, zapoznaj się z sekcją Zanim zaczniesz w tym przewodniku, aby skonfigurować projekt i aplikację. W tej sekcji klikniesz też przycisk wybranego dostawcyGemini API, aby na tej stronie wyświetlały się 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 model ma używać.
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
W przypadku Kotlina metody w tym pakiecie SDK są funkcjami zawieszającymi i muszą być wywoływane w zakresie Coroutine.
// 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
W przypadku Javy metody strumieniowania w tym pakiecie SDK zwracają typPublisher
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 */ "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.");
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, zapoznaj się z sekcją Zanim zaczniesz w tym przewodniku, aby skonfigurować projekt i aplikację. W tej sekcji klikniesz też przycisk wybranego dostawcyGemini API, aby na tej stronie wyświetlały się 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. Dane wyjściowe to 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 responseMimeType
(w tym przykładzie text/x.enum
) oraz responseSchema
, którego model ma używać.
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
W przypadku Kotlina metody w tym pakiecie SDK są funkcjami zawieszającymi i muszą być wywoływane w zakresie Coroutine.
// 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
W przypadku Javy metody strumieniowania w tym pakiecie SDK zwracają typPublisher
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 */ "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.");
Dowiedz się, jak wybrać model odpowiednie do Twojego przypadku użycia i aplikacji.
Inne opcje sterowania generowaniem 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ć, jak model ma generować odpowiedź. W przypadku modeli Gemini te parametry obejmują maksymalną liczbę tokenów wyjściowych, temperaturę, topK i topP. W przypadku Imagen obejmują one m.in. współczynnik proporcji, 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 sterować zachowaniem modelu. Ta funkcja działa jak wstęp, który dodajesz, zanim model otrzyma dalsze instrukcje od użytkownika.
Prześlij opinię o korzystaniu z usługi Firebase AI Logic