使用伺服器提示詞範本時,您可以在特定範本中更新值,不必發布新版應用程式。不過,由於應用程式的請求幾乎會立即使用範本的任何變更,因此您必須謹慎進行變更,以免導致應用程式中斷或行為發生非預期的變化。
因此,如要進行重大變更或逐步推出變更,請勿變更正式版程式碼中使用的範本。
建議您改用 Firebase Remote Config 控制要求中使用的範本 ID 值。
Firebase Remote Config 可讓您從 Firebase 管理中心動態更新應用程式中的參數值 (例如範本 ID),不必發布新版應用程式。此外,這項功能也簡化了推出變更和進行 A/B 測試的程序,並提供相關整合。
本指南說明如何在應用程式中實作 Remote Config,特別是控管應用程式中使用的範本 ID。
步驟 1:在 Firebase 控制台中設定參數值
建立 Remote Config 用戶端範本,並設定 template_id 參數及其值,以便在應用程式中擷取及使用。
在 Firebase 控制台中開啟 Firebase 專案。接著,從導覽選單中展開「執行」,然後選取 Remote Config。
確認已從頁面頂端的「Client/Server」(用戶端/伺服器) 選取器中選取「Client」(用戶端)。
按一下「建立設定」(或「新增參數」,如果您先前使用過用戶端範本),即可開始建立用戶端範本。
定義
template_id參數:參數名稱 說明 類型 預設值 template_id範本 ID。 字串 my-first-template-v1-0-0新增這個參數後,請按一下「發布變更」。如果這不是新範本,請查看變更並再次按一下「發布變更」。Remote Config
步驟 2:在應用程式中新增及初始化 Remote Config
在應用程式中新增 Remote Config 程式庫,並設定 Remote Config。
Swift
在Firebase AI Logic設定過程中,您已將 Firebase SDK 新增至應用程式,但還需要新增 Remote Config。
在 Xcode 中開啟專案,然後依序前往「File」>「Add Package Dependencies」。
選取「firebase-ios-sdk」,然後點選「Add package」。
在「Project Navigator」中,依序選取應用程式 >「Targets」 > 應用程式。
在「一般」分頁中,捲動至「架構、程式庫和內嵌內容」。
按一下「+」,然後選擇「FirebaseRemoteConfig」,再按一下「新增」。
在程式碼中新增
FirebaseRemoteConfig匯入項目:import FirebaseRemoteConfig在應用程式的適當類別中,初始化 Firebase 並將 Remote Config 加入主要應用程式邏輯。
您可以在這裡加入 Remote Config 和Remote Config 即時監聽器做為匯入項目,讓應用程式即時擷取新值,並新增最短擷取間隔:
let remoteConfig = RemoteConfig.remoteConfig() let settings = RemoteConfigSettings() settings.minimumFetchInterval = 3600 remoteConfig.configSettings = settings
Kotlin
將 Remote Config 依附元件新增至模組 (應用程式層級) Gradle 檔案 (通常為
app/build.gradle.kts或app/build.gradle):dependencies { implementation(platform("com.google.firebase:firebase-bom:34.7.0")) implementation("com.google.firebase:firebase-ai") implementation("com.google.firebase:firebase-config") // ... other dependencies }將 Remote Config 新增至主要應用程式邏輯。在這裡,您將初始化 Remote Config 並新增最短擷取間隔:
val remoteConfig: FirebaseRemoteConfig = Firebase.remoteConfig val configSettings = remoteConfigSettings { minimumFetchIntervalInSeconds = 3600 } remoteConfig.setConfigSettingsAsync(configSettings)
Java
將 Remote Config 依附元件新增至模組 (應用程式層級) Gradle 檔案 (通常為
app/build.gradle.kts或app/build.gradle):dependencies { implementation(platform("com.google.firebase:firebase-bom:34.7.0")) implementation("com.google.firebase:firebase-ai") implementation("com.google.firebase:firebase-config") // ... other dependencies }將 Remote Config 新增至主要應用程式邏輯。在這裡,您將初始化 Remote Config 並新增最短擷取間隔:
FirebaseRemoteConfig mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance(); FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder() .setMinimumFetchIntervalInSeconds(3600) .build(); mFirebaseRemoteConfig.setConfigSettingsAsync(configSettings);
Web
在文字編輯器中開啟程式碼,然後匯入 Remote Config:
import { getRemoteConfig } from 'firebase/remote-config';在主要函式中,並在初始化 Firebase 應用程式後,初始化 Firebase AI Logic SDK,請初始化 Remote Config:
// Initialize Remote Config and get a reference to the service const remoteConfig = getRemoteConfig(app);設定最短擷取間隔:
remoteConfig.settings.minimumFetchIntervalMillis = 3600000;
Dart
在 Flutter 專案目錄中,使用下列指令安裝並新增 Remote Config:
flutter pub add firebase_remote_config開啟
./lib/main.dart,並在您為支援 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';將
_modelName變數新增至應用程式,以便日後使用:late final String _modelName; late final String _systemInstructions; late final String _prompt;取得 Remote Config 物件執行個體,並設定最短擷取間距,才能經常更新。請務必在 Firebase 初始化後新增這項設定。
final remoteConfig = FirebaseRemoteConfig.instance; await remoteConfig.setConfigSettings(RemoteConfigSettings( fetchTimeout: const Duration(seconds: 3600), minimumFetchInterval: const Duration(seconds: 3600), ));
Unity
按照這些操作說明,將 Remote Config 新增至 Unity 專案。
取得 Remote Config 物件執行個體,並設定最短擷取間距,才能經常更新。請務必在 Firebase 初始化後新增這項設定。
var remoteConfig = FirebaseRemoteConfig.DefaultInstance; const int MillisecondsPerSecond = 1000; await remoteConfig.SetConfigSettingsAsync(new ConfigSettings() { FetchTimeoutInMilliseconds = 3600 * MillisecondsPerSecond, MinimumFetchIntervalInMilliseconds = 3600 * MillisecondsPerSecond });
步驟 3:設定應用程式內參數值
您應在 Remote Config 物件中設定應用程式內預設參數值。即使無法從 Remote Config 服務擷取值,應用程式也能正常運作。
Swift
在 Firebase 控制台中開啟 Remote Config。
系統提示時,請啟用「iOS 的 .plist」,然後按一下「下載檔案」。
將檔案儲存在應用程式目錄中。
在 Xcode 中,對應用程式按一下滑鼠右鍵,然後選取「Add Files」(新增檔案)
選取「remote_config_defaults.plist」,然後按一下「新增」。
更新應用程式程式碼,參照預設檔案:
// Set default values for Remote Config parameters. remoteConfig.setDefaults(fromPlist: "remote_config_defaults")
Kotlin
從 Firebase 控制台開啟 Remote Config。
系統提示時,請啟用「.xml (適用於 Android)」,然後按一下「下載檔案」。
將檔案儲存在應用程式的 XML 資源目錄中。
更新主要活動檔案,在先前新增的
configSettings後方加入預設值:// Set default values for Remote Config parameters. remoteConfig.setDefaultsAsync(R.xml.remote_config_defaults)
Java
在 Firebase 控制台中開啟 Remote Config。
系統提示時,請啟用「.xml (適用於 Android)」,然後按一下「下載檔案」。
將檔案儲存在應用程式的 XML 資源目錄中。
更新主要活動檔案,在先前新增的
configSettings後方加入預設值:// Set default values for Remote Config parameters. mFirebaseRemoteConfig.setDefaultsAsync(R.xml.remote_config_defaults);
Web
您可以直接在程式碼中設定模型名稱的預設值:
// Set default values for Remote Config parameters.
remoteConfig.defaultConfig = {
template_id: 'my-first-template-v1-0-0',
};
Dart
您可以直接在程式碼中設定模型名稱的預設值:
// Set default values for Remote Config parameters.
remoteConfig.setDefaults(const {
"template_id": "my-first-template-v1-0-0"
});
Unity
您可以直接在程式碼中設定模型名稱的預設值:
// 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" }
}
);
步驟 4:擷取並啟用值
設定型號名稱的預設值後,請新增下列項目來擷取及啟用值。
Swift
// Fetch and activate Remote Config values
remoteConfig.fetchAndActivate { status, error in
if let error = error {
print("Error fetching Remote Config: \(error.localizedDescription)")
}
}
每當發布新的 Remote Config 範本時,這項作業應會更新 Remote Config 物件。
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
在匯入項目中新增
getValue和fetchAndActivate:import { getValue, fetchAndActivate } from 'firebase/remote-config';找出指定模型名稱預設值的程式碼。 在該程式碼區塊後方,直接新增下列程式碼,以擷取及啟用設定,並將擷取的值指派給
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();
步驟 5:新增即時Remote Config監聽器
在應用程式中新增即時 Remote Config 監聽器,確保您對 Remote Config 範本所做的變更更新後,會立即傳播至用戶端。
每當參數值變更時,下列程式碼就會更新 Remote Config 物件。
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
您也可以選擇在 addOnCompleteListener 啟用時設定動作:
// 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
您也可以選擇在 addOnCompleteListener 啟用時設定動作:
// 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
網頁應用程式不支援即時 Remote Config 監聽器。
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();
};
步驟 6:更新 Gemini API 要求,使用 Remote Config 值
|
按一下 Gemini API 供應商,即可在這個頁面查看供應商專屬內容和程式碼。 |
Remote Config 設定完成後,請更新程式碼,將硬式編碼值替換為來自 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}");
}
// ...
步驟 7:執行應用程式
建構並執行應用程式,確認應用程式是否正常運作。在 Firebase 控制台的「Remote Config」頁面中變更設定,發布變更並驗證結果。
後續步驟
進一步瞭解如何實施其他 Remote Config 和 Firebase AI Logic 的應用做法。
行動應用程式和遊戲:
使用 Remote Config 和 A/B Testing 測試範本變更。
使用Remote Config推出功能 (僅限 iOS+ 和 Android),逐步發布變更。
使用Remote Config個人化功能,透過機器學習技術為個別使用者決定最佳設定 (僅適用於 iOS+、Android 和 Unity)。