使用 Firebase AI Logic SDK 從應用程式呼叫 Gemini API 時,您的要求會包含多個參數,用於控制生成式 AI 回應。這些通常包括模型名稱、模型產生設定 (最大符記、溫度等)、安全設定、系統指示和提示資料。
在大多數情況下,您需要視需要或在多種情況下變更這些設定:
- 無須發布新版應用程式,即可更新生成式 AI 模型。您可以在舊版模型停用前升級至較新的穩定版模型,也可以根據使用者的需要和屬性降級至成本較低或效能較高的模型,或是有條件地將最新的最佳模型部署至特定使用者區隔 (例如 Beta 版測試人員)。
- 設定模型存取位置,讓模型更靠近使用者。
- 針對不同的系統指示和提示進行 A/B 測試,然後逐步向使用者推出最佳實驗值。
- 使用功能旗標,快速在應用程式中顯示或隱藏生成式 AI 功能。
Firebase Remote Config 會執行上述所有操作,並提供更多功能,讓您可以視需要更新參數值,並針對符合您在 Firebase 控制台中設定的特性的應用程式執行個體,依條件更新,而無須發布新版應用程式。
本解決方案指南提供特定建議用途,並說明如何將 Remote Config 新增至生成式 AI 應用程式。
為什麼要將 Firebase Remote Config 與應用程式搭配使用?
Firebase Remote Config 可讓您動態調整應用程式的行為,而無需更新應用程式。對於使用生成式 AI 的應用程式來說,這項功能特別實用,因為這類應用程式需要快速迭代和精細調整。
Remote Config 與生成式 AI 應用程式的重要用途
建議您在下列重要用途中搭配使用 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 專案。接著,在導覽選單中展開「Run」,然後選取「Remote Config」。
- 確認已從頁面頂端的「Client/Server」選取器中選取「Client」。
- 按一下「建立設定」(如果您先前曾使用客戶範本,請按一下「新增參數」),即可開始使用客戶範本。
定義要透過 Remote Config 控制的參數。例如:
參數名稱 說明 類型 預設值 model_name
型號名稱。請參閱可用的型號名稱。 字串 gemini-2.0-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 偵測到的用戶端位置設定這個選項。字串 us-central1
新增參數完成後,請按一下「發布變更」。如果這不是新的 Remote Config 範本,請查看變更內容,然後再次按一下「Publish changes」。
步驟 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」中,依序選取應用程式 >「目標」 > 應用程式。
在「一般」分頁中,捲動至「架構、程式庫和嵌入內容」。
按一下「+」,然後選擇「FirebaseRemoteConfig」,接著按一下「新增」。
將
FirebaseRemoteConfig
匯入項目新增至程式碼:import FirebaseRemoteConfig
在應用程式的適當類別中,初始化 Firebase,並將 Remote Config 新增至主要應用程式邏輯。
在此,您將納入 Remote Config 和 Remote Config 即時事件監聽器 做為匯入項目,以便應用程式即時擷取新值,並新增擷取間隔的最小值:
let remoteConfig = RemoteConfig.remoteConfig() let settings = RemoteConfigSettings() settings.minimumFetchInterval = 3600 remoteConfig.configSettings = settings
在快速入門應用程式中,這會位於
VertexAISampleApp
內,位於AppDelegate
類別內。
Kotlin
將 Remote Config 依附元件新增至模組 (應用程式層級) Gradle 檔案 (通常為
app/build.gradle.kts
或app/build.gradle
):dependencies { implementation(platform("com.google.firebase:firebase-bom:33.14.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.14.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 AI Logic SDK 為 Firebase 應用程式初始化後,請初始化 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.0-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: 'us-central1',
};
Dart
您可以直接在程式碼中設定預設值:
remoteConfig.setDefaults(const {
"model_name": "gemini-2.0-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": "us-central1"
});
Unity
您可以直接在程式碼中設定預設值:
await remoteConfig.SetDefaultsAsync(
new System.Collections.Generic.Dictionary<string, object>() {
{ "model_name", "gemini-2.0-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", "us-central1" }
}
);
步驟 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)。