使用 Firebase AI Logic SDK 从应用中调用 Gemini API 时,您的请求会包含一些用于控制生成式 AI 回答的参数。这些参数通常包括模型名称、模型生成配置(token 数量上限、温度等)、安全设置、系统指令和提示数据。
在大多数情况下,您需要按需更改这些参数,或者根据多种场景的需要进行更改:
- 无需发布新应用即可更新生成式 AI 模型。您可以在旧版本停用之前升级到较新的稳定模型版本,根据用户需求和属性降级到成本较低或性能较高的模型,或者有条件地将最新和最好的模型部署到特定细分用户群(例如 Beta 版测试人员)。
- 设置模型的访问位置,使其更靠近用户。
- 对不同的系统指令和提示进行 A/B 测试,然后逐步向用户发布实验的胜出值。
- 使用功能标志在应用中快速公开或隐藏生成式 AI 功能。
Firebase Remote Config 可执行上述所有操作及更多操作,让您可以根据需要更新参数值,并有条件地为与您在 Firebase 控制台中设置的特征相匹配的应用实例更新参数值,而无需发布新版本的应用。
本解决方案指南提供了特定的推荐应用场景,并介绍了如何向生成式 AI 应用添加 Remote Config。
为什么要将 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 模型之间切换,甚至针对不同的细分用户群访问不同的模型,以找到最适合您的特定应用场景的模型。
优化模型性能:微调模型参数,例如系统提示、输出 token 数量上限、温度和其他设置。
根据客户端属性使用不同的系统指令、提示和模型配置:将 Remote Config 与 Google Analytics 搭配使用时,您可以根据客户端属性或自定义受众群体创建条件,并根据这些属性设置不同的参数。
例如,如果您使用生成式 AI 在应用中提供技术支持,则可能需要设置特定于应用平台的系统指令,以确保向 Android、iOS 和 Web 平台用户提供准确的指令。
为每位用户提供个性化体验:将 Remote Config 个性化与移动应用和游戏搭配使用,自动确定适用于每位用户的最佳生成式 AI 设置。
控制费用:远程调整调用的生成式 AI 模型、模型的使用频率,并根据用户受众群体动态配置输出令牌数量上限值,以减少不必要的费用。
优化应用体验和成效:将 A/B Testing 与 Remote Config 搭配用于移动应用和游戏,以在不同细分用户群中测试对生成式 AI 参数进行的更改,了解这些更改对留存率和收入等关键指标的影响。
通过使用 Firebase Remote Config 对生成式 AI 应用进行插桩,您可以构建灵活、安全且经济实惠的依托 AI 技术的应用,同时为用户打造愉悦的体验。
将 Firebase Remote Config 添加到您的应用
在本解决方案指南中,您将使用 Firebase Remote Config 动态更新 Android 应用中使用 Firebase AI Logic SDK 的参数。您将学习如何:
- 从 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。
- 确保从页面顶部的客户端/服务器选择器中选择客户端。
- 点击创建配置(如果您之前使用过客户端模板,则点击添加参数)以开始创建客户端模板。
定义您要使用 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 模板,请查看更改,然后再次点击发布更改。
第 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(添加软件包)。
在项目导航器中,依次选择您的应用 > Targets(目标)> 您的应用。
在 General(常规)标签页中,滚动到 Frameworks, Libraries, and Embedded Content(框架、库和嵌入内容)。
点击 +,然后选择 FirebaseRemoteConfig,接着点击 Add(添加)。
将
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.13.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.13.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。
在参数标签页中,打开菜单,然后选择下载默认值。
看到提示时,启用 .plist (iOS),然后点击下载文件。
将该文件保存在应用目录中。
如果使用的是示例应用,请将其保存在
FirebaseVertexAI/Sample/VertexAISample
中。在 Xcode 中,右键点击您的应用,然后选择 Add Files(添加文件)
如果使用示例,请右键点击 VertexAISample,然后选择 Add Files to "VertexAISample"。
选择 remote_config_defaults.plist,然后点击 Add(添加)。
更新应用代码以引用默认文件:
// Set default values remoteConfig.setDefaults(fromPlist: "remote_config_defaults")
Kotlin
在 Firebase 控制台中,打开 Remote Config。
在参数标签页中,打开菜单,然后选择下载默认值。
看到提示时,启用 .xml (Android),然后点击下载文件。
将该文件保存在应用的 XML 资源目录中。
更新主 activity 文件,以便在您之前添加的
configSettings
后面添加默认值:// Set default values. remoteConfig.setDefaultsAsync(R.xml.remote_config_defaults)
Java
在 Firebase 控制台中,打开 Remote Config。
在参数标签页中,打开菜单,然后选择下载默认值。
看到提示时,启用 .xml (Android),然后点击下载文件。
将该文件保存在应用的 XML 资源目录中。
更新主 activity 文件,以便在您之前添加的
configSettings
后面添加默认值:// Set default values. mFirebaseRemoteConfig.setDefaultsAsync(R.xml.remote_config_defaults);
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
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)。