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


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

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

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

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

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

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

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

  1. ในคอนโซลFirebase ให้ไปที่DevOps และการมีส่วนร่วม > การกำหนดค่าระยะไกล

  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 แล้วคลิก Add package

  3. เลือกแอป > Targets > แอปของคุณจากตัวนำทางโปรเจ็กต์

  4. จากแท็บ General ให้เลื่อนไปที่ Frameworks, Libraries, and Embedded Content

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

  6. เพิ่มการนำเข้า FirebaseRemoteConfig ลงในโค้ด

    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.13.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.13.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;
    

Dart

  1. ติดตั้งและเพิ่ม Remote Config จากไดเรกทอรีโปรเจ็กต์ Flutter โดยใช้คำสั่งต่อไปนี้

    flutter pub add firebase_remote_config
    
  2. เปิด ./lib/main.dart และเพิ่มการนำเข้าหลังจากการนำเข้าอื่นๆ ที่คุณ เพิ่มเพื่อรองรับ Firebase 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. เพิ่มตัวแปร _modelName ลงในแอปเพื่อให้คุณใช้ตัวแปรนี้ได้ในภายหลัง

    late final String _modelName;
    late final String _systemInstructions;
    late final String _prompt;
    
  4. สร้างอินสแตนซ์ออบเจ็กต์ Remote Config แล้วตั้งช่วงการดึงข้อมูล ขั้นต่ำเพื่อให้มีการรีเฟรชบ่อยๆ อย่าลืมเพิ่มอินสแตนซ์นี้หลังจากเริ่มต้น Firebase แล้ว

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

Unity

  1. เพิ่ม Remote Config ลงในโปรเจ็กต์ Unity โดยทำตาม วิธีการต่อไปนี้

  2. สร้างอินสแตนซ์ออบเจ็กต์ Remote Config แล้วตั้งช่วงการดึงข้อมูล ขั้นต่ำเพื่อให้มีการรีเฟรชบ่อยๆ อย่าลืมเพิ่มอินสแตนซ์นี้หลังจากเริ่มต้น Firebase แล้ว

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

ขั้นตอนที่ 3: ตั้งค่าพารามิเตอร์ในแอป

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

Swift

  1. ในคอนโซล Firebase ให้ไปที่หน้า DevOps และการมีส่วนร่วม > การกำหนดค่าระยะไกล > พารามิเตอร์

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

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

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

  5. ใน Xcode ให้คลิกขวาที่แอป แล้วเลือกAdd Files

  6. เลือก remote_config_defaults.plist แล้วคลิก Add

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

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

Kotlin

  1. ในคอนโซล Firebase ให้ไปที่หน้า DevOps และการมีส่วนร่วม > การกำหนดค่าระยะไกล > พารามิเตอร์

  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 ให้ไปที่หน้า DevOps และการมีส่วนร่วม > การกำหนดค่าระยะไกล > พารามิเตอร์

  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',
};

Dart

คุณตั้งค่าเริ่มต้นสำหรับชื่อโมเดลได้โดยตรงในโค้ด

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

Unity

คุณตั้งค่าเริ่มต้นสำหรับชื่อโมเดลได้โดยตรงในโค้ด

// 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" }
  }
);

ขั้นตอนที่ 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();
    

Dart

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

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

Unity

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

ขั้นตอนที่ 5: เพิ่ม Listener แบบเรียลไทม์Remote Config

เพิ่ม Listener 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

 // Add a real-time Remote Config listener
 onConfigUpdate(remoteConfig, {
   next: (configUpdate) => {
      console.log("Updated keys:", configUpdate.getUpdatedKeys());
      if (configUpdate.getUpdatedKeys().has("welcome_message")) {
         activate(remoteConfig).then(() => {
         showWelcomeMessage();
         });
      }
   },
   error: (error) => {
      console.log("Config update error:", error);
   },
   complete: () => {
      console.log("Listening stopped.");
   }
});

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

ขั้นตอนที่ 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(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}");
}

// ...

ขั้นตอนที่ 7: เรียกใช้แอป

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

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