Khi sử dụng mẫu lời nhắc của máy chủ, bạn có thể cập nhật các giá trị trong một mẫu nhất định mà không cần phát hành phiên bản mới của ứng dụng. Tuy nhiên, vì mọi thay đổi đối với mẫu sẽ được các yêu cầu từ ứng dụng của bạn sử dụng gần như ngay lập tức, nên bạn cần thận trọng khi thực hiện các thay đổi có thể làm hỏng ứng dụng hoặc gây ra những thay đổi không mong muốn về hành vi.
Vì vậy, nếu muốn thực hiện những thay đổi đáng kể hơn hoặc triển khai dần các thay đổi, thì bạn không nên thay đổi mẫu được dùng trong mã sản xuất.
Thay vào đó, bạn nên sử dụng Firebase Remote Config để kiểm soát giá trị của mã mẫu được dùng trong yêu cầu gửi đến mô hình.
Firebase Remote Config cho phép bạn cập nhật các giá trị tham số trong ứng dụng (chẳng hạn như mã mẫu) một cách linh hoạt và từ xa từ bảng điều khiểnFirebase mà không cần phát hành phiên bản mới của ứng dụng. Tính năng này cũng có các khả năng và hoạt động tích hợp được sắp xếp hợp lý để triển khai các thay đổi cũng như thử nghiệm A/B.
Hướng dẫn này mô tả cách triển khai Remote Config trong ứng dụng, cụ thể là để kiểm soát mã mẫu được dùng trong ứng dụng.
Bước 1: Đặt giá trị tham số trong bảng điều khiển Firebase
Tạo mẫu ứng dụng máy khách Remote Config và định cấu hình tham số template_id
cùng giá trị của tham số đó để tìm nạp và sử dụng trong ứng dụng.
Trong bảng điều khiển Firebase, hãy chuyển đến DevOps & Tương tác > Cấu hình từ xa.
Trong trình chọn Ứng dụng/Máy chủ ở đầu trang, hãy chọn Ứng dụng.
Bắt đầu mẫu ứng dụng bằng cách nhấp vào Tạo cấu hình (hoặc Thêm tham số nếu bạn đã từng sử dụng mẫu ứng dụng).
Xác định tham số
template_id:Tên thông số Mô tả Loại Giá trị mặc định template_idMã mẫu. Chuỗi my-first-template-v1-0-0Sau khi thêm tham số này, hãy nhấp vào Xuất bản các thay đổi. Nếu đây không phải là mẫu Remote Config mới, hãy xem lại các thay đổi rồi nhấp lại vào Xuất bản các thay đổi.
Bước 2: Thêm và khởi chạy Remote Config trong ứng dụng
Thêm thư viện Remote Config và thiết lập Remote Config trong ứng dụng.
Swift
Trong quá trình thiết lập Firebase AI Logic, bạn đã thêm SDK Firebase vào ứng dụng của mình, nhưng cũng cần thêm Remote Config.
Trong Xcode, khi dự án đang mở, hãy chuyển đến File (Tệp) > Add Package Dependencies (Thêm phần phụ thuộc của gói).
Chọn firebase-ios-sdk rồi nhấp vào Add package (Thêm gói).
Trong trình điều hướng Dự án, hãy chọn ứng dụng > Targets (Mục tiêu) > ứng dụng của bạn.
Trong thẻ General (Chung) , hãy di chuyển đến Frameworks, Libraries, and Embedded Content (Khung, Thư viện và Nội dung nhúng).
Nhấp vào + rồi chọn FirebaseRemoteConfig, sau đó nhấp vào Add (Thêm).
Thêm lệnh nhập
FirebaseRemoteConfigvào mã của bạn:import FirebaseRemoteConfigTrong lớp thích hợp cho ứng dụng của bạn, hãy khởi chạy Firebase và thêm Remote Config vào logic ứng dụng chính.
Tại đây, bạn sẽ thêm Remote Config và trình nghe theo thời gian thực Remote Config dưới dạng lệnh nhập để ứng dụng có thể tìm nạp các giá trị mới theo thời gian thực và thêm khoảng thời gian tìm nạp tối thiểu:
let remoteConfig = RemoteConfig.remoteConfig() let settings = RemoteConfigSettings() settings.minimumFetchInterval = 3600 remoteConfig.configSettings = settings
Kotlin
Thêm phần phụ thuộc Remote Config vào tệp Gradle của mô-đun (cấp ứng dụng) (thường là
app/build.gradle.ktshoặcapp/build.gradle):dependencies { implementation(platform("com.google.firebase:firebase-bom:34.13.0")) implementation("com.google.firebase:firebase-ai") implementation("com.google.firebase:firebase-config") // ... other dependencies }Thêm Remote Config vào logic ứng dụng chính. Tại đây, bạn sẽ khởi chạy Remote Config và thêm khoảng thời gian tìm nạp tối thiểu:
val remoteConfig: FirebaseRemoteConfig = Firebase.remoteConfig val configSettings = remoteConfigSettings { minimumFetchIntervalInSeconds = 3600 } remoteConfig.setConfigSettingsAsync(configSettings)
Java
Thêm phần phụ thuộc Remote Config vào tệp Gradle của mô-đun (cấp ứng dụng) (thường là
app/build.gradle.ktshoặcapp/build.gradle):dependencies { implementation(platform("com.google.firebase:firebase-bom:34.13.0")) implementation("com.google.firebase:firebase-ai") implementation("com.google.firebase:firebase-config") // ... other dependencies }Thêm Remote Config vào logic ứng dụng chính. Tại đây, bạn sẽ khởi chạy Remote Config và thêm khoảng thời gian tìm nạp tối thiểu:
FirebaseRemoteConfig mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance(); FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder() .setMinimumFetchIntervalInSeconds(3600) .build(); mFirebaseRemoteConfig.setConfigSettingsAsync(configSettings);
Web
Mở mã của bạn trong trình chỉnh sửa văn bản và nhập Remote Config:
import { getRemoteConfig } from 'firebase/remote-config';Trong hàm chính và sau khi ứng dụng Firebase được khởi chạy cho Firebase AI Logic SDK, hãy khởi chạy Remote Config:
// Initialize Remote Config and get a reference to the service const remoteConfig = getRemoteConfig(app);Đặt khoảng thời gian tìm nạp tối thiểu:
remoteConfig.settings.minimumFetchIntervalMillis = 3600000;
Dart
Trong thư mục dự án Flutter, hãy cài đặt và thêm Remote Config bằng lệnh sau:
flutter pub add firebase_remote_configMở
./lib/main.dartvà thêm lệnh nhập sau các lệnh nhập khác mà bạn đã thêm để hỗ trợ Firebase AI Logic:import 'package:firebase_vertexai/firebase_ai.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_remote_config/firebase_remote_config.dart';Thêm biến
_modelNamevào ứng dụng để bạn có thể sử dụng sau này:late final String _modelName; late final String _systemInstructions; late final String _prompt;Tải một phiên bản đối tượng Remote Config và đặt khoảng thời gian tìm nạp tối thiểu để cho phép làm mới thường xuyên. Hãy nhớ thêm phiên bản này sau khi Firebase được khởi chạy.
final remoteConfig = FirebaseRemoteConfig.instance; await remoteConfig.setConfigSettings(RemoteConfigSettings( fetchTimeout: const Duration(seconds: 3600), minimumFetchInterval: const Duration(seconds: 3600), ));
Unity
Thêm Remote Config vào dự án Unity theo các hướng dẫn này.
Tải một phiên bản đối tượng Remote Config và đặt khoảng thời gian tìm nạp tối thiểu để cho phép làm mới thường xuyên. Hãy nhớ thêm phiên bản này sau khi Firebase được khởi chạy.
var remoteConfig = FirebaseRemoteConfig.DefaultInstance; const int MillisecondsPerSecond = 1000; await remoteConfig.SetConfigSettingsAsync(new ConfigSettings() { FetchTimeoutInMilliseconds = 3600 * MillisecondsPerSecond, MinimumFetchIntervalInMilliseconds = 3600 * MillisecondsPerSecond });
Bước 3: Đặt giá trị tham số trong ứng dụng
Bạn nên đặt các giá trị tham số mặc định trong ứng dụng trong đối tượng Remote Config. Điều này đảm bảo rằng ứng dụng của bạn hoạt động như mong đợi ngay cả khi không thể tìm nạp các giá trị từ dịch vụ Remote Config.
Swift
Trong bảng điều khiển Firebase, hãy chuyển đến trang DevOps & Tương tác > Cấu hình từ xa > Tham số.
Mở
Menu , rồi chọn Download default values (Tải giá trị mặc định xuống).Khi được nhắc, hãy bật .plist for iOS, rồi nhấp vào Download file.
Lưu tệp trong thư mục ứng dụng của bạn.
Trong Xcode, hãy nhấp chuột phải vào ứng dụng của bạn rồi chọn Add Files (Thêm tệp)
Chọn remote_config_defaults.plist, rồi nhấp vào Add (Thêm).
Cập nhật mã ứng dụng của bạn để tham chiếu đến tệp mặc định:
// Set default values for Remote Config parameters. remoteConfig.setDefaults(fromPlist: "remote_config_defaults")
Kotlin
Trong bảng điều khiển Firebase, hãy chuyển đến trang DevOps & Tương tác > Cấu hình từ xa > Tham số.
Mở
Menu , rồi chọn Download default values (Tải giá trị mặc định xuống).Khi được nhắc, hãy bật .xml for Android, rồi nhấp vào Download file.
Lưu tệp trong thư mục tài nguyên XML của ứng dụng.
Cập nhật tệp hoạt động chính để thêm các giá trị mặc định sau
configSettingsmà bạn đã thêm trước đó:// Set default values for Remote Config parameters. remoteConfig.setDefaultsAsync(R.xml.remote_config_defaults)
Java
Trong bảng điều khiển Firebase, hãy chuyển đến trang DevOps & Tương tác > Cấu hình từ xa > Tham số.
Mở
Menu , rồi chọn Download default values (Tải giá trị mặc định xuống).Khi được nhắc, hãy bật .xml for Android, rồi nhấp vào Download file.
Lưu tệp trong thư mục tài nguyên XML của ứng dụng.
Cập nhật tệp hoạt động chính để thêm các giá trị mặc định sau
configSettingsmà bạn đã thêm trước đó:// Set default values for Remote Config parameters. mFirebaseRemoteConfig.setDefaultsAsync(R.xml.remote_config_defaults);
Web
Bạn có thể đặt giá trị mặc định cho tên mô hình trực tiếp trong mã của mình:
// Set default values for Remote Config parameters.
remoteConfig.defaultConfig = {
template_id: 'my-first-template-v1-0-0',
};
Dart
Bạn có thể đặt giá trị mặc định cho tên mô hình trực tiếp trong mã của mình:
// Set default values for Remote Config parameters.
remoteConfig.setDefaults(const {
"template_id": "my-first-template-v1-0-0"
});
Unity
Bạn có thể đặt giá trị mặc định cho tên mô hình trực tiếp trong mã của mình:
// Set default values for Remote Config parameters.
await remoteConfig.SetDefaultsAsync(
new System.Collections.Generic.Dictionary<string, object>() {
{ "template_id", "my-first-template-v1-0-0" }
}
);
Bước 4: Tìm nạp và kích hoạt giá trị
Sau khi đặt giá trị mặc định cho tên mô hình, hãy thêm nội dung sau để tìm nạp và kích hoạt các giá trị.
Swift
// Fetch and activate Remote Config values
remoteConfig.fetchAndActivate { status, error in
if let error = error {
print("Error fetching Remote Config: \(error.localizedDescription)")
}
}
Thao tác này sẽ cập nhật đối tượng Remote Config bất cứ khi nào một mẫu Remote Config mới được xuất bản.
Kotlin
// Fetch and activate Remote Config values
remoteConfig.fetchAndActivate()
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
val updated = task.result
Log.d(TAG, "Remote Config values fetched and activated: $updated")
} else {
Log.e(TAG, "Error fetching Remote Config", task.exception)
}
}
Java
// Fetch and activate Remote Config values
mFirebaseRemoteConfig.fetchAndActivate()
.addOnCompleteListener(this, new OnCompleteListener<Boolean>() {
@Override
public void onComplete(@NonNull Task<Boolean> task) {
if (task.isSuccessful()) {
boolean updated = task.getResult();
Log.d(TAG, "Config params updated: " + updated);
} else {
Log.e(TAG, "Error fetching Remote Config", task.exception)
}
}
});
Web
Thêm
getValuevàfetchAndActivatevào lệnh nhập:import { getValue, fetchAndActivate } from 'firebase/remote-config';Tìm mã nơi bạn chỉ định giá trị mặc định cho tên mô hình. Ngay sau khối mã đó, hãy thêm mã sau để tìm nạp và kích hoạt cấu hình, đồng thời gán giá trị đã tìm nạp cho hằng số
templateID.// Fetch and activate Remote Config. try { await fetchAndActivate(remoteConfig); } catch(err) { console.error('Remote Config fetch failed', err); } console.log('Remote Config fetched.'); // Assign Remote Config values. const templateID = getValue(remoteConfig, 'template_id').asString();
Dart
// Fetch and activate Remote Config.
remoteConfig.fetchAndActivate();
// Assign Remote Config values.
String? _templateID = remoteConfig.getString("template_id");
Unity
// Fetch and activate Remote Config values.
await remoteConfig.FetchAndActivateAsync();
Bước 5: Thêm trình nghe theo thời gian thực Remote Config
Thêm trình nghe theo thời gian thực Remote Config vào ứng dụng để đảm bảo rằng các thay đổi mà bạn thực hiện đối với mẫu Remote Config được truyền đến ứng dụng ngay khi được cập nhật.
Mã sau đây sẽ cập nhật đối tượng Remote Config bất cứ khi nào giá trị tham số thay đổi.
Swift
// Add real-time Remote Config
remoteConfig.addOnConfigUpdateListener { configUpdate, error in
guard let configUpdate = configUpdate, error == nil else {
print("Error listening for config updates: \(error?.localizedDescription ?? "No error available")")
return
}
print("Updated keys: \(configUpdate.updatedKeys)")
remoteConfig.activate { changed, error in
guard error == nil else {
print("Error activating config: \(error?.localizedDescription ?? "No error available")")
return
}
print("Activated config successfully")
}
}
Kotlin
Bạn cũng có thể định cấu hình một hành động bên trong quá trình kích hoạt addOnCompleteListener (không bắt buộc):
// Add a real-time Remote Config listener
remoteConfig.addOnConfigUpdateListener(object : ConfigUpdateListener {
override fun onUpdate(configUpdate : ConfigUpdate) {
Log.d(ContentValues.TAG, "Updated keys: " + configUpdate.updatedKeys);
remoteConfig.activate().addOnCompleteListener {
// Optionally, add an action to perform on update here.
}
}
override fun onError(error : FirebaseRemoteConfigException) {
Log.w(ContentValues.TAG, "Config update error with code: " + error.code, error)
}
}
Java
Bạn cũng có thể định cấu hình một hành động bên trong quá trình kích hoạt addOnCompleteListener (không bắt buộc):
// Add a real-time Remote Config listener
remoteConfig.addOnConfigUpdateListener(new ConfigUpdateListener() {
@Override
public void onUpdate(ConfigUpdate configUpdate) {
Log.d(ContentValues.TAG, "Updated keys: " + configUpdate.getUpdatedKeys());
remoteConfig.activate().addOnCompleteListener(new OnCompleteListener<Boolean>() {
@Override
public void onComplete(@NonNull Task<Boolean> task) {
// Optionally, add an action to perform on update here.
}
});
}
@Override
public void onError(FirebaseRemoteConfigException error) {
Log.w(ContentValues.TAG, "Config update error with code: " + error.getCode(), error);
}
});
Web
// Add a real-time Remote Config listener
onConfigUpdate(remoteConfig, {
next: (configUpdate) => {
console.log("Updated keys:", configUpdate.getUpdatedKeys());
if (configUpdate.getUpdatedKeys().has("welcome_message")) {
activate(remoteConfig).then(() => {
showWelcomeMessage();
});
}
},
error: (error) => {
console.log("Config update error:", error);
},
complete: () => {
console.log("Listening stopped.");
}
});
Dart
// Add a real-time Remote Config listener
remoteConfig.onConfigUpdated.listen((event) async {
await remoteConfig.activate();
});
Unity
// Add a real-time Remote Config listener to automatically update whenever
// a new template is published.
// Note: the parameters can be anonymous as they are unused.
remoteConfig.OnConfigUpdateListener += (_, _) => {
remoteConfig.ActivateAsync();
};
Bước 6: Cập nhật các yêu cầu Gemini API để sử dụng giá trị Remote Config
|
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. |
Bây giờ, khi Remote Config đã được định cấu hình đầy đủ, hãy cập nhật mã của bạn để thay thế các giá trị được mã hoá cứng bằng các giá trị lấy từ Remote Config.
Swift
import FirebaseAI
let templateID = remoteConfig.configValue(forKey: "template_id").stringValue
let model = FirebaseAI.firebaseAI(backend: .googleAI()).templateGenerativeModel()
let customerName = "Jane"
// When making the `generateContent` call, source the template ID value from Remote Config
let response = try await model.generateContent(
templateID: templateID,
// Provide the values for any input variables required by your template.
inputs: [
"customerName": customerName
]
)
// ...
Kotlin
// ...
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).templateGenerativeModel()
val customerName = "Jane"
// When making the `generateContent` call, source the template ID value from Remote Config
val response = model.generateContent(
remoteConfig.getString("template_id"),
// Provide the values for any input variables required by your template.
mapOf(
"customerName" to customerName
)
)
val text = response.text
println(text)
Java
// ...
TemplateGenerativeModel ai = FirebaseAI.getInstance()
.templateGenerativeModel(null /* Request Options */);
TemplateGenerativeModelFutures model = TemplateGenerativeModelFutures.from(ai);
String customerName = "Jane";
// When making the `generateContent` call, source the template ID value from Remote Config
Future<GenerateContentResponse> response = model.generateContent(
remoteConfig.getString("template_id"),
// Provide the values for any input variables required by your template.
mapOf("customerName", customerName)
);
addCallback(response,
new FutureCallback<GenerateContentResponse>() {
public void onSuccess(GenerateContentResponse result) {
System.out.println(result.getText());
}
public void onFailure(Throwable t) {
reportError(t);
}
}
executor);
// ...
Web
// ...
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
const model = getTemplateGenerativeModel(ai);
const templateID = getValue(remoteConfig, 'template_id').asString();
const customerName = 'Jane';
// When making the `generateContent` call, source the template ID value from Remote Config
const result = await model.generateContent(
templateID,
// Provide the values for any input variables required by your template
{
customerName: customerName,
}
);
// ...
Dart
// ...
final model = FirebaseAI.googleAI().templateGenerativeModel();
final templateID = remoteConfig.getString("template_id");
final customerName = 'Jane';
// When making the `generateContent` call, source the template ID value from Remote Config
var response = await model.generateContent(
templateID,
// Provide the values for any input variables required by your template
inputs: {
'customerName': customerName,
},
);
// ...
Unity
// ...
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());
var templateID = remoteConfig.GetValue("template_id").StringValue;
var model = ai.GetTemplateGenerativeModel();
var customerName = "Jane";
try
{
// When making the `generateContent` call, source the template ID value from Remote Config
var response = await model.GenerateContentAsync(
templateID,
// Provide the values for any input variables required by your template
new Dictionary<string, object>
{
{ "customerName", customerName },
}
);
Debug.Log($"Response Text: {response.Text}");
}
catch (Exception e)
{
Debug.LogError($"An error occurred: {e.Message}");
}
// ...
Bước 7: Chạy ứng dụng
Tạo bản dựng và chạy ứng dụng, đồng thời xác minh rằng ứng dụng hoạt động. Thay đổi cấu hình của bạn trên trang Remote Config trong bảng điều khiển Firebase, xuất bản các thay đổi và xác minh kết quả.
Các bước tiếp theo
Tìm hiểu thêm về cách triển khai các trường hợp sử dụng khác cho Remote Config và Firebase AI Logic.
Đối với ứng dụng và trò chơi di động:
Kiểm thử các thay đổi đối với mẫu bằng Remote Config và A/B Testing.
Phát hành dần các thay đổi bằng cách triển khai Remote Config (chỉ dành cho iOS+ và Android).
Sử dụng Remote Config tính năng cá nhân hoá để dùng công nghệ học máy nhằm xác định chế độ cài đặt phù hợp nhất cho từng người dùng (chỉ dành cho iOS+, Android và Unity).