サーバー プロンプト テンプレートを使用すると、アプリの新しいバージョンをリリースすることなく、特定のテンプレート内の値を更新できます。ただし、テンプレートに対する変更はアプリからのリクエストによってほぼ即座に使用されるため、アプリを破損させたり、予期しない動作の変更を引き起こしたりする可能性のある変更を加える際には注意が必要です。
そのため、大幅な変更を行ったり、変更を段階的にロールアウトしたりする場合は、本番環境コードで使用されているテンプレートを変更しないようにします。
代わりに、Firebase Remote Config を使用して、モデルへのリクエストで使用されるテンプレート ID の値を制御することをおすすめします。
Firebase Remote Config を使用すると、アプリの新しいバージョンをリリースしなくても、Firebase コンソールからアプリのパラメータ値(テンプレート ID など)を動的にリモートで更新できます。また、変更のロールアウトや A/B テストのための合理化された機能と統合も備えています。
このガイドでは、アプリに Remote Config を実装する方法、特にアプリで使用されるテンプレート ID を制御する方法について説明します。
ステップ 1: Firebase コンソールでパラメータ値を設定する
Remote Config クライアント テンプレートを作成し、アプリでフェッチして使用する template_id パラメータとその値を構成します。
Firebase コンソールで Firebase プロジェクトを開きます。次に、ナビゲーション メニューから [実行] を開いて、Remote Config を選択します。
ページの上部にある [クライアント/サーバー] セレクタで [クライアント] が選択されていることを確認します。
[構成を作成](または、以前にクライアント テンプレートを使用したことがある場合は [パラメータを追加])をクリックして、クライアント テンプレートを開始します。
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 でプロジェクトを開き、[ファイル] > [パッケージの依存関係を追加] の順に移動します。
[Firebase iOS SDK] を選択し、[パッケージを追加] をクリックします。
プロジェクト ナビゲータで、ご使用のアプリ > [ターゲット] > ご使用のアプリを選択します。
[全般] タブで、[フレームワーク、ライブラリ、埋め込みコンテンツ] までスクロールします。
[+] をクリックして [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
モジュール(アプリレベル)の Gradle ファイル(通常は
app/build.gradle.ktsまたはapp/build.gradle)に Remote Config 依存関係を追加します。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
モジュール(アプリレベル)の Gradle ファイル(通常は
app/build.gradle.ktsまたはapp/build.gradle)に Remote Config 依存関係を追加します。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;
ステップ 3: アプリ内のパラメータ値を設定する
アプリ内のデフォルト パラメータ値は Remote Config オブジェクトに設定する必要があります。これにより、Remote Config サービスから値をフェッチできない場合でも、アプリが想定どおりに動作します。
Swift
Firebase コンソールで Remote Config を開きます。
[パラメータ] タブで [メニュー] を開き、[デフォルト値をダウンロード] を選択します。
メッセージが表示されたら、[.plist(iOS 用)] を有効にして、[ファイルをダウンロード] をクリックします。
ファイルをアプリケーション ディレクトリに保存します。
Xcode でアプリを右クリックし、[ファイルを追加] を選択します。
[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',
};
ステップ 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();
ステップ 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 リスナーはサポートされていません。
ステップ 6: Remote Config 値を使用するように Gemini API リクエストを更新する
|
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().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,
}
);
// ...
ステップ 7: アプリを実行する
アプリをビルドして実行し、動作することを確認します。Firebase コンソールの Remote Config ページで構成を変更し、変更をパブリッシュして結果を確認します。
次のステップ
モバイルアプリやゲームの場合:
Remote Config と A/B Testing を使用して、テンプレートの変更をテストする。
Remote Config ロールアウトを使用して、変更を段階的にリリースする(iOS + と Android のみ)。
Remote Config のパーソナライズを使用して、機械学習で個々のユーザーに最適な設定を決定する(iOS+、Android、Unity のみ)。