Theo mặc định, các mô hình Gemini sẽ trả về 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 (như JSON hoặc enum). Ví dụ: bạn có thể đang sử dụng phản hồi cho các tác vụ hạ nguồn khác yêu cầu một giản đồ dữ liệu đã thiết lập.
Để đảm bảo rằng kết quả do mô hình tạo ra luôn tuân thủ một giản đồ cụ thể, bạn có thể xác định một giản đồ, 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ừ kết quả của mô hình mà không cần xử lý hậu kỳ nhiều.
Sau đây là một số trường hợp sử dụng mẫu:
Đả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 đồ 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 thực hiện. 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 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 nhóm nhãn cụ thể (ví dụ: một nhóm enum cụ thể nhưpositivevànegative), thay vì các nhãn do mô hình tạo ra (có thể có mức độ biến thiên nhưgood,positive,negativehoặcbad).
Trang này mô tả cách tạo đầu ra có cấu trúc (như JSON và enum) trong trải nghiệm kết hợp cho ứng dụng web.
Chuyển đến kết quả JSON Chuyển đến kết quả enum
Cấu hình cho đầu ra có cấu trúc
Tính năng tạo kết quả có cấu trúc (như JSON và enum) được hỗ trợ cho hoạt động suy luận bằng cả mô hình được lưu trữ trên đám mây và mô hình trên thiết bị.
Chế độ suy luận kết hợp: Định cấu hình cả
inCloudParamsvàonDeviceParamsđể mô hình phản hồi bằng kết quả có cấu trúc, bất kể suy luận chạy trên đám mây hay trên thiết bị:Đối với mô hình trên thiết bị: Chỉ định
responseConstrainttrongonDeviceParamsbằng giản đồ được tạo bằng các phương thức trợ giúpSchemahoặc giản đồ JSON thuần tuý.Đối với các mô hình được lưu trữ trên đám mây: Chỉ định
responseMimeType(application/jsoncho JSON hoặctext/x.enumcho enum) vàresponseSchematronginCloudParams.
Chế độ suy luận không kết hợp: Chỉ sử dụng cấu hình phù hợp được mô tả ở trên.
Trước khi bắt đầu
|
Nhấp vào nhà cung cấp Gemini API của bạn để xem nội dung và mã dành riêng cho nhà cung cấp trên trang này. |
Đảm bảo rằng bạn đã hoàn tất hướng dẫn bắt đầu sử dụng để xây dựng trải nghiệm kết hợp.
Chuyển đến kết quả JSON Chuyển đến kết quả enum
Kết quả JSON
Các ví dụ sau đây điều chỉnh
ví dụ chung về kết quả JSON
để phù hợp với suy luận kết hợp (ví dụ: PREFER_ON_DEVICE).
Trong trường hợp của những ví dụ này, mô hình sẽ tạo danh sách hồ sơ nhân vật cho một câu chuyện giả tưởng, với các thuộc tính có cấu trúc như tên, tuổi, loài và phụ kiện không bắt buộc.
Bạn có thể xác định giản đồ phản hồi bằng một trong hai cách sau:
Các phương thức trợ giúp
Schemacủa Firebase (nên dùng): Sử dụng các phương thức trợ giúp (chẳng hạn nhưSchema.object()vàSchema.enumString()) để viết giản đồ ngắn gọn, súc tích ngay trong mã mà không cần thêm mã nguyên mẫu.Giản đồ JSON thuần tuý: Sử dụng đối tượng Giản đồ JSON chuẩn nếu bạn đã có định nghĩa giản đồ, chia sẻ giản đồ trên các nền tảng hoặc dịch vụ phụ trợ hoặc nhập giản đồ từ tệp JSON.
Ví dụ 1: Sử dụng các phương thức trợ giúp Schema của Firebase
Ví dụ này sử dụng các phương thức trợ giúp Schema (chẳng hạn như Schema.object, Schema.array, Schema.string và Schema.number) do SDK Firebase AI Logic cung cấp để xác định giản đồ đối tượng.
|
Trước khi thử mẫu này, hãy hoàn tất 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 của bạn. Trong phần đó, bạn cũng sẽ nhấp vào một nút cho nhà cung cấp 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. |
import { initializeApp } from "firebase/app";
import {
getAI,
getGenerativeModel,
GoogleAIBackend,
InferenceMode,
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() });
// Define a schema using the `Schema` helper methods.
// Optional properties are specified in optionalProperties.
const jsonSchema = Schema.object({
properties: {
characters: Schema.array({
items: Schema.object({
properties: {
name: Schema.string(),
age: Schema.number(),
species: Schema.string(),
accessory: Schema.string()
},
optionalProperties: ["accessory"]
})
})
}
});
// Create a GenerativeModel instance configured to use a hybrid inference mode (like PREFER_ON_DEVICE).
const model = getGenerativeModel(ai, {
mode: InferenceMode.INFERENCE_MODE,
// For cloud-hosted models, specify MIME type and response schema.
inCloudParams: {
model: "CLOUD_MODEL_NAME",
generationConfig: {
responseMimeType: "application/json",
responseSchema: jsonSchema
}
},
// For on-device models, pass the schema as the response constraint.
onDeviceParams: {
promptOptions: {
responseConstraint: jsonSchema
}
}
});
const prompt = "Create profiles for some characters for a fantasy story.";
// Generate the structured output.
const result = await model.generateContent(prompt);
// Access the generated JSON string conforming to the schema from response.text().
console.log(result.response.text());
// Parse the JSON string into a JavaScript object.
console.log(JSON.parse(result.response.text()));
Ví dụ 2: Sử dụng giản đồ JSON thuần tuý
Ví dụ này chỉ xác định giản đồ bằng JSON.
|
Trước khi thử mẫu này, hãy hoàn tất 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 của bạn. Trong phần đó, bạn cũng sẽ nhấp vào một nút cho nhà cung cấp 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. |
import { initializeApp } from "firebase/app";
import {
getAI,
getGenerativeModel,
GoogleAIBackend,
InferenceMode
} 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() });
// Define the schema as a plain JSON object.
// Properties are required by default unless omitted from the required array.
const jsonSchema = {
type: "object",
properties: {
characters: {
type: "array",
items: {
type: "object",
properties: {
name: {
type: "string",
nullable: false
},
age: {
type: "number",
nullable: false
},
species: {
type: "string",
nullable: false
},
accessory: {
type: "string",
nullable: true
}
},
nullable: false,
required: [
"name",
"age",
"species"
]
},
nullable: false
}
},
nullable: false,
required: [
"characters"
]
};
// Create a GenerativeModel instance configured to use a hybrid inference mode (like PREFER_ON_DEVICE).
const model = getGenerativeModel(ai, {
mode: InferenceMode.INFERENCE_MODE,
// For cloud-hosted models, specify MIME type and response schema.
inCloudParams: {
model: "CLOUD_MODEL_NAME",
generationConfig: {
responseMimeType: "application/json",
responseSchema: jsonSchema
}
},
// For on-device models, pass the schema as the response constraint.
onDeviceParams: {
promptOptions: {
responseConstraint: jsonSchema
}
}
});
const prompt = "Create profiles for some characters for a fantasy story.";
// Generate the structured output.
const result = await model.generateContent(prompt);
// Access the generated JSON string conforming to the schema from response.text().
console.log(result.response.text());
// Parse the JSON string into a JavaScript object.
console.log(JSON.parse(result.response.text()));
Kết quả enum
Các ví dụ sau đây điều chỉnh
ví dụ về kết quả enum chung
để phù hợp với suy luận kết hợp (ví dụ: PREFER_ON_DEVICE).
Trong trường hợp của những ví dụ này, mô hình sẽ phân loại nội dung mô tả phim bằng cách chọn một thể loại duy nhất trong danh sách các lựa chọn được phép (drama, comedy hoặc documentary).
Bạn có thể xác định giản đồ phản hồi bằng một trong hai cách sau:
Các phương thức trợ giúp
Schemacủa Firebase (nên dùng): Sử dụng các phương thức trợ giúp (chẳng hạn nhưSchema.object()vàSchema.enumString()) để viết giản đồ ngắn gọn, súc tích ngay trong mã mà không cần thêm mã nguyên mẫu.Giản đồ JSON thuần tuý: Sử dụng đối tượng Giản đồ JSON chuẩn nếu bạn đã có định nghĩa giản đồ, chia sẻ giản đồ trên các nền tảng hoặc dịch vụ phụ trợ hoặc nhập giản đồ từ tệp JSON.
Ví dụ 1: Sử dụng các phương thức trợ giúp Schema của Firebase
Ví dụ này sử dụng phương thức trợ giúp Schema.enumString do SDK Firebase AI Logic cung cấp để xác định các giá trị enum được phép.
|
Trước khi thử mẫu này, hãy hoàn tất 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 của bạn. Trong phần đó, bạn cũng sẽ nhấp vào một nút cho nhà cung cấp 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. |
import { initializeApp } from "firebase/app";
import {
getAI,
getGenerativeModel,
GoogleAIBackend,
InferenceMode,
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() });
// Define an enum schema using the `Schema` helper method with allowed string values.
const enumSchema = Schema.enumString({
enum: ["drama", "comedy", "documentary"]
});
// Create a GenerativeModel instance configured to use a hybrid inference mode (like PREFER_ON_DEVICE).
const model = getGenerativeModel(ai, {
mode: InferenceMode.INFERENCE_MODE,
// For cloud-hosted models, specify MIME type and response schema.
inCloudParams: {
model: "CLOUD_MODEL_NAME",
generationConfig: {
responseMimeType: "text/x.enum",
responseSchema: enumSchema
}
},
// For on-device models, pass the enum schema as the response constraint.
onDeviceParams: {
promptOptions: {
responseConstraint: enumSchema
}
}
});
const 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.`;
// Generate the structured enum output.
const result = await model.generateContent(prompt);
// Access the selected enum value string from response.text().
console.log(result.response.text());
Ví dụ 2: Sử dụng giản đồ JSON thuần tuý
Ví dụ này chỉ xác định giản đồ enum bằng JSON.
|
Trước khi thử mẫu này, hãy hoàn tất 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 của bạn. Trong phần đó, bạn cũng sẽ nhấp vào một nút cho nhà cung cấp 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. |
import { initializeApp } from "firebase/app";
import {
getAI,
getGenerativeModel,
GoogleAIBackend,
InferenceMode
} 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() });
// Define the enum schema as a plain JSON object.
const enumSchema = {
type: "string",
enum: ["drama", "comedy", "documentary"]
};
// Create a GenerativeModel instance configured to use a hybrid inference mode (like PREFER_ON_DEVICE).
const model = getGenerativeModel(ai, {
mode: InferenceMode.INFERENCE_MODE,
// For cloud-hosted models, specify MIME type and response schema.
inCloudParams: {
model: "CLOUD_MODEL_NAME",
generationConfig: {
responseMimeType: "text/x.enum",
responseSchema: enumSchema
}
},
// For on-device models, pass the enum schema as the response constraint.
onDeviceParams: {
promptOptions: {
responseConstraint: enumSchema
}
}
});
const 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.`;
// Generate the structured enum output.
const result = await model.generateContent(prompt);
// Access the selected enum value string from response.text().
console.log(result.response.text());
Gửi ý kiến phản hồi về trải nghiệm của bạn với Firebase AI Logic