<br />

| **Preview**: Using server prompt templates is a feature that's in Preview, which means that it isn't subject to any SLA or deprecation policy and could change in backwards-incompatible ways.

<br />

When you use server prompt templates, you can update values*within*a given template without releasing a new version of your app. However, since any changes to the template will nearly immediately be used by requests from your app, you need to be cautious about making changes that could break your app or cause unexpected changes in behavior.

So, if you want to make more substantial changes or roll out changes gradually, then you won't want to change the template that's used in production code.

Instead, we recommend usingFirebase Remote Configto*control the value of template ID*used in the request to the model.

[Firebase Remote Config](https://firebase.google.com/docs/remote-config)lets you update parameter values in your app (like the template ID) dynamically and remotely from theFirebaseconsole, without the need to release a new version of your app. It also has streamlined capabilities and integrations for rolling out changes as well as A/B testing.
| We**strongly recommend implementingFirebase Remote Configinto your app as early as possible**, even during development, so that you can update the template ID remotely in every version of your app.

This guide describes how to implementRemote Configin your app, specifically to***control the template ID used in your app***.

### **Step 1** : Set the parameter value in theFirebaseconsole

Create aRemote Configclient template and configure a`template_id`parameter and its value to fetch and use in the app.

1. Open your Firebase project in theFirebaseconsole. Then, from the navigation menu, expand**Run** and select[**Remote Config**](https://console.firebase.google.com/project/_/config).

2. Ensure that**Client** is selected from the**Client/Server**selector at the top of the page.

3. Start a client template by clicking**Create Configuration** (or**Add parameter**if you've previously used client templates).

4. Define the`template_id`parameter:

   | Parameter name | Description  |  Type  |       Default value        |
   |----------------|--------------|--------|----------------------------|
   | `template_id`  | Template ID. | String | `my-first-template-v1-0-0` |

5. After adding this parameter, click**Publish changes** . If this is not a newRemote Configtemplate, review the changes and click**Publish changes**again.

### **Step 2** : Add and initializeRemote Configin your app

Add theRemote Configlibrary and set upRemote Configwithin your app.  

### Swift

As part of[Firebase AI Logicsetup](https://firebase.google.com/docs/ai-logic/get-started#add-sdk), you've already added the Firebase SDK to your app, but will also need to addRemote Config.

1. In Xcode, with the project open, navigate to**File \> Add Package Dependencies**.

2. Select**firebase-ios-sdk** and then click**Add package**.

3. From the Project navigator, select your app \>**Targets**\> your app.

4. From the**General** tab, scroll to**Frameworks, Libraries, and Embedded Content**.

5. Click**+** and choose**FirebaseRemoteConfig** , then click**Add**.

6. Add the`FirebaseRemoteConfig`import to your code:

       import FirebaseRemoteConfig

7. Inside the appropriate class for your app, initialize Firebase and addRemote Configto your main application logic.

   Here, you'll includeRemote Configand the[Remote Configreal-time listener](https://firebase.google.com/docs/remote-config/real-time)as imports so that the app can fetch new values in real-time, and add a minimum fetch interval:  

       let remoteConfig = RemoteConfig.remoteConfig()
       let settings = RemoteConfigSettings()
       settings.minimumFetchInterval = 3600
       remoteConfig.configSettings = settings

   | **Note:** In this example, the default fetch interval is 3600 seconds, but we recommend that you set a relatively low minimum fetch interval inside your code during development.

### Kotlin

1. Add theRemote Configdependency to your module (app-level) Gradle file (usually`app/build.gradle.kts`or`app/build.gradle`):

       dependencies {
           implementation(platform("com.google.firebase:firebase-bom:34.6.0"))
           implementation("com.google.firebase:firebase-ai")
           implementation("com.google.firebase:firebase-config")
           // ... other dependencies
       }

2. AddRemote Configto your main application logic. Here, you'll initializeRemote Configand add a minimum fetch interval:

       val remoteConfig: FirebaseRemoteConfig = Firebase.remoteConfig
       val configSettings = remoteConfigSettings {
       minimumFetchIntervalInSeconds = 3600
       }
       remoteConfig.setConfigSettingsAsync(configSettings)

   | **Note:** In this example, the default fetch interval is 3600 seconds, but we recommend that you set a relatively low minimum fetch interval inside your code during development.

### Java

1. Add theRemote Configdependency to your module (app-level) Gradle file (usually`app/build.gradle.kts`or`app/build.gradle`):

       dependencies {
           implementation(platform("com.google.firebase:firebase-bom:34.6.0"))
           implementation("com.google.firebase:firebase-ai")
           implementation("com.google.firebase:firebase-config")
           // ... other dependencies
       }

2. AddRemote Configto your main application logic. Here, you'll initializeRemote Configand add a minimum fetch interval:

       FirebaseRemoteConfig mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
       FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
           .setMinimumFetchIntervalInSeconds(3600)
           .build();
       mFirebaseRemoteConfig.setConfigSettingsAsync(configSettings);

   | **Note:** In this example, the default fetch interval is 3600 seconds, but we recommend that you set a relatively low minimum fetch interval inside your code during development.

### Web

1. Open your code in a text editor and importRemote Config:

       import { getRemoteConfig } from 'firebase/remote-config';

2. Inside your primary function and after the Firebase app is initialized forFirebase AI LogicSDK, initializeRemote Config:

         // Initialize Remote Config and get a reference to the service
         const remoteConfig = getRemoteConfig(app);

3. Set a minimum fetch interval:

       remoteConfig.settings.minimumFetchIntervalMillis = 3600000;

   | **Note:** In this example, the default fetch interval is 3600 seconds, but we recommend that you set a relatively low minimum fetch interval inside your code during development.

### Dart

1. From your Flutter project directory, install and addRemote Configusing the following command:

       flutter pub add firebase_remote_config

2. Open`./lib/main.dart`and add the import after the other imports you added to supportFirebase 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';

3. Add the`_modelName`variable to your app so that you can use it later:

       late final String _modelName;
       late final String _systemInstructions;
       late final String _prompt;

4. Get theRemote Configobject instance and set the minimum fetch interval to allow for frequent refreshes. Make sure to add this after Firebase is initialized.

         final remoteConfig = FirebaseRemoteConfig.instance;
         await remoteConfig.setConfigSettings(RemoteConfigSettings(
           fetchTimeout: const Duration(seconds: 3600),
           minimumFetchInterval: const Duration(seconds: 3600),
         ));

   | **Note:** In this example, the default fetch interval is 3600 seconds, but we recommend that you set a relatively low minimum fetch interval inside your code during development.

### Unity

1. AddRemote Configto your Unity project, following these[instructions](https://firebase.google.com/docs/unity/setup#add-sdks).

2. Get theRemote Configobject instance and set the minimum fetch interval to allow for frequent refreshes. Make sure to add this after Firebase is initialized.

       var remoteConfig = FirebaseRemoteConfig.DefaultInstance;
       const int MillisecondsPerSecond = 1000;
       await remoteConfig.SetConfigSettingsAsync(new ConfigSettings() {
         FetchTimeoutInMilliseconds = 3600 * MillisecondsPerSecond,
         MinimumFetchIntervalInMilliseconds = 3600 * MillisecondsPerSecond
       });

   | **Note:** In this example, the default fetch interval is 3600 seconds, but we recommend that you set a relatively low minimum fetch interval inside your code during development.

### **Step 3**: Set the in-app parameter value

You should set in-app default parameter values in theRemote Configobject. This ensures that your app behaves as expected even if it cannot fetch values from theRemote Configservice.  

### Swift

1. In theFirebaseconsole, openRemote Config.

2. In the[**Parameters**](https://console.firebase.google.com/project/_/config)tab, open the**Menu** , and select**Download default values**.

3. When prompted, enable**.plist for iOS** , then click**Download file**.

4. Save the file in the your application directory.

5. In Xcode, right-click on your app and select**Add Files**

6. Select**remote_config_defaults.plist** , then click**Add**.

7. Update your app code to reference the defaults file:

       // Set default values for Remote Config parameters.
       remoteConfig.setDefaults(fromPlist: "remote_config_defaults")

### Kotlin

1. From theFirebaseconsole, openRemote Config.

2. In the[**Parameters**](https://console.firebase.google.com/project/_/config)tab, open the**Menu** , and select**Download default values**.

3. When prompted, enable**.xml for Android** , then click**Download file**.

4. Save the file in your app's XML resources directory.

5. Update your main activity file to add the defaults after the`configSettings`you added previously:

       // Set default values for Remote Config parameters.
       remoteConfig.setDefaultsAsync(R.xml.remote_config_defaults)

### Java

1. In theFirebaseconsole, openRemote Config.

2. In the[**Parameters**](https://console.firebase.google.com/project/_/config)tab, open the**Menu** , and select**Download default values**.

3. When prompted, enable**.xml for Android** , then click**Download file**.

4. Save the file in your app's XML resources directory.

5. Update your main activity file to add the defaults after the`configSettings`you added previously:

       // Set default values for Remote Config parameters.
       mFirebaseRemoteConfig.setDefaultsAsync(R.xml.remote_config_defaults);

### Web

You can set the default value for the model name directly in your code:  

    // Set default values for Remote Config parameters.
    remoteConfig.defaultConfig = {
      template_id: 'my-first-template-v1-0-0',
    };

### Dart

You can set the default value for the model name directly in your code:  

    // Set default values for Remote Config parameters.
    remoteConfig.setDefaults(const {
      "template_id": "my-first-template-v1-0-0"
    });

### Unity

You can set the default value for the model name directly in your code:  

    // Set default values for Remote Config parameters.
    await remoteConfig.SetDefaultsAsync(
      new System.Collections.Generic.Dictionary<string, object>() {
        { "template_id", "my-first-template-v1-0-0" }
      }
    );

### **Step 4**: Fetch and activate the value

After setting the default value for the model name, add the following to fetch and activate values.  

### Swift

    // Fetch and activate Remote Config values
    remoteConfig.fetchAndActivate { status, error in
      if let error = error {
        print("Error fetching Remote Config: \(error.localizedDescription)")
      }
    }

This should update theRemote Configobject whenever a newRemote Configtemplate is published.
| **Important:** Be sure to put any code that depends on these values*after*fetch and activate.

### 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)
              }
          }

| **Important:** Be sure to put any code that depends on these values*after*fetch and activate.

### 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)
                }
              }
        });

| **Important:** Be sure to put any code that depends on these values*after*fetch and activate.

### Web

1. Add`getValue`and`fetchAndActivate`to your imports:

       import { getValue, fetchAndActivate } from 'firebase/remote-config';

2. Locate the code where you specify the default value for the model name. Directly after that code block, add the following code to fetch and activate the config and assign the fetched value to the`templateID`constant.

       // 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();

| **Important:** Be sure to put any code that depends on these values*after*fetch and activate.

### Dart

    // Fetch and activate Remote Config.
    remoteConfig.fetchAndActivate();

    // Assign Remote Config values.
    String? _templateID = remoteConfig.getString("template_id");

| **Important:** Be sure to put any code that depends on these values*after*fetch and activate.

### Unity

    // Fetch and activate Remote Config values.
    await remoteConfig.FetchAndActivateAsync();

| **Important:** Be sure to put any code that depends on these values*after*fetch and activate.

### **Step 5** : Add a real-timeRemote Configlistener

Add a[real-timeRemote Configlistener](https://firebase.google.com/docs/remote-config/real-time)to your app to ensure that changes you make to theRemote Configtemplate are propagated to the client as soon as they're updated.

The following code updates theRemote Configobject whenever a parameter value changes.  

### 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

Optionally, you can also configure an action inside the`addOnCompleteListener`activation:  

          // 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

Optionally, you can also configure an action inside the`addOnCompleteListener`activation:  

      // 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

[Real-timeRemote Configlisteners](https://firebase.google.com/docs/remote-config/real-time)aren't supported for Web apps.

### 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();
    };

### **Step 6** : Update theGemini APIrequests to use theRemote Configvalue

|----------------------------------------------------------------------------------------------------------------------------------|
| *Click yourGemini APIprovider to view provider-specific content and code on this page.* Gemini Developer APIVertex AI Gemini API |

Now thatRemote Configis fully configured, update your code to replace hard-coded values with values sourced fromRemote Config.
**Note:** This example shows using a`templateGenerativeModel`, but it also works with an`templateImagenModel`, as applicable.  

### 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(backend = GenerativeBackend.googleAI()).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,
      }
    );

    // ...

### Dart

    // ...

    final model = FirebaseAI.googleAI().templateGenerativeModel();

    final templateID = remoteConfig.getString("template_id");
    final customerName = 'Jane';

    // When making the `generateContent` call, source the template ID value from Remote Config
    var response = await model.generateContent(
      templateID,
      // Provide the values for any input variables required by your template
      inputs: {
        'customerName': customerName,
      },
    );

    // ...

### Unity

    // ...

    var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());

    var templateID = remoteConfig.GetValue("template_id").StringValue;
    var model = ai.GetTemplateGenerativeModel();
    var customerName = "Jane";

    try
    {
        // When making the `generateContent` call, source the template ID value from Remote Config
        var response = await model.GenerateContentAsync(
            templateID,
            // Provide the values for any input variables required by your template
            new Dictionary<string, object>
            {
                { "customerName", customerName },
            }
        );
        Debug.Log($"Response Text: {response.Text}");
    }
    catch (Exception e)
    {
        Debug.LogError($"An error occurred: {e.Message}");
    }

    // ...

### **Step 7**: Run the app

Build and run the app and verify that it works. Make changes to your configuration from theRemote Configpage in theFirebaseconsole, publish the changes, and verify the result.

### Next steps

- Learn more about implementing other[use cases forRemote ConfigandFirebase AI Logic](https://firebase.google.com/docs/ai-logic/solutions/remote-config).

- For mobile apps and games:

  - Test your template changes with[Remote ConfigandA/B Testing](https://firebase.google.com/docs/ab-testing/abtest-config).

  - Gradually release changes using[Remote Configrollouts](https://firebase.google.com/docs/remote-config/rollouts)(iOS+ and Android only).

  - Use[Remote Configpersonalization](https://firebase.google.com/docs/remote-config/personalization)to use machine learning to determine the best settings for individual users (iOS+, Android, and Unity only).