Theo mặc định, Gemini API trả về câu trả lời dưới dạng văn bản không có cấu trúc. Tuy nhiên, một số trường hợp sử dụng yêu cầu văn bản có cấu trúc, chẳng hạn như JSON. Ví dụ: bạn có thể sử dụng câu trả lời cho các tác vụ khác ở hạ nguồn yêu cầu một giản đồ dữ liệu đã thiết lập.
Để đảm bảo rằng đầu ra do mô hình tạo luôn tuân thủ một giản đồ cụ thể, bạn có thể xác định giản đồ phản hồi hoạt động như một bản thiết kế cho các câu trả lời của mô hình. Sau đó, bạn có thể trực tiếp trích xuất dữ liệu từ đầu ra của mô hình mà không cần xử lý hậu kỳ nhiều.
Dưới đây là một số ví dụ:
Đảm bảo rằng câu trả lời của mô hình tạo ra JSON hợp lệ và tuân thủ giản đồ mà bạn cung cấp.
Ví dụ: mô hình có thể tạo các mục có cấu trúc cho công thức nấu ăn luôn bao gồm tên công thức, danh sách nguyên liệu và các bước. Sau đó, bạn có thể dễ dàng phân tích cú pháp và hiển thị thông tin này trong giao diện người dùng của ứng dụng.Hạn chế cách mô hình có thể phản hồi trong các tác vụ phân loại.
Ví dụ: bạn có thể yêu cầu mô hình chú thích văn bản bằng một tập hợp nhãn cụ thể (ví dụ: một tập hợp enum cụ thể nhưpositivevànegative), thay vì các nhãn mà mô hình tạo ra (có thể có mức độ biến đổi nhưgood,positive,negativehoặcbad).
Hướng dẫn này trình bày cách tạo đầu ra JSON bằng cách cung cấp responseSchema trong lệnh gọi đến generateContent. Hướng dẫn này tập trung vào dữ liệu đầu vào chỉ có văn bản, nhưng Gemini cũng có thể tạo câu trả lời có cấu trúc cho các yêu cầu đa phương thức bao gồm hình ảnh, video và âm thanh làm dữ liệu đầu vào.
Ở cuối trang này có thêm các ví dụ, chẳng hạn như cách tạo giá trị enum làm đầu ra.
Trước khi bắt đầu
|
Nhấp vào nhà cung định Gemini API để xem nội dung dành riêng cho nhà cung cấp và mã trên trang này. |
Nếu bạn chưa hoàn thành, hãy làm theo
hướng dẫn bắt đầu. Hướng dẫn này mô tả cách
thiết lập dự án Firebase, kết nối ứng dụng với Firebase, thêm SDK,
khởi chạy dịch vụ phụ trợ cho nhà cung cấp Gemini API mà bạn chọn và
tạo thực thể GenerativeModel.
Để thử nghiệm và lặp lại các câu lệnh, bạn nên sử dụng Google AI Studio.
Các mô hình hỗ trợ tính năng này
gemini-3.1-pro-previewgemini-3.5-flashgemini-3.1-flash-litegemini-3-pro-image(còn gọi là "Nano Banana Pro")gemini-2.5-progemini-2.5-flashgemini-2.5-flash-lite
Bước 1: Xác định giản đồ phản hồi
Xác định giản đồ phản hồi để chỉ định cấu trúc của đầu ra của mô hình, tên trường và loại dữ liệu dự kiến cho từng trường.
Khi tạo câu trả lời, mô hình sẽ sử dụng tên trường và ngữ cảnh từ câu lệnh của bạn. Để đảm bảo rằng ý định của bạn rõ ràng, bạn nên sử dụng cấu trúc rõ ràng, tên trường không mơ hồ và thậm chí cả nội dung mô tả nếu cần.
Những điều cần cân nhắc đối với giản đồ phản hồi
Hãy lưu ý những điều sau khi viết giản đồ phản hồi:
Kích thước của giản đồ phản hồi được tính vào giới hạn mã thông báo đầu vào.
Tính năng giản đồ phản hồi hỗ trợ các loại MIME phản hồi sau:
application/json: JSON đầu ra như được xác định trong giản đồ phản hồi (hữu ích cho các yêu cầu về đầu ra có cấu trúc)text/x.enum: xuất giá trị enum như được xác định trong giản đồ phản hồi (hữu ích cho các tác vụ phân loại)
Tính năng giản đồ phản hồi hỗ trợ các trường giản đồ sau:
enum
items
maxItems
nullable
properties
required
Nếu bạn sử dụng một trường không được hỗ trợ, mô hình vẫn có thể xử lý yêu cầu của bạn nhưng sẽ bỏ qua trường đó. Xin lưu ý rằng danh sách trên là một nhóm nhỏ của đối tượng giản đồ OpenAPI 3.0.
Theo mặc định, đối với Firebase AI Logic SDK, tất cả các trường đều được coi là bắt buộc trừ phi bạn chỉ định chúng là không bắt buộc trong
optionalPropertiesmảng. Đối với các trường không bắt buộc này, mô hình có thể điền hoặc bỏ qua các trường đó. Xin lưu ý rằng điều này ngược lại với hành vi mặc định của hai Gemini API nhà cung cấp nếu bạn sử dụng SDK máy chủ hoặc API của họ trực tiếp.
Bước 2: Tạo đầu ra JSON bằng giản đồ phản hồi
|
Trước khi thử mẫu này, hãy hoàn thành phần
Trước khi bắt đầu của hướng dẫn này
để thiết lập dự án và ứng dụng. Trong phần đó, bạn cũng sẽ nhấp vào một nút cho Gemini API mà bạn chọn để xem nội dung dành riêng cho nhà cung cấp trên trang này. |
Ví dụ sau đây cho biết cách tạo đầu ra JSON có cấu trúc.
Khi bạn tạo thực thể GenerativeModel, hãy chỉ định responseMimeType thích hợp (trong ví dụ này là application/json) cũng như responseSchema mà bạn muốn mô hình sử dụng.
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-3.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
Đối với Kotlin, các phương thức trong SDK này là các hàm tạm ngưng và cần được gọi từ phạm vi 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-3.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
Đối với Java, các phương thức truyền trực tuyến trong SDK này trả về loạiPublisher từ thư viện 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-3.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-3.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-3.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-3.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.");
Tìm hiểu cách chọn mô hình phù hợp với trường hợp sử dụng và ứng dụng của bạn.
Các ví dụ khác
Dưới đây là một số ví dụ khác về cách bạn có thể sử dụng và tạo đầu ra có cấu trúc.Tạo giá trị enum làm đầu ra
|
Trước khi thử mẫu này, hãy hoàn thành phần
Trước khi bắt đầu của hướng dẫn này
để thiết lập dự án và ứng dụng. Trong phần đó, bạn cũng sẽ nhấp vào một nút cho Gemini API mà bạn chọn để xem nội dung dành riêng cho nhà cung cấp trên trang này. |
Ví dụ sau đây cho biết cách sử dụng giản đồ phản hồi cho tác vụ phân loại. Mô hình được yêu cầu xác định thể loại của một bộ phim dựa trên nội dung mô tả. Đầu ra là một giá trị enum văn bản thuần tuý mà mô hình chọn trong danh sách các giá trị được xác định trong giản đồ phản hồi được cung cấp.
Để thực hiện tác vụ phân loại có cấu trúc này, bạn cần chỉ định trong quá trình khởi chạy mô hình responseMimeType thích hợp (trong ví dụ này là text/x.enum) cũng như responseSchema mà bạn muốn mô hình sử dụng.
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-3.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
Đối với Kotlin, các phương thức trong SDK này là các hàm tạm ngưng và cần được gọi từ phạm vi 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-3.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
Đối với Java, các phương thức truyền trực tuyến trong SDK này trả về loạiPublisher từ thư viện 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-3.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-3.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-3.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-3.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.");
Tìm hiểu cách chọn mô hình phù hợp với trường hợp sử dụng và ứng dụng của bạn.
Các lựa chọn khác để kiểm soát việc tạo nội dung
- Tìm hiểu thêm về thiết kế câu lệnh để bạn có thể tác động đến mô hình nhằm tạo ra đầu ra phù hợp với nhu cầu của mình.
- Định cấu hình các tham số của mô hình để kiểm soát cách mô hình tạo câu trả lời. Đối với Gemini mô hình, các tham số này bao gồm mã thông báo đầu ra tối đa, xác suất của các mã thông báo đầu ra lặp lại, v.v. Đối với Imagen mô hình, các tham số này bao gồm tỷ lệ khung hình, tạo người, đóng dấu bản quyền, v.v.
- Sử dụng chế độ cài đặt an toàn để điều chỉnh khả năng nhận được các câu trả lời có thể bị coi là gây hại, bao gồm cả lời nói hận thù và nội dung khiêu dâm.
- Đặt hướng dẫn hệ thống để điều chỉnh hành vi của mô hình. Tính năng này giống như phần mở đầu mà bạn thêm trước khi mô hình tiếp xúc với bất kỳ hướng dẫn nào khác của người dùng cuối.
Gửi ý kiến phản hồi về trải nghiệm của bạn với Firebase AI Logic