เทมเพลตเวอร์ชันโดยใช้การกำหนดค่าระยะไกล


เมื่อใช้เทมเพลตพรอมต์ของเซิร์ฟเวอร์ คุณจะอัปเดตค่าภายในเทมเพลตที่กำหนดได้โดยไม่ต้องเผยแพร่แอปเวอร์ชันใหม่ อย่างไรก็ตาม เนื่องจากระบบจะใช้การเปลี่ยนแปลงใดๆ กับเทมเพลตในการคำขอจากแอปของคุณในทันที คุณจึงต้องระมัดระวังในการทำการเปลี่ยนแปลงที่อาจทำให้แอปใช้งานไม่ได้หรือทำให้เกิดการเปลี่ยนแปลงลักษณะการทำงานที่ไม่คาดคิด

ดังนั้น หากต้องการทำการเปลี่ยนแปลงที่สำคัญมากขึ้นหรือค่อยๆ เปิดตัวการเปลี่ยนแปลง คุณก็ไม่ควรเปลี่ยนเทมเพลตที่ใช้ในโค้ดเวอร์ชันที่ใช้งานจริง

เราขอแนะนำให้ใช้ Firebase Remote Config เพื่อควบคุมค่าของ รหัสเทมเพลตที่ใช้ในคำขอไปยังโมเดลแทน

Firebase Remote Config ช่วยให้คุณอัปเดตค่าพารามิเตอร์ ในแอป (เช่น รหัสเทมเพลต) แบบไดนามิกและจากระยะไกลจากคอนโซล Firebase โดยไม่ต้องเผยแพร่แอปเวอร์ชันใหม่ นอกจากนี้ ยังมีฟีเจอร์และการผสานรวมที่ปรับปรุงแล้วสำหรับการเปิดตัวการเปลี่ยนแปลง รวมถึงการทดสอบ A/B

คู่มือนี้อธิบายวิธีติดตั้งใช้งาน Remote Config ในแอป โดยเฉพาะเพื่อควบคุมรหัสเทมเพลตที่ใช้ในแอป

ขั้นตอนที่ 1: ตั้งค่าพารามิเตอร์ในคอนโซล Firebase

สร้างRemote Configเทมเพลตไคลเอ็นต์และกำหนดค่าtemplate_id พารามิเตอร์และค่าของพารามิเตอร์เพื่อดึงข้อมูลและใช้ในแอป

  1. เปิดโปรเจ็กต์ Firebase ในFirebaseคอนโซล จากนั้นจากเมนูการนำทาง ให้ขยายเรียกใช้ แล้วเลือก Remote Config

  2. ตรวจสอบว่าได้เลือกไคลเอ็นต์จากตัวเลือกไคลเอ็นต์/เซิร์ฟเวอร์ ที่ด้านบนของหน้า

  3. เริ่มเทมเพลตไคลเอ็นต์โดยคลิกสร้างการกำหนดค่า (หรือเพิ่มพารามิเตอร์หากเคยใช้เทมเพลตไคลเอ็นต์มาก่อน)

  4. กำหนดพารามิเตอร์ template_id ดังนี้

    ชื่อพารามิเตอร์ คำอธิบาย ประเภท ค่าเริ่มต้น
    template_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 แล้วคลิกเพิ่มแพ็กเกจ

  3. จากแถบนำทางของโปรเจ็กต์ ให้เลือกแอป > เป้าหมาย > แอปของคุณ

  4. จากแท็บทั่วไป ให้เลื่อนไปที่เฟรมเวิร์ก ไลบรารี และ เนื้อหาที่ฝัง

  5. คลิก + แล้วเลือก FirebaseRemoteConfig จากนั้นคลิกเพิ่ม

  6. เพิ่ม FirebaseRemoteConfig import ลงในโค้ด

    import FirebaseRemoteConfig
    
  7. ภายในคลาสที่เหมาะสมสำหรับแอป ให้เริ่มต้น Firebase และเพิ่ม Remote Configลงในตรรกะของแอปพลิเคชันหลัก

    ในส่วนนี้ คุณจะรวม Remote Config และ Remote Config Listener แบบเรียลไทม์เป็น การนำเข้าเพื่อให้แอปดึงค่าใหม่ได้แบบเรียลไทม์ และเพิ่ม ช่วงเวลาการดึงข้อมูลขั้นต่ำ

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

Kotlin

  1. เพิ่มทรัพยากร Dependency Remote Config ลงในไฟล์ Gradle ระดับโมดูล (ระดับแอป) (โดยปกติคือ app/build.gradle.kts หรือ app/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. เพิ่มทรัพยากร Dependency Remote Config ลงในไฟล์ Gradle ระดับโมดูล (ระดับแอป) (โดยปกติคือ app/build.gradle.kts หรือ app/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. ในแท็บพารามิเตอร์ ให้เปิดเมนู แล้วเลือกดาวน์โหลดค่าเริ่มต้น

  3. เมื่อได้รับข้อความแจ้ง ให้เปิดใช้ .plist สำหรับ iOS แล้วคลิกดาวน์โหลดไฟล์

  4. บันทึกไฟล์ในไดเรกทอรีแอปพลิเคชัน

  5. ใน Xcode ให้คลิกขวาที่แอปแล้วเลือกเพิ่มไฟล์

  6. เลือก remote_config_defaults.plist แล้วคลิกเพิ่ม

  7. อัปเดตโค้ดของแอปเพื่ออ้างอิงไฟล์ค่าเริ่มต้น

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

Kotlin

  1. เปิด Remote Config จากคอนโซล Firebase

  2. ในแท็บพารามิเตอร์ ให้เปิดเมนู แล้วเลือกดาวน์โหลดค่าเริ่มต้น

  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. ในแท็บพารามิเตอร์ ให้เปิดเมนู แล้วเลือกดาวน์โหลดค่าเริ่มต้น

  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. เพิ่ม getValue และ fetchAndActivate ลงในการนำเข้า

    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: เรียกใช้แอป

สร้างและเรียกใช้แอป แล้วตรวจสอบว่าแอปทำงานได้ ทำการเปลี่ยนแปลงการกำหนดค่าจากหน้า Remote Config ในคอนโซล Firebase เผยแพร่การเปลี่ยนแปลง และยืนยันผลลัพธ์

ขั้นตอนถัดไป