生成式 AI 模型的供應情形經常變動,我們會推出更優質的新模型,並淘汰舊型模型。
使用 Firebase AI Logic 從行動或網頁應用程式直接存取生成式 AI 模型時,請務必設定應用程式,以因應這些頻繁的模型變更。並非所有使用者都會更新至最新版應用程式,開始使用您希望他們使用的模型。
Firebase Remote Config 可讓您從 Firebase 控制台動態更新應用程式中的參數值 (例如模型名稱),不必發布新版應用程式。
請注意,變更模型名稱是使用 Remote Config 和 Firebase AI Logic 的重要用途,但您也可以使用 Remote Config 動態控制應用程式中的參數,甚至是條件式控制,例如模型生成設定 (最多權杖數、溫度等)、安全設定、系統指令和提示資料。
本指南說明如何在應用程式中實作 Remote Config,特別是控制應用程式中使用的模型名稱。
步驟 1:在 Firebase 控制台中設定參數值
建立 Remote Config 用戶端範本,並設定 model_name 參數及其值,以便在應用程式中擷取及使用。
在 Firebase 控制台中開啟 Firebase 專案。接著,從導覽選單中展開「執行」,然後選取 Remote Config。
確認已從頁面頂端的「Client/Server」(用戶端/伺服器) 選取器中選取「Client」(用戶端)。
按一下「建立設定」(或「新增參數」,如果您先前使用過用戶端範本),即可開始建立用戶端範本。
定義
model_name參數:參數名稱 說明 類型 預設值 model_name模型名稱。請參閱可用的模型名稱。 字串 gemini-2.5-flash新增這個參數後,請按一下「發布變更」。如果這不是新範本,請查看變更並再次按一下「發布變更」。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.5.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.5.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 = {
model_name: 'gemini-2.5-flash',
};
Dart
您可以直接在程式碼中設定模型名稱的預設值:
// Set default values for Remote Config parameters.
remoteConfig.setDefaults(const {
"model_name": "gemini-2.5-flash"
});
Unity
您可以直接在程式碼中設定模型名稱的預設值:
// Set default values for Remote Config parameters.
await remoteConfig.SetDefaultsAsync(
new System.Collections.Generic.Dictionary<string, object>() {
{ "model_name", "gemini-2.5-flash" }
}
);
步驟 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';找出指定模型名稱預設值的程式碼。 在該程式碼區塊後方,直接新增下列程式碼,以擷取及啟用設定,並將擷取的值指派給
modelName常數。// 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 modelName = getValue(remoteConfig, 'model_name').asString();
Dart
// Fetch and activate Remote Config.
remoteConfig.fetchAndActivate();
// Assign Remote Config values.
String? _modelName = remoteConfig.getString("model_name");
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
// When creating a `GenerativeModel` instance, source the model name value from Remote Config
let modelName = remoteConfig.configValue(forKey: "model_name").stringValue
let model = FirebaseAI.firebaseAI(backend: .googleAI()).generativeModel(
modelName: modelName
)
// ...
Kotlin
// When creating a `GenerativeModel` instance, source the model name value from Remote Config
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
modelName = remoteConfig.getString("model_name")
)
// ...
Java
// When creating a `GenerativeModel` instance, source the model name value from Remote Config
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.generativeModel(
/* modelName */ remoteConfig.getString("model_name"),
/* generationConfig (optional) */ null,
/* safetySettings (optional) */ null,
/* requestOptions (optional) */ new RequestOptions(),
/* tools (optional) */ null,
/* toolsConfig (optional) */ null,
/* systemInstruction (optional) */ null,
);
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
// ...
Web
// ...
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// When creating a `GenerativeModel` instance, source the model name value from Remote Config
const model = getGenerativeModel(ai, {
model: modelName
});
// ...
Dart
// ...
// When creating a `GenerativeModel` instance, source the model name value from Remote Config
final model = FirebaseAI.googleAI().generativeModel(
model: _modelName,
);
// ...
Unity
// ...
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());
// When creating a `GenerativeModel` instance, source the model name value from Remote Config
var modelName = remoteConfig.GetValue("model_name").StringValue;
var model = ai.GetGenerativeModel(
modelName: modelName
);
// ...
步驟 7:執行應用程式
建構並執行應用程式,確認應用程式是否正常運作。在 Firebase 控制台的「Remote Config」頁面中變更設定,發布變更並驗證結果。
後續步驟
進一步瞭解如何實施其他 Remote Config 和 Firebase AI Logic 的應用做法。
行動應用程式和遊戲:
使用 Remote Config 和 A/B Testing 測試不同的模型設定。
使用Remote Config推出功能,逐步發布模型參數變更 (僅限 iOS+ 和 Android)。
使用Remote Config個人化功能,透過機器學習技術為個別使用者決定最佳設定 (僅適用於 iOS+、Android 和 Unity)。