# Dynamically update your Firebase AI Logic app with Firebase Remote Config

Firebase Remote Config lets you dynamically adjust your app's behavior without requiring app updates. This is especially powerful for apps that use generative AI, where rapid iteration and fine-tuning are crucial.

## Why use Firebase Remote Config with your app?

### Essential use cases for Remote Config with generative AI apps

We recommend using Remote Config with Firebase AI Logic for the following essential use cases:

- **Upgrade to the latest model version without an app update**:
  Use Remote Config parameters to change the model name as needed, so that you can upgrade to the latest version of your preferred Gemini model as soon as it's available.

- **Update system instructions and safety settings without an app update**:
  Store system instructions and safety settings inside Remote Config parameters to ensure that you can change them on-demand if you discover issues after deployment.

- **Reduce risk and enforce AI safety**:
  Use [Remote Config rollouts](/content/docs/remote-config/rollouts/index.html) to safely and gradually release generative AI changes to your iOS and Android users.

### Advanced and recommended use cases for Remote Config with generative AI apps

After instrumenting your app with Remote Config and Google Analytics, you can explore advanced use cases:

- **Set location based on client location**:
  Use Remote Config conditions to [set the location where you access the model](/content/docs/ai-logic/locations?api=vertex/index.html) based on the client's detected location.

- **Experiment with different models**:
  Quickly test and switch between various generative AI models, or even access different models for different user segments, to find the best fit for your specific use case.

- **Optimize model performance**:
  Fine-tune model parameters, such as system prompt, maximum output tokens, temperature, and other settings.

- **Use different system instructions, prompts, and model configurations based on client attributes**:
  When using [Remote Config with Google Analytics](/content/docs/remote-config/config-analytics/index.html), you can create conditions based on client attributes or custom audiences and set different parameters based on these attributes.

- **Personalize experiences for each user**:
  Use [Remote Config personalization](/content/docs/remote-config/personalization/index.html) with your mobile apps and games to automatically determine the optimum generative AI settings for each user.

- **Control costs**:
  Remotely adjust which generative AI models are called, how frequently they are used, and dynamically configure maximum output token values based on user audience to reduce unnecessary costs.

- **Optimize app experience and results**:
  Use [A/B Testing with Remote Config](/content/docs/ab-testing/index.html) with your mobile apps and games to test changes to generative AI parameters across different user segments to see how they affect key metrics like retention and revenue.

By instrumenting your generative AI app with Firebase Remote Config, you can build flexible, safe, and cost-effective AI-powered applications while creating delightful experiences for your users.

## Add Firebase Remote Config to your app

In this solution guide, you'll use Firebase Remote Config to dynamically update parameters in your app that use the Firebase AI Logic SDK. You will learn how to:

- Fetch and activate parameters like model names and system instructions from Firebase Remote Config.
- Update your Gemini API calls to use the dynamically retrieved parameters, letting you switch between different models or modify system instructions without an app update.
- Control parameters remotely, adjusting model behavior and capabilities as needed.

### Prerequisites

This guide assumes that you're familiar with developing apps for your platform.

Before you begin, make sure that you do the following:

