כשמשתמשים בתבניות לפרומפטים בשרת, אפשר לעדכן ערכים בתוך תבנית נתונה בלי להשיק גרסה חדשה של האפליקציה. עם זאת, מכיוון שכל שינוי בתבנית ישמש כמעט מיד לבקשות מהאפליקציה, צריך להיזהר כשמבצעים שינויים שעלולים לשבש את האפליקציה או לגרום לשינויים בלתי צפויים בהתנהגות.
לכן, אם אתם רוצים לבצע שינויים משמעותיים יותר או להשיק שינויים בהדרגה, אל תשנו את התבנית שמשמשת בקוד בסביבת הייצור.
במקום זאת, מומלץ להשתמש ב-Firebase Remote Config כדי לשלוט בערך של מזהה התבנית שמשמש בבקשה למודל.
Firebase Remote Config מאפשרת לכם לעדכן ערכי פרמטרים באפליקציה (כמו מזהה התבנית) באופן דינמי ומרחוק דרך מסוף Firebase, בלי שתצטרכו להוציא גרסה חדשה של האפליקציה. יש בה גם יכולות ושילובים יעילים להטמעת שינויים ולבדיקות A/B.
במדריך הזה מוסבר איך להטמיע את Remote Config באפליקציה, ובמיוחד איך לשלוט במזהה התבנית שמשמש באפליקציה.
שלב 1: מגדירים את ערך הפרמטר במסוף Firebase
יוצרים תבנית לקוח של Remote Config ומגדירים פרמטר של template_id ואת הערך שלו כדי לאחזר אותו ולהשתמש בו באפליקציה.
במסוף Firebase, עוברים אל DevOps & Engagement (פיתוח ותפעול ומעורבות) > Remote Config (הגדרת תצורה מרחוק).
בבורר Client/Server שבחלק העליון של הדף, בוחרים באפשרות Client.
כדי להתחיל ליצור תבנית לקוח, לוחצים על Create Configuration (יצירת הגדרה) (או על Add parameter (הוספת פרמטר) אם כבר השתמשתם בתבניות לקוח).
מגדירים את הפרמטר
template_id:שם הפרמטר תיאור סוג ערך ברירת מחדל template_idמזהה התבנית. מחרוזת my-first-template-v1-0-0אחרי שמוסיפים את הפרמטר הזה, לוחצים על פרסום השינויים. אם זו לא תבנית Remote Config חדשה, בודקים את השינויים ולוחצים שוב על פרסום השינויים.
שלב 2: מוסיפים את Remote Config לאפליקציה ומפעילים אותו
מוסיפים את הספרייה Remote Config ומגדירים את Remote Config באפליקציה.
Swift
כחלק מההגדרה של Firebase AI Logic, כבר הוספתם את Firebase SDK לאפליקציה, אבל תצטרכו להוסיף גם את Remote Config.
ב-Xcode, כשהפרויקט פתוח, עוברים אל File > Add Package Dependencies (קובץ > הוספת יחסי תלות של חבילות).
בוחרים באפשרות firebase-ios-sdk ולוחצים על Add package.
ב-Project navigator (ניווט בפרויקט), בוחרים את האפליקציה > Targets (יעדים) > האפליקציה.
בכרטיסייה General, גוללים אל Frameworks, Libraries, and Embedded Content.
לוחצים על +, בוחרים באפשרות FirebaseRemoteConfig ולוחצים על Add (הוספה).
מוסיפים את הייבוא של
FirebaseRemoteConfigלקוד:import FirebaseRemoteConfigבתוך המחלקה המתאימה לאפליקציה, מאתחלים את Firebase ומוסיפים את Remote Config ללוגיקה הראשית של האפליקציה.
כאן תכללו את Remote Config ואת המאזין בזמן אמת של Remote Config כייבוא, כדי שהאפליקציה תוכל לאחזר ערכים חדשים בזמן אמת, ותוסיפו מרווח אחזור מינימלי:
let remoteConfig = RemoteConfig.remoteConfig() let settings = RemoteConfigSettings() settings.minimumFetchInterval = 3600 remoteConfig.configSettings = settings
Kotlin
מוסיפים את התלות ב-Remote Config לקובץ Gradle של המודול (ברמת האפליקציה) (בדרך כלל
app/build.gradle.ktsאוapp/build.gradle):dependencies { implementation(platform("com.google.firebase:firebase-bom:35.1.0")) implementation("com.google.firebase:firebase-ai") implementation("com.google.firebase:firebase-config") // ... other dependencies }מוסיפים את Remote Config ללוגיקה של האפליקציה הראשית. כאן מפעילים את Remote Config ומוסיפים מרווח אחזור מינימלי:
val remoteConfig: FirebaseRemoteConfig = Firebase.remoteConfig val configSettings = remoteConfigSettings { minimumFetchIntervalInSeconds = 3600 } remoteConfig.setConfigSettingsAsync(configSettings)
Java
מוסיפים את התלות ב-Remote Config לקובץ Gradle של המודול (ברמת האפליקציה) (בדרך כלל
app/build.gradle.ktsאוapp/build.gradle):dependencies { implementation(platform("com.google.firebase:firebase-bom:35.1.0")) implementation("com.google.firebase:firebase-ai") implementation("com.google.firebase:firebase-config") // ... other dependencies }מוסיפים את Remote Config ללוגיקה של האפליקציה הראשית. כאן מפעילים את Remote Config ומוסיפים מרווח אחזור מינימלי:
FirebaseRemoteConfig mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance(); FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder() .setMinimumFetchIntervalInSeconds(3600) .build(); mFirebaseRemoteConfig.setConfigSettingsAsync(configSettings);
Web
פותחים את הקוד בכלי לעריכת טקסט ומייבאים את Remote Config:
import { getRemoteConfig } from 'firebase/remote-config';בתוך הפונקציה הראשית, ואחרי שאפליקציית Firebase מופעלת ל-SDK של Firebase AI Logic, מפעילים את Remote Config:
// Initialize Remote Config and get a reference to the service const remoteConfig = getRemoteConfig(app);מגדירים מרווח מינימלי לאחזור:
remoteConfig.settings.minimumFetchIntervalMillis = 3600000;
Dart
בספריית הפרויקט ב-Flutter, מתקינים ומוסיפים את Remote Config באמצעות הפקודה הבאה:
flutter pub add firebase_remote_configפותחים את
./lib/main.dartומוסיפים את הייבוא אחרי הייבואים האחרים שהוספתם כדי לתמוך ב-Firebase AI Logic:import 'package:firebase_ai/firebase_ai.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_remote_config/firebase_remote_config.dart';מוסיפים את המשתנה
_modelNameלאפליקציה כדי שתוכלו להשתמש בו בהמשך:late final String _modelName; late final String _systemInstructions; late final String _prompt;משיגים מופע של אובייקט Remote Config ומגדירים מרווח זמן מינימלי לאחזור כדי לאפשר למערכת לבצע רענון בתדירות גבוהה. חשוב להוסיף את זה אחרי ש-Firebase מאותחל.
final remoteConfig = FirebaseRemoteConfig.instance; await remoteConfig.setConfigSettings(RemoteConfigSettings( fetchTimeout: const Duration(seconds: 3600), minimumFetchInterval: const Duration(seconds: 3600), ));
Unity
מוסיפים את Remote Config לפרויקט Unity לפי ההוראות האלה.
משיגים מופע של אובייקט 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
במסוף Firebase, נכנסים לדף DevOps & Engagement (DevOps ומעורבות) > Remote Config (הגדרת תצורה מרחוק) > Parameters (פרמטרים).
פותחים את
Menu ובוחרים באפשרות Download default values.כשמוצגת בקשה, מפעילים את .plist ל-iOS ולוחצים על הורדת הקובץ.
שומרים את הקובץ בספריית האפליקציה.
ב-Xcode, לוחצים לחיצה ימנית על האפליקציה ובוחרים באפשרות Add Files (הוספת קבצים).
בוחרים באפשרות remote_config_defaults.plist ולוחצים על Add (הוספה).
מעדכנים את קוד האפליקציה כך שיפנה לקובץ ברירות המחדל:
// Set default values for Remote Config parameters. remoteConfig.setDefaults(fromPlist: "remote_config_defaults")
Kotlin
במסוף Firebase, נכנסים לדף DevOps & Engagement (DevOps ומעורבות) > Remote Config (הגדרת תצורה מרחוק) > Parameters (פרמטרים).
פותחים את
Menu ובוחרים באפשרות Download default values.כשמוצגת בקשה, מפעילים את האפשרות .xml ל-Android ולוחצים על הורדת הקובץ.
שומרים את הקובץ בספריית משאבי ה-XML של האפליקציה.
מעדכנים את קובץ הפעילות הראשי כדי להוסיף את ברירות המחדל אחרי ה-
configSettingsשהוספתם קודם:// Set default values for Remote Config parameters. remoteConfig.setDefaultsAsync(R.xml.remote_config_defaults)
Java
במסוף Firebase, נכנסים לדף DevOps & Engagement (DevOps ומעורבות) > Remote Config (הגדרת תצורה מרחוק) > Parameters (פרמטרים).
פותחים את
Menu ובוחרים באפשרות Download default values.כשמוצגת בקשה, מפעילים את האפשרות .xml ל-Android ולוחצים על הורדת הקובץ.
שומרים את הקובץ בספריית משאבי ה-XML של האפליקציה.
מעדכנים את קובץ הפעילות הראשי כדי להוסיף את ברירות המחדל אחרי ה-
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
מוסיפים את
getValueו-fetchAndActivateלייבוא:import { getValue, fetchAndActivate } from 'firebase/remote-config';מאתרים את הקוד שבו מציינים את ערך ברירת המחדל של שם המודל. מיד אחרי בלוק הקוד הזה, מוסיפים את הקוד הבא כדי לאחזר ולהפעיל את ההגדרות ולהקצות את הערך שאוחזר לקבוע
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: הוספת מאזין 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
// 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 FirebaseAILogic
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: templateID,
// Provide the values for any input variables required by your template
templateVariables: {
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, מפרסמים את השינויים ובודקים את התוצאה.
השלבים הבאים
מידע נוסף על הטמעה של תרחישי שימוש אחרים ב-Remote Config וב-Firebase AI Logic
לאפליקציות ולמשחקים לנייד:
בודקים את השינויים בתבנית באמצעות Remote Config ו-A/B Testing.
משיקים שינויים בהדרגה באמצעות השקות של Remote Config (iOS+ ו-Android בלבד).
משתמשים בהתאמה אישית של Remote Config כדי להשתמש בלמידת מכונה ולקבוע את ההגדרות הטובות ביותר למשתמשים ספציפיים (iOS+, Android ו-Unity בלבד).