Theo mặc định, Gemini API trả về các phản hồ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 phản hồi cho các tác vụ hạ nguồn khác cần có giản đồ dữ liệu đã thiết lập.
Để đảm bảo rằng đầu ra được tạo của mô hình luôn tuân thủ một giản đồ cụ thể, bạn có thể xác định một giản đồ phản hồi. Giản đồ này hoạt động như một bản thiết kế cho các phản hồ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 với ít quá trình xử lý sau hơn.
Sau đây là một số ví dụ:
Đảm bảo rằng phản hồ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 nhập có cấu trúc cho các 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.Giới hạn cách mô hình có thể phản hồi trong các nhiệm 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ưpositive
vànegative
), thay vì nhãn mà mô hình tạo ra (có thể có mức độ biến đổi nhưgood
,positive
,negative
hoặcbad
).
Hướng dẫn này cho bạn biết cách tạo đầu ra JSON bằng cách cung cấp responseSchema
trong lệnh gọi đến generateContent
. Công cụ này tập trung vào dữ liệu đầu vào chỉ văn bản, nhưng Gemini cũng có thể tạo phản hồ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 là các ví dụ khác, chẳng hạn như cách tạo giá trị enum dưới dạng đầu ra. Để xem thêm ví dụ về cách tạo đầu ra có cấu trúc, hãy xem danh sách Ví dụ về giản đồ và phản hồi của mô hình trong tài liệu về Google Cloud.
Trước khi bắt đầu
Nếu bạn chưa hoàn tất, hãy hoàn thành hướng dẫn bắt đầu sử dụng. 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ụ Vertex AI và tạo một thực thể GenerativeModel
.
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 mỗi trường.
Khi tạo phản hồ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. Để ý đị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 rõ ràng và thậm chí là 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 đượ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 một giá trị enum như được xác định trong giản đồ phản hồi (hữu ích cho các nhiệm 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 tập hợp con của đối tượng giản đồ OpenAPI 3.0 (xem Tham chiếu giản đồ Vertex AI).
Theo mặc định, đối với SDK Vertex AI in Firebase, tất cả các trường đều được coi là bắt buộc, trừ phi bạn chỉ định các trường đó là không bắt buộc trong mảng
optionalProperties
. Đối với các trường không bắt buộc này, mô hình có thể điền sẵn các trường hoặc bỏ qua các trường đó.Xin lưu ý rằng điều này trái ngược với hành vi mặc định của Gemini API in Vertex AI.
Bước 2: Gửi lời nhắc có giản đồ phản hồi để tạo JSON
Ví dụ sau đây cho thấy cách tạo đầu ra JSON có cấu trúc.
Để tạo đầu ra có cấu trúc, 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à application/json
) cũng như responseSchema
mà bạn muốn mô hình sử dụng.
Tất cả các mô hình Gemini đều hỗ trợ việc sử dụng responseSchema
(ngoại trừ các mô hình Gemini 1.0).
Swift
import FirebaseVertexAI
// 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 Vertex AI service and the generative model.
let model = VertexAI.vertexAI().generativeModel(
modelName: "gemini-2.0-flash",
// In the generation config, set the `responseMimeType` to `application/json`
// and pass the JSON schema object into `responseSchema`.
generationConfig: GenerationConfig(
responseMIMEType: "application/json",
responseSchema: jsonSchema
)
)
let prompt = "For use in a children's card game, generate 10 animal-based characters."
let response = try await model.generateContent(prompt)
print(response.text ?? "No text in response.")
Kotlin
Đối với Kotlin, các phương thức trong SDK này là 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 Vertex AI service and the generative model.
val generativeModel = Firebase.vertexAI.generativeModel(
modelName = "gemini-2.0-flash",
// In the generation config, set the `responseMimeType` to `application/json`
// and pass the JSON schema object into `responseSchema`.
generationConfig = generationConfig {
responseMimeType = "application/json"
responseSchema = jsonSchema
})
val prompt = "For use in a children's card game, generate 10 animal-based characters."
val response = generativeModel.generateContent(prompt)
print(response.text)
Java
Đối với Java, các phương thức truyền trực tuyến trong SDK này trả về một loạiPublisher
từ thư viện Luồng phản ứng.
// 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 Vertex AI service and the generative model.
GenerativeModel gm = FirebaseVertexAI.getInstance().generativeModel(
/* modelName */ "gemini-2.0-flash",
/* generationConfig */ generationConfig);
GenerativeModelFutures model = GenerativeModelFutures.from(gm);
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 { getVertexAI, getGenerativeModel, Schema } from "firebase/vertexai";
// 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 Vertex AI service.
const vertexAI = getVertexAI(firebaseApp);
// 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"],
}),
}),
}
});
// Initialize the generative model.
const model = getGenerativeModel(vertexAI, {
model: "gemini-2.0-flash",
// In the generation config, set the `responseMimeType` to `application/json`
// and pass the JSON schema object into `responseSchema`.
generationConfig: {
responseMimeType: "application/json",
responseSchema: jsonSchema
},
});
let prompt = "For use in a children's card game, generate 10 animal-based characters.";
let result = await model.generateContent(prompt)
console.log(result.response.text());
Dart
import 'package:firebase_vertexai/firebase_vertexai.dart';
import 'package:firebase_core/firebase_core.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'],
);
await Firebase.initializeApp();
// Initialize the Vertex AI service and the generative model.
final model =
FirebaseVertexAI.instance.generativeModel(
model: 'gemini-2.0-flash',
// In the generation config, set the `responseMimeType` to `application/json`
// and pass the JSON schema object into `responseSchema`.
generationConfig: GenerationConfig(
responseMimeType: 'application/json', responseSchema: jsonSchema));
final prompt = "For use in a children's card game, generate 10 animal-based characters.";
final response = await model.generateContent([Content.text(prompt)]);
print(response.text);
Tìm hiểu cách chọn một mô hình và tuỳ ý chọn một vị trí 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
Để xem thêm ví dụ về cách sử dụng và tạo đầu ra có cấu trúc, hãy xem danh sách Ví dụ về giản đồ và phản hồi mô hình trong tài liệu về Google Cloud.
Tạo giá trị enum dưới dạng đầu ra
Ví dụ sau đây cho thấy cách sử dụng giản đồ phản hồi cho một 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ả của bộ phim đó. Kết quả 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 nhiệm vụ phân loại có cấu trúc này, bạn cần chỉ đị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 trong quá trình khởi chạy mô hình.
Swift
import FirebaseVertexAI
// 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 Vertex AI service and the generative model.
let model = VertexAI.vertexAI().generativeModel(
modelName: "gemini-2.0-flash",
// In the generation config, set the `responseMimeType` to `text/x.enum`
// and pass the enum schema object into `responseSchema`.
generationConfig: GenerationConfig(
responseMIMEType: "text/x.enum",
responseSchema: enumSchema
)
)
let prompt = """
The film aims to educate and inform viewers about real-life subjects, events, or people.
It offers a factual record of a particular topic by combining interviews, historical footage,
and narration. The primary purpose of a film is to present information and provide insights
into various aspects of reality.
"""
let response = try await model.generateContent(prompt)
print(response.text ?? "No text in response.")
Kotlin
Đối với Kotlin, các phương thức trong SDK này là 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 Vertex AI service and the generative model.
val generativeModel = Firebase.vertexAI.generativeModel(
modelName = "gemini-2.0-flash",
// In the generation config, set the `responseMimeType` to `text/x.enum`
// and pass the enum schema object into `responseSchema`.
generationConfig = generationConfig {
responseMimeType = "text/x.enum"
responseSchema = enumSchema
})
val prompt = """
The film aims to educate and inform viewers about real-life subjects, events, or people.
It offers a factual record of a particular topic by combining interviews, historical footage,
and narration. The primary purpose of a film is to present information and provide insights
into various aspects of reality.
"""
val response = generativeModel.generateContent(prompt)
print(response.text)
Java
Đối với Java, các phương thức truyền trực tuyến trong SDK này trả về một loạiPublisher
từ thư viện Luồng phản ứng.
// 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 Vertex AI service and the generative model.
GenerativeModel gm = FirebaseVertexAI.getInstance().generativeModel(
/* modelName */ "gemini-2.0-flash",
/* generationConfig */ generationConfig);
GenerativeModelFutures model = GenerativeModelFutures.from(gm);
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 { getVertexAI, getGenerativeModel, Schema } from "firebase/vertexai";
// 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 Vertex AI service.
const vertexAI = getVertexAI(firebaseApp);
// 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"],
});
// Initialize the generative model.
const model = getGenerativeModel(vertexAI, {
model: "gemini-2.0-flash",
// In the generation config, set the `responseMimeType` to `text/x.enum`
// and pass the JSON schema object into `responseSchema`.
generationConfig: {
responseMimeType: "text/x.enum",
responseSchema: enumSchema,
},
});
let prompt = `The film aims to educate and inform viewers about real-life
subjects, events, or people. It offers a factual record of a particular topic
by combining interviews, historical footage, and narration. The primary purpose
of a film is to present information and provide insights into various aspects
of reality.`;
let result = await model.generateContent(prompt);
console.log(result.response.text());
Dart
import 'package:firebase_vertexai/firebase_vertexai.dart';
import 'package:firebase_core/firebase_core.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']);
await Firebase.initializeApp();
// Initialize the Vertex AI service and the generative model.
final model =
FirebaseVertexAI.instance.generativeModel(
model: 'gemini-2.0-flash',
// In the generation config, set the `responseMimeType` to `text/x.enum`
// and pass the enum schema object into `responseSchema`.
generationConfig: GenerationConfig(
responseMimeType: 'text/x.enum', responseSchema: enumSchema));
final prompt = """
The film aims to educate and inform viewers about real-life subjects, events, or people.
It offers a factual record of a particular topic by combining interviews, historical footage,
and narration. The primary purpose of a film is to present information and provide insights
into various aspects of reality.
""";
final response = await model.generateContent([Content.text(prompt)]);
print(response.text);
Tìm hiểu cách chọn một mô hình và tuỳ ý chọn một vị trí 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 để có thể tác động đến mô hình nhằm tạo ra kết quả phù hợp với nhu cầu của bạn.
- Định cấu hình các thông số mô hình để kiểm soát cách mô hình tạo ra phản hồi. Đối với các mô hình Gemini, các tham số này bao gồm mã thông báo đầu ra tối đa, nhiệt độ, topK và topP. Đối với các mô hình Imagen, các tham số này bao gồm tỷ lệ khung hình, tạo người, tạo hình mờ, v.v.
- Sử dụng chế độ cài đặt an toàn để điều chỉnh khả năng nhận được những 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 hướng hành vi của mô hình. Tính năng này giống như một "lời mở đầu" mà bạn thêm vào trước khi mô hình hiển thị 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 Vertex AI in Firebase