使用遠端設定的範本版本


使用伺服器提示詞範本時,您可以特定範本中更新值,不必發布新版應用程式。不過,由於應用程式的請求幾乎會立即使用範本的任何變更,因此請謹慎進行變更,以免導致應用程式中斷或發生非預期的行為變化。

因此,如要進行重大變更或逐步推出變更,請勿變更正式版程式碼中使用的範本。

建議您改用 Firebase Remote Config 控制要求中使用的範本 ID 值

Firebase Remote Config 可讓您從 Firebase 管理中心動態更新應用程式中的參數值 (例如範本 ID),不必發布新版應用程式。此外,這項功能也提供簡化的功能和整合服務,可推出變更並進行 A/B 測試。

本指南說明如何在應用程式中實作 Remote Config,特別是控管應用程式中使用的範本 ID

步驟 1:在 Firebase 控制台中設定參數值

建立 Remote Config 用戶端範本,並設定 template_id 參數及其值,以便在應用程式中擷取及使用。

  1. Firebase 控制台中開啟 Firebase 專案。接著,從導覽選單中展開「執行」,然後選取 Remote Config

  2. 確認已從頁面頂端的「Client/Server」(用戶端/伺服器) 選取器中選取「Client」(用戶端)

  3. 按一下「建立設定」(或「新增參數」,如果您先前使用過用戶端範本),即可開始建立用戶端範本。

  4. 定義 template_id 參數:

    參數名稱 說明 類型 預設值
    template_id 範本 ID。 字串 my-first-template-v1-0-0
  5. 新增這個參數後,請按一下「發布變更」。如果這不是新範本,請查看變更並再次按一下「發布變更」Remote Config

步驟 2:在應用程式中新增及初始化 Remote Config

在應用程式中新增 Remote Config 程式庫,並設定 Remote Config

Swift

Firebase AI Logic設定過程中,您已將 Firebase SDK 新增至應用程式,但還需要新增 Remote Config

  1. 在 Xcode 中開啟專案,然後依序前往「File」>「Add Package Dependencies」

  2. 選取「firebase-ios-sdk」,然後點選「Add package」

  3. 在「Project Navigator」中,依序選取應用程式 >「Targets」 > 應用程式。

  4. 在「一般」分頁中,捲動至「架構、程式庫和內嵌內容」

  5. 按一下「+」,然後選擇「FirebaseRemoteConfig」,再按一下「新增」

  6. 在程式碼中新增 FirebaseRemoteConfig 匯入項目:

    import FirebaseRemoteConfig
    
  7. 在應用程式的適當類別中,初始化 Firebase 並將 Remote Config 加入主要應用程式邏輯。

    您可以在這裡加入 Remote ConfigRemote Config 即時監聽器做為匯入項目,讓應用程式即時擷取新值,並新增最短擷取間隔:

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

Kotlin

  1. Remote Config 依附元件新增至模組 (應用程式層級) Gradle 檔案 (通常為 app/build.gradle.ktsapp/build.gradle):

    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
    }
    
  2. Remote Config 新增至主要應用程式邏輯。在這裡,您將初始化 Remote Config 並新增最短擷取間隔:

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

Java

  1. Remote Config 依附元件新增至模組 (應用程式層級) Gradle 檔案 (通常為 app/build.gradle.ktsapp/build.gradle):

    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
    }
    
  2. Remote Config 新增至主要應用程式邏輯。在這裡,您將初始化 Remote Config 並新增最短擷取間隔:

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

Web

  1. 在文字編輯器中開啟程式碼,然後匯入 Remote Config

    import { getRemoteConfig } from 'firebase/remote-config';
    
  2. 在主要函式中,並在初始化 Firebase 應用程式後,初始化 Firebase AI Logic SDK,請初始化 Remote Config

      // Initialize Remote Config and get a reference to the service
      const remoteConfig = getRemoteConfig(app);
    
  3. 設定最短擷取間隔:

    remoteConfig.settings.minimumFetchIntervalMillis = 3600000;
    

步驟 3:設定應用程式內參數值

您應在 Remote Config 物件中設定應用程式內預設參數值。即使無法從 Remote Config 服務擷取值,應用程式也能正常運作。

Swift

  1. Firebase 控制台中開啟 Remote Config

  2. 在「Parameters」分頁中,開啟「Menu」,然後選取「Download default values」

  3. 系統提示時,請啟用「iOS 的 .plist」,然後按一下「下載檔案」

  4. 將檔案儲存在應用程式目錄中。

  5. 在 Xcode 中,對應用程式按一下滑鼠右鍵,然後選取「Add Files」(新增檔案)

  6. 選取「remote_config_defaults.plist」,然後按一下「新增」

  7. 更新應用程式程式碼,參照預設檔案:

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

Kotlin

  1. Firebase 控制台開啟 Remote Config

  2. 在「Parameters」 分頁中,開啟「Menu」,然後選取「Download default values」

  3. 系統提示時,請啟用「.xml (適用於 Android)」,然後按一下「下載檔案」

  4. 將檔案儲存在應用程式的 XML 資源目錄中。

  5. 更新主要活動檔案,在先前新增的 configSettings 後方加入預設值:

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

Java

  1. Firebase 控制台中開啟 Remote Config

  2. 在「Parameters」 分頁中,開啟「Menu」,然後選取「Download default values」

  3. 系統提示時,請啟用「.xml (適用於 Android)」,然後按一下「下載檔案」

  4. 將檔案儲存在應用程式的 XML 資源目錄中。

  5. 更新主要活動檔案,在先前新增的 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

  1. 在匯入項目中新增 getValuefetchAndActivate

    import { getValue, fetchAndActivate } from 'firebase/remote-config';
    
  2. 找出指定模型名稱預設值的程式碼。 在該程式碼區塊後方,直接新增下列程式碼,以擷取及啟用設定,並將擷取的值指派給 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:更新 Gemini API 要求,使用 Remote Config

按一下 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」頁面中變更設定,發布變更並驗證結果。

後續步驟