使用 Firebase AI Logic SDK 從應用程式呼叫 Gemini API 時,要求會包含多個參數,用來控管生成式 AI 回覆。通常包括模型名稱、模型生成設定 (例如權杖上限、溫度等)、安全設定、系統指令和提示資料。
在多數情況下,您會想在下列情況中,視需要變更這些設定:
- 無須發布新版應用程式,即可更新生成式 AI 模型。您可以在舊版模型停用前升級至較新的穩定模型版本,根據使用者的需求和屬性改用成本較低或效能較高的模型,或是將最新且效能最佳的模型有條件地部署至特定使用者區隔 (例如 Beta 版測試人員)。
- 設定模型存取位置,盡量靠近使用者。
- 進行 A/B 測試,找出最合適的系統指令和提示,然後逐步將測試結果套用至使用者。
- 使用功能旗標,在應用程式中快速顯示或隱藏生成式 AI 功能。
Firebase Remote Config 可執行上述所有操作,還能視需要更新參數值,並有條件地更新符合您在 Firebase 控制台中設定特徵的應用程式執行個體,不必發布新版應用程式。
本解決方案指南提供具體的建議用途,並說明如何在生成式 AI 應用程式中加入 Remote Config。
為什麼要在應用程式中使用 Firebase Remote Config?
Firebase Remote Config 可讓您動態調整應用程式的行為,不必更新應用程式。對於使用生成式 AI 的應用程式來說,這項功能特別實用,因為快速疊代和微調至關重要。
搭配生成式 AI 應用程式使用 Remote Config 的基本用途
建議您將 Remote Config 與 Firebase AI Logic 搭配使用,以因應下列重要用途:
無須更新應用程式,即可升級至最新模型版本: 視需要使用 Remote Config 參數變更模型名稱,以便在偏好的 Gemini 模型推出最新版本時立即升級。
更新系統指令和安全設定,不必更新應用程式: 將系統指令和安全設定儲存在 Remote Config 參數中,確保您在部署後發現問題時,可以視需要變更這些設定。
降低風險並強制執行 AI 安全性: 使用 Remote Config推出功能,安全地逐步向 iOS 和 Android 使用者發布生成式 AI 變更。
Remote Config 搭配生成式 AI 應用程式的進階和建議用途
使用 Remote Config 和 Google Analytics 檢測應用程式後,即可探索進階用途:
根據用戶端位置設定位置: 使用 Remote Config 條件,根據系統偵測到的用戶端位置,設定您存取模型的所在位置。
試用不同模型: 快速測試及切換各種生成式 AI 模型,甚至針對不同使用者區隔存取不同模型,找出最符合特定用途的模型。
改善模型成效: 微調模型參數,例如系統提示、輸出詞元數量上限、 隨機性參數和其他設定。
根據用戶端屬性使用不同的系統指令、提示和模型設定:使用 Remote Config Google Analytics 時,您可以根據用戶端屬性或自訂目標對象建立條件,並根據這些屬性設定不同的參數。
舉例來說,如果您在應用程式中使用生成式 AI 提供技術支援,可能需要針對應用程式平台設定專屬的系統指令,確保為 Android、iOS 和網頁平台使用者提供正確的指示。
為每位使用者打造個人化體驗: 在行動應用程式和遊戲中Remote Config啟用個人化功能,系統就會自動為每位使用者決定最佳的生成式 AI 設定。
控管費用: 遠端調整呼叫的生成式 AI 模型、使用頻率,以及根據使用者目標對象動態設定最大輸出權杖值,以減少不必要的費用。
改善應用程式體驗和成效: 搭配使用A/B Testing和Remote Config,針對不同使用者區隔測試生成式 AI 參數的變更,瞭解這些變更對留存率和收益等重要指標的影響。
透過 Firebase Remote Config 檢測生成式 AI 應用程式,您可以建構彈性、安全且經濟實惠的 AI 輔助應用程式,同時為使用者打造愉悅的體驗。
在應用程式中新增 Firebase Remote Config
在本解決方案指南中,您將使用 Firebase Remote Config,在採用 Firebase AI Logic SDK 的 Android 應用程式中動態更新參數。您將學習下列內容:
- 從 Firebase Remote Config 擷取並啟用模型名稱和系統指令等參數。
- 更新 Gemini API 呼叫,使用動態擷取的參數,即可在不同模型之間切換,或修改系統指令,不必更新應用程式。
- 從遠端控制參數,視需要調整模型行為和功能。
事前準備
本指南假設您已熟悉為平台開發應用程式。
開始之前,請先確認下列事項:
請參閱Firebase AI Logic入門指南,瞭解如何設定 Firebase 專案、將應用程式連結至 Firebase、新增 SDK、為所選「Gemini API」供應商初始化後端服務,以及建立模型例項。
在 Firebase 專案中啟用 Google Analytics,並將 SDK 新增至應用程式 (如要設定存取模型的所在位置,必須根據用戶端裝置的位置資訊,因此需要啟用這項功能)。
步驟 1:在 Firebase 控制台中設定參數值
建立用戶端Remote Config範本,並設定要在應用程式中擷取及使用的參數和值。
- 在 Firebase 控制台中開啟 Firebase 專案。然後,在導覽選單中展開「執行」,並選取「Remote Config」。
- 確認已從頁面頂端的「Client/Server」選取器中選取「Client」。
- 按一下「建立設定」(或「新增參數」,如果您先前使用過用戶端範本),即可開始建立用戶端範本。
定義要透過 Remote Config 控制的參數。例如:
參數名稱 說明 類型 預設值 model_name
模型名稱。請參閱可用的模型名稱。 字串 gemini-2.5-flash
system_instructions
系統指令就像「前言」,您可以在模型接收任何來自使用者的進一步指令前新增,藉此影響模型行為。 字串 You are a helpful assistant who knows everything there is to know about Firebase!
prompt
搭配生成式 AI 功能使用的預設提示。 字串 I am a developer who wants to know more about Firebase!
vertex_location
僅適用於使用 Vertex AI Gemini API 的情況。
控制模型存取位置。您可以設定條件,根據 Google Analytics 偵測到的用戶端位置設定這個選項。字串 global
新增完參數後,請按一下「發布變更」。如果這不是新範本,請查看變更並再次按一下「發布變更」。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
在快速入門應用程式中,這會位於
AppDelegate
類別的VertexAISampleApp
內。
Kotlin
將 Remote Config 依附元件新增至模組 (應用程式層級) Gradle 檔案 (通常為
app/build.gradle.kts
或app/build.gradle
):dependencies { implementation(platform("com.google.firebase:firebase-bom:33.15.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:33.15.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
、_systemInstructions
和_prompt
變數,以便稍後使用: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」,然後按一下「下載檔案」。
將檔案儲存在應用程式目錄中。
如果使用範例應用程式,請將檔案儲存在
FirebaseVertexAI/Sample/VertexAISample
中。在 Xcode 中,對應用程式按一下滑鼠右鍵,然後選取「Add Files」(新增檔案)
如果使用範例,請在「VertexAISample」上按一下滑鼠右鍵,然後選取「Add Files to "VertexAISample"」。
選取「remote_config_defaults.plist」,然後按一下「新增」。
更新應用程式程式碼,參照預設檔案:
// Set default values remoteConfig.setDefaults(fromPlist: "remote_config_defaults")
Kotlin
Java
Web
您可以在程式碼中直接設定預設值:
// Set default Remote Config parameter values
remoteConfig.defaultConfig = {
model_name: 'gemini-2.5-flash',
system_instructions:
'You are a helpful assistant who knows everything there is to know about Firebase!',
prompt: 'I am a developer who wants to know more about Firebase!',
vertex_location: 'global',
};
Dart
您可以在程式碼中直接設定預設值:
remoteConfig.setDefaults(const {
"model_name": "gemini-2.5-flash",
"system_instructions": "You are a helpful assistant who knows everything there is to know about Firebase!",
"prompt": "I am a developer who wants to know more about Firebase!",
"vertex_location": "global"
});
Unity
您可以在程式碼中直接設定預設值:
await remoteConfig.SetDefaultsAsync(
new System.Collections.Generic.Dictionary<string, object>() {
{ "model_name", "gemini-2.5-flash" },
{ "system_instructions", "You are a helpful assistant who knows everything there is to know about Firebase!" },
{ "prompt", "I am a developer who wants to know more about Firebase!" },
{ "vertex_location", "global" }
}
);
步驟 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';
在您新增的程式碼中設定預設 Remote Config 值後,請擷取並啟用設定,然後將值指派給
modelName
、systemInstructions
、prompt
和vertexLocation
常數。// 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(); const systemInstructions = getValue(remoteConfig, 'system_instructions').asString(); const prompt = getValue(remoteConfig, 'prompt').asString(); const vertexLocation = getValue(remoteConfig, 'vertex_location').asString();
Dart
// Fetch and activate Remote Config.
remoteConfig.fetchAndActivate();
// Assign Remote Config values.
String? _modelName = remoteConfig.getString("model_name");
String? _systemInstructions = remoteConfig.getString("system_instructions");
String? _prompt = remoteConfig.getString("prompt");
String? _vertexLocation = remoteConfig.getString("vertex_location");
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
// Initialize the Gemini Developer API backend service
// The Gemini Developer API doesn't support setting the location of a model
let ai = FirebaseAI.firebaseAI(backend: .googleAI())
// Create a `GenerativeModel` and add system instructions into its config
// Both the model name and the system instructions will be sourced from Remote Config
let modelName = remoteConfig.configValue(forKey: "model_name").stringValue
let systemInstructions = remoteConfig.configValue(forKey: "system_instructions").stringValue
let model = ai.generativeModel(
modelName: modelName,
systemInstruction: ModelContent(role: "system", parts: systemInstructions)
)
// Provide a prompt that contains text
// The text in the prompt will be sourced from Remote Config
let userPrompt = remoteConfig.configValue(forKey: "prompt").stringValue
// To generate text output, call `generateContent` with the text input
let response = try await model.generateContent(userPrompt)
if let text = response.text {
print(text)
}
Kotlin
// Initialize the Gemini Developer API backend service
// The Gemini Developer API doesn't support setting the location of a model
val ai = Firebase.ai(backend = GenerativeBackend.googleAI())
// Create a `GenerativeModel` and add system instructions into its config
// Both the model name and the system instructions will be sourced from Remote Config
val model = ai.generativeModel(
modelName = remoteConfig.getString("model_name"),
systemInstruction = content { text(remoteConfig.getString("system_instructions")) }
)
// To generate text output, call `generateContent` with the text input
// The text in the prompt will be sourced from Remote Config
val response = model.generateContent(remoteConfig.getString("prompt"))
print(response.text)
Java
// Initialize the Gemini Developer API backend service
// The Gemini Developer API doesn't support setting the location of a model
FirebaseAI ai = FirebaseAI.getInstance(GenerativeBackend.googleAI());
// Create a `GenerativeModel` and add system instructions into its config
// Both the model name and the system instructions will be sourced from Remote Config
GenerativeModel gm = ai.generativeModel(
/* modelName */ remoteConfig.getString("model_name"),
/* generationConfig (optional) */ null,
/* safetySettings (optional) */ null,
/* tools (optional) */ null,
/* toolsConfig (optional) */ null,
/* systemInstruction (optional) */ new Content.Builder().addText(
remoteConfig.getString("system_instructions")).build(),
/* requestOptions (optional) */ new RequestOptions()
);
GenerativeModelFutures model = GenerativeModelFutures.from(gm);
// Provide a prompt that contains text
// The text in the prompt will be sourced from Remote Config
Content userPrompt = new Content.Builder()
.addText(remoteConfig.getString("prompt"))
.build();
// To generate text output, call `generateContent` with the text input
ListenableFuture<GenerateContentResponse> response = model.generateContent(userPrompt);
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
// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);
// Initialize the Gemini Developer API backend service
// The Gemini Developer API doesn't support setting the location of a model
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Create a `GenerativeModel` and add system instructions into its config
// Both the model name and the system instructions will be sourced from Remote Config
const model = getGenerativeModel(ai, {
model: modelName,
systemInstruction: systemInstruction
});
// Wrap in an async function so you can use await
async function run() {
// Provide a prompt that contains text
// The text in the prompt will be sourced from Remote Config
const userPrompt = prompt;
// To generate text output, call `generateContent` with the text input
const result = await model.generateContent(userPrompt);
const response = result.response;
const text = response.text();
console.log(text);
}
Dart
// Initialize the Gemini Developer API backend service
// The Gemini Developer API doesn't support setting the location of a model
final ai = await FirebaseAI.googleAI();
// Create a `GenerativeModel` and add system instructions into its config
// Both the model name and the system instructions will be sourced from Remote Config
final model =
ai.generativeModel(
model: _modelName,
systemInstruction: Content.system(_systemInstructions),
);
// Provide a prompt that contains text
// The text in the prompt will be sourced from Remote Config
final _userPrompt = [Content.text(_prompt)];
// To generate text output, call `generateContent` with the text input
final response = await model.generateContent(_userPrompt);
print(response.text);
Unity
// Initialize the Gemini Developer API backend service
// The Gemini Developer API doesn't support setting the location of a model
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());
// Create a `GenerativeModel` and add system instructions into its config
// Both the model name and the system instructions will be sourced from Remote Config
var modelName = remoteConfig.GetValue("model_name").StringValue;
var systemInstructions = remoteConfig.GetValue("system_instructions").StringValue;
var model = ai.GetGenerativeModel(
modelName: modelName,
systemInstruction: ModelContent.Text(systemInstructions)
);
// Provide a prompt that contains text
// The text in the prompt will be sourced from Remote Config
var userPrompt = remoteConfig.GetValue("prompt").StringValue;
// To generate text output, call `GenerateContentAsync` with the text input
var response = await model.GenerateContentAsync(userPrompt);
UnityEngine.Debug.Log(response.Text ?? "No text in response.");
步驟 7:執行應用程式
建構並執行應用程式,確認應用程式是否正常運作。在 Firebase 控制台的「Remote Config」頁面中變更設定,發布變更並驗證結果。
後續步驟
進一步瞭解 Remote Config。
在用戶端程式碼中加入 Google Analytics ,即可啟用指定目標。
行動應用程式和遊戲:
使用 Remote Config 和 A/B Testing 測試不同的模型設定。
使用Remote Config推出功能,逐步發布模型參數變更 (僅限 iOS+ 和 Android)。
使用Remote Config個人化功能,透過機器學習技術為個別使用者找出最佳設定 (僅適用於 iOS+、Android 和 Unity)。