- Complete the [Firebase AI Logic getting started guide](/content/docs/ai-logic/get-started/index.html), which describes how to set up your Firebase project, connect your app to Firebase, add the SDK, initialize the backend service for your chosen "Gemini API" provider, and create a model instance.
- Enable [Google Analytics](/content/docs/analytics/index.html) in your Firebase project and add its SDK to your app (required for conditional targeting, like setting the location where you access the model based on the client device's location).

### **Step 1**: Set parameter values in the Firebase console

Create a Remote Config client template and configure parameters and values to fetch and use in the app.

1. In the Firebase console, go to **DevOps & Engagement** > [**Remote Config**](https://console.firebase.google.com/project/_/config).
2. From the **Client/Server** selector at the top of the page, select **Client**.
3. Start a client template by clicking **Create Configuration** (or **Add parameter** if you've previously used client templates).
4. Define the parameters you want to control with Remote Config. For example:
   
   | Parameter name           | Description                                                                                                                                                 | Type   | Default value             |
   |--------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------|--------|---------------------------|
   | `model_name`             | Model name. See [available model names](/content/docs/ai-logic/models#available-model-names/index.html).                                          | String | `gemini-3.8-flash`       |
   | `system_instructions`    | [System instructions](/content/docs/ai-logic/system-instructions/index.html) are like a "preamble" that you add before the model gets exposed to any further instructions from the end user to influence model behavior. | String | `You are a helpful assistant who knows everything there is to know about Firebase!` |
   | `prompt`                 | Default prompt to use with your generative AI feature.                                                                                                     | String | `I am a developer who wants to know more about Firebase!` | 
   | `agent_platform_location` | _Only applicable if using Agent Platform Gemini API (formerly Vertex AI)._ Control the [location](/content/docs/ai-logic/locations?api=vertex/index.html) to access the model. You can set conditions to configure this option based on client location detected by Google Analytics. | String | `global`                 |

5. When you've finished adding parameters, click **Publish changes**. If this is not a new Remote Config template, review the changes and click **Publish changes** again.

### **Step 2**: Add and initialize Remote Config in your app

1. In Xcode, with the project open, navigate to **File > Add Package Dependencies**.
2. Select **firebase-ios-sdk** and then click **Add package**.
3. Add the Remote Config dependency to your module (app-level) Gradle file (usually `app/build.gradle.kts` or `app/build.gradle`).
```kotlin
dependencies {
       implementation(platform("com.google.firebase:firebase-bom:34.19.0"))
       implementation("com.google.firebase:firebase-ai")
       implementation("com.google.firebase:firebase-config")
       // ... other dependencies
}
```
4. Inside the appropriate class for your app, initialize Firebase and add Remote Config to your main application logic:
```swift
let remoteConfig = RemoteConfig.remoteConfig()
let settings = RemoteConfigSettings()
settings.minimumFetchInterval = 3600
remoteConfig.configSettings = settings
```

### **Step 3**: Set in-app parameter values

You should set in-app default parameter values in the Remote Config object. This ensures that your app behaves as expected even if it cannot fetch values from the Remote Config service.

1. In the Firebase console, go to the **DevOps & Engagement** > **Remote Config** > [**Parameters** page](https://console.firebase.google.com/project/_/config).
2. Open the more_vert **Menu**, and select **Download default values**.
3. When prompted, enable **.plist for iOS**, then click **Download file**.
4. Save the file in 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:
```swift
// Set default values for Remote Config parameters.
remoteConfig.setDefaults(fromPlist: "remote_config_defaults")
```

### **Step 4**: Fetch and activate values

After setting defaults, 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)")
  }
}
```

### **Step 5**: Add a real-time Remote Config listener

Add a [real-time Remote Config listener](/content/docs/remote-config/ios/real-time/index.html) to your app to ensure that changes you make to the Remote Config template are propagated to the client as soon as they're updated.

```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")
  }
}
```

### **Step 6**: Update the Gemini API requests to use Remote Config values

Now that Remote Config is fully configured, update your code to replace hard-coded values with values sourced from Remote Config.

```swift
// Initialize the Gemini Developer API backend service
let ai = FirebaseAI.firebaseAI(backend: .googleAI())
let modelName = remoteConfig.configValue(forKey: "model_name").stringValue
let systemInstructions = remoteConfig.configValue(forKey: "system_instructions").stringValue
let userPrompt = remoteConfig.configValue(forKey: "prompt").stringValue
let response = try await model.generateContent(userPrompt)
if let text = response.text {
  print(text)
}
```

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

Build and run the app and verify that it works. Make changes to your configuration from the Remote Config page in the Firebase console, publish the changes, and verify the result.
