Firebase 원격 구성으로 Firebase AI 로직 앱 동적 업데이트

Firebase AI Logic SDK를 사용하여 앱에서 Gemini API를 호출하면 요청에 생성형 AI 응답을 제어하는 여러 파라미터가 포함됩니다. 여기에는 일반적으로 모델 이름, 모델 생성 구성(최대 토큰, 온도 등), 안전 설정, 시스템 안내, 프롬프트 데이터가 포함됩니다.

대부분의 경우 주문형으로 또는 여러 시나리오에 맞게 필요에 따라 변경하는 것이 좋습니다.

  • 새 앱을 출시하지 않고도 생성형 AI 모델을 업데이트할 수 있습니다. 이전 버전이 사용 중단되기 전에 최신 정식 모델 버전으로 업그레이드하거나, 사용자의 요구사항과 속성에 따라 비용이 더 낮거나 성능이 더 우수한 모델로 전환하거나, 최신 모델을 특정 사용자 세그먼트(예: 베타 테스터)에 조건부로 배포할 수 있습니다.
  • 모델에 액세스하는 위치를 사용자와 더 가까운 위치로 설정합니다.
  • 다양한 시스템 안내와 프롬프트에 대해 A/B 테스트를 진행한 후 실험에서 가장 우수한 값을 사용자에게 점진적으로 출시합니다.
  • 기능 플래그를 사용하여 앱에서 생성형 AI 기능을 빠르게 노출하거나 숨깁니다.

Firebase Remote Config은 이 모든 작업을 실행할 수 있으므로 새 버전의 앱을 출시하지 않고도 Firebase Console에서 설정한 특성과 일치하는 앱 인스턴스의 경우 조건부로, 그리고 필요에 따라 파라미터 값을 업데이트할 수 있습니다.

이 솔루션 가이드에서는 권장되는 구체적인 사용 사례를 제공하고 생성형 AI 앱에 Remote Config을 추가하는 방법을 설명합니다.

코드 구현으로 이동

앱에서 Firebase Remote Config을 사용하는 이유는 무엇인가요?

Firebase Remote Config을 사용하면 앱 업데이트 없이 앱의 동작을 동적으로 조정할 수 있습니다. 이는 특히 빠른 반복과 미세 조정이 중요한 생성형 AI를 사용하는 앱에 유용합니다.

생성형 AI 앱을 사용한 Remote Config의 필수 사용 사례

다음과 같은 필수 사용 사례에는 Firebase AI Logic와 함께 Remote Config을 사용하는 것이 좋습니다.

  • 앱 업데이트 없이 최신 모델 버전으로 업그레이드: Remote Config 파라미터를 사용하여 필요에 따라 모델 이름을 변경하면 원하는 Gemini 모델이 출시되는 즉시 최신 버전으로 업그레이드할 수 있습니다.

  • 앱 업데이트 없이 시스템 안내 및 안전 설정 업데이트: Remote Config 매개변수 내에 시스템 안내 및 안전 설정을 저장하여 배포 후 문제를 발견하면 필요에 따라 변경할 수 있도록 합니다.

  • 위험 줄이고 AI 안전 시행: Remote Config 출시를 사용하여 생성형 AI 변경사항을 iOS 및 Android 사용자에게 안전하고 점진적으로 출시합니다.

생성형 AI 앱을 사용한 Remote Config의 고급 및 권장 사용 사례

Remote ConfigGoogle Analytics로 앱을 계측한 후 고급 사용 사례를 살펴볼 수 있습니다.

  • 클라이언트 위치를 기반으로 위치 설정: Remote Config 조건을 사용하여 클라이언트의 감지된 위치를 기반으로 모델에 액세스하는 위치를 설정합니다.

  • 다양한 모델 실험: 다양한 생성형 AI 모델을 빠르게 테스트하고 전환하거나, 다양한 사용자 세그먼트에 서로 다른 모델에 액세스하여 특정 사용 사례에 가장 적합한 모델을 찾을 수 있습니다.

  • 모델 성능 최적화: 시스템 프롬프트, 최대 출력 토큰, 온도, 기타 설정과 같은 모델 파라미터를 미세 조정합니다.

  • 클라이언트 속성에 따라 다양한 시스템 안내, 프롬프트, 모델 구성 사용: Remote ConfigGoogle Analytics를 함께 사용하면 클라이언트 속성 또는 맞춤 잠재고객을 기반으로 조건을 만들고 이러한 속성을 기반으로 다양한 파라미터를 설정할 수 있습니다.

    예를 들어 생성형 AI를 사용하여 앱에서 기술 지원을 제공하는 경우 Android, iOS, 웹 플랫폼 사용자에게 정확한 안내가 제공되도록 앱 플랫폼에 맞는 시스템 안내를 설정하는 것이 좋습니다.

  • 사용자별 환경 맞춤설정: 모바일 앱 및 게임에서 Remote Config 맞춤설정을 사용하여 각 사용자에게 최적의 생성형 AI 설정을 자동으로 결정합니다.

  • 비용 관리: 호출되는 생성형 AI 모델과 사용 빈도를 원격으로 조정하고 사용자 잠재고객을 기반으로 최대 출력 토큰 값을 동적으로 구성하여 불필요한 비용을 줄입니다.

  • 앱 환경 및 결과 최적화: 모바일 앱 및 게임에서 Remote Config으로 A/B Testing을 사용하여 다양한 사용자 세그먼트에서 생성형 AI 파라미터 변경사항을 테스트하고 유지 및 수익과 같은 주요 측정항목에 미치는 영향을 확인합니다.

Firebase Remote Config으로 생성형 AI 앱을 계측하면 유연하고 안전하며 비용 효율적인 AI 기반 애플리케이션을 빌드하는 동시에 사용자에게 만족스러운 환경을 제공할 수 있습니다.

앱에 Firebase Remote Config 추가

이 솔루션 가이드에서는 Firebase Remote Config을 사용하여 Firebase AI Logic SDK를 사용하는 Android 앱의 파라미터를 동적으로 업데이트합니다. 다음을 수행하는 방법을 배우게 됩니다.

  • Firebase Remote Config에서 모델 이름 및 시스템 안내와 같은 파라미터를 가져오고 활성화합니다.
  • 동적으로 검색된 파라미터를 사용하도록 Gemini API 호출을 업데이트하여 앱 업데이트 없이 여러 모델 간에 전환하거나 시스템 안내를 수정할 수 있습니다.
  • 파라미터를 원격으로 제어하여 필요에 따라 모델 동작과 기능을 조정합니다.

기본 요건

이 가이드에서는 개발자가 플랫폼용 앱을 개발하는 데 익숙하다고 가정합니다.

시작하기 전에 다음을 실행해야 합니다.

  • Firebase 프로젝트를 설정하고, 앱을 Firebase에 연결하고, SDK를 추가하고, 선택한 'Gemini API' 제공업체의 백엔드 서비스를 초기화하고, 모델 인스턴스를 만드는 방법을 설명하는 Firebase AI Logic 시작 가이드를 완료합니다.

  • Firebase 프로젝트에서 Google Analytics를 사용 설정하고 앱에 SDK를 추가합니다 (클라이언트 기기의 위치를 기반으로 모델에 액세스하는 위치를 설정하는 것과 같은 조건부 타겟팅에 필요).

1단계: Firebase Console에서 파라미터 값 설정

클라이언트 Remote Config 템플릿을 만들고 앱에서 가져와 사용할 파라미터 및 값을 구성합니다.

  1. Firebase 콘솔에서 Firebase 프로젝트를 엽니다. 그런 다음 탐색 메뉴에서 실행을 펼치고 Remote Config을 선택합니다.
  2. 페이지 상단의 클라이언트/서버 선택기에서 클라이언트가 선택되어 있는지 확인합니다.
  3. 구성 만들기를 클릭하여 클라이언트 템플릿을 시작합니다(이전에 클라이언트 템플릿을 사용한 경우 매개변수 추가).
  4. Remote Config로 제어할 매개변수를 정의합니다. 예를 들면 다음과 같습니다.

    매개변수 이름 설명 유형 기본값
    model_name 모델 이름입니다. 사용 가능한 모델 이름을 참고하세요. 문자열 gemini-2.0-flash
    system_instructions 시스템 안내는 모델 동작에 영향을 미치기 위해 최종 사용자의 추가 안내에 노출되기 전에 추가하는 '프리앰블'과 같습니다. 문자열 You are a helpful assistant who knows everything there is to know about Firebase!
    prompt 생성형 AI 기능과 함께 사용할 기본 프롬프트입니다. 문자열 I am a developer who wants to know more about Firebase!
    vertex_location Vertex AI Gemini API를 사용하는 경우에만 적용됩니다.
    모델에 액세스할 위치를 제어합니다. Google Analytics에서 감지된 클라이언트 위치를 기반으로 이 옵션을 구성하는 조건을 설정할 수 있습니다.
    문자열 us-central1
  5. 파라미터 추가가 완료되면 변경사항 게시를 클릭합니다. 새 Remote Config 템플릿이 아닌 경우 변경사항을 검토하고 변경사항 게시를 다시 클릭합니다.

2단계: 앱에 Remote Config 추가 및 초기화

Remote Config 라이브러리를 추가하고 앱 내에서 Remote Config을 설정합니다.

Swift

Firebase AI Logic 설정의 일환으로 이미 Firebase SDK를 앱에 추가했지만 Remote Config도 추가해야 합니다.

  1. Xcode에서 프로젝트를 연 상태로 파일 > 패키지 종속 항목 추가로 이동합니다.

  2. firebase-ios-sdk를 선택한 다음 패키지 추가를 클릭합니다.

  3. 프로젝트 탐색기에서 앱 > 대상 > 앱을 선택합니다.

  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
    

    빠른 시작 앱에서는 AppDelegate 클래스 내의 VertexAISampleApp 내에 있습니다.

Kotlin

  1. 모듈 (앱 수준) Gradle 파일 (일반적으로 app/build.gradle.kts 또는 app/build.gradle)에 Remote Config 종속 항목을 추가합니다.

    dependencies {
        implementation(platform("com.google.firebase:firebase-bom:33.14.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. 모듈 (앱 수준) Gradle 파일 (일반적으로 app/build.gradle.kts 또는 app/build.gradle)에 Remote Config 종속 항목을 추가합니다.

    dependencies {
        implementation(platform("com.google.firebase:firebase-bom:33.14.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 AI Logic SDK에 대해 Firebase 앱이 초기화된 후 Remote Config을 초기화합니다.

      // Initialize Remote Config and get a reference to the service
      const remoteConfig = getRemoteConfig(app);
    
  3. 가져오기 간격 최솟값을 설정합니다.

    remoteConfig.settings.minimumFetchIntervalMillis = 3600000;
    

Dart

  1. Flutter 프로젝트 디렉터리에서 다음 명령어를 사용하여 Remote Config을 설치하고 추가합니다.

    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, _systemInstructions, _prompt 변수를 추가합니다.

    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. 다음 안내에 따라 Unity 프로젝트에 Remote Config를 추가합니다.

  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 콘솔에서 Remote Config을 엽니다.

  2. 매개변수 탭에서 메뉴를 열고 기본값 다운로드를 선택합니다.

  3. 메시지가 표시되면 iOS의 경우 .plist를 사용 설정하고 파일 다운로드를 클릭합니다.

  4. 애플리케이션 디렉터리에 파일을 저장합니다.

    샘플 앱을 사용하는 경우 FirebaseVertexAI/Sample/VertexAISample 내에 저장합니다.

  5. Xcode에서 앱을 마우스 오른쪽 버튼으로 클릭하고 파일 추가를 선택합니다.

    샘플을 사용하는 경우 VertexAISample을 마우스 오른쪽 버튼으로 클릭하고 'VertexAISample'에 파일 추가를 선택합니다.

  6. remote_config_defaults.plist를 선택한 다음 추가를 클릭합니다.

  7. 기본 파일을 참조하도록 앱 코드를 업데이트합니다.

    // Set default values
    remoteConfig.setDefaults(fromPlist: "remote_config_defaults")
    

Kotlin

  1. Firebase Console에서 Remote Config을 엽니다.

  2. 매개변수 탭에서 메뉴를 열고 기본값 다운로드를 선택합니다.

  3. 메시지가 표시되면 Android의 경우 .xml을 사용 설정한 후 파일 다운로드를 클릭합니다.

  4. 앱의 XML 리소스 디렉터리에 파일을 저장합니다.

  5. 이전에 추가한 configSettings 뒤에 기본값을 추가하도록 기본 활동 파일을 업데이트합니다.

    // Set default values.
    remoteConfig.setDefaultsAsync(R.xml.remote_config_defaults)
    

Java

  1. Firebase 콘솔에서 Remote Config을 엽니다.

  2. 매개변수 탭에서 메뉴를 열고 기본값 다운로드를 선택합니다.

  3. 메시지가 표시되면 Android의 경우 .xml을 사용 설정한 후 파일 다운로드를 클릭합니다.

  4. 앱의 XML 리소스 디렉터리에 파일을 저장합니다.

  5. 이전에 추가한 configSettings 뒤에 기본값을 추가하도록 기본 활동 파일을 업데이트합니다.

    // Set default values.
    mFirebaseRemoteConfig.setDefaultsAsync(R.xml.remote_config_defaults);
    

Web

코드에서 직접 기본값을 설정할 수 있습니다.

// Set default Remote Config parameter values
remoteConfig.defaultConfig = {
  model_name: 'gemini-2.0-flash',
  system_instructions:
    'You are a helpful assistant who knows everything there is to know about Firebase!',
  prompt: 'I am a developer who wants to know more about Firebase!',
  vertex_location: 'us-central1',
};

Dart

코드에서 직접 기본값을 설정할 수 있습니다.

remoteConfig.setDefaults(const {
  "model_name": "gemini-2.0-flash",
  "system_instructions": "You are a helpful assistant who knows everything there is to know about Firebase!",
  "prompt": "I am a developer who wants to know more about Firebase!",
  "vertex_location": "us-central1"
});

Unity

코드에서 직접 기본값을 설정할 수 있습니다.

await remoteConfig.SetDefaultsAsync(
  new System.Collections.Generic.Dictionary<string, object>() {
    { "model_name", "gemini-2.0-flash" },
    { "system_instructions", "You are a helpful assistant who knows everything there is to know about Firebase!" },
    { "prompt", "I am a developer who wants to know more about Firebase!" },
    { "vertex_location", "us-central1" }
  }
);

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. 기본 Remote Config 값을 구성하기 위해 추가한 코드가 실행된 후 구성을 가져와 활성화한 다음 modelName, systemInstructions, prompt, vertexLocation 상수에 값을 할당합니다.

    // 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 modelName = getValue(remoteConfig, 'model_name').asString();
    const systemInstructions = getValue(remoteConfig, 'system_instructions').asString();
    const prompt = getValue(remoteConfig, 'prompt').asString();
    const vertexLocation = getValue(remoteConfig, 'vertex_location').asString();
    

Dart

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

// Assign Remote Config values.
String? _modelName = remoteConfig.getString("model_name");
String? _systemInstructions = remoteConfig.getString("system_instructions");
String? _prompt = remoteConfig.getString("prompt");
String? _vertexLocation = remoteConfig.getString("vertex_location");

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

웹 앱에는 실시간 Remote Config 리스너가 지원되지 않습니다.

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단계: Remote Config 값을 사용하도록 Gemini API 요청 업데이트

Gemini API 제공업체를 클릭하여 이 페이지에서 제공업체별 콘텐츠와 코드를 확인합니다.

이제 Remote Config이 완전히 구성되었으므로 하드코딩된 값을 Remote Config에서 가져온 값으로 대체하도록 코드를 업데이트합니다.

Swift

// Initialize the Gemini Developer API backend service
// The Gemini Developer API doesn't support setting the location of a model
let ai = FirebaseAI.firebaseAI(backend: .googleAI())

// Create a `GenerativeModel` and add system instructions into its config
// Both the model name and the system instructions will be sourced from Remote Config
let modelName = remoteConfig.configValue(forKey: "model_name").stringValue
let systemInstructions = remoteConfig.configValue(forKey: "system_instructions").stringValue

let model = ai.generativeModel(
  modelName: modelName,
  systemInstruction: ModelContent(role: "system", parts: systemInstructions)
)

// Provide a prompt that contains text
// The text in the prompt will be sourced from Remote Config
let userPrompt = remoteConfig.configValue(forKey: "prompt").stringValue

// To generate text output, call `generateContent` with the text input
let response = try await model.generateContent(userPrompt)
if let text = response.text {
  print(text)
}

Kotlin

// Initialize the Gemini Developer API backend service
// The Gemini Developer API doesn't support setting the location of a model
val ai = Firebase.ai(backend = GenerativeBackend.googleAI())

// Create a `GenerativeModel` and add system instructions into its config
// Both the model name and the system instructions will be sourced from Remote Config
val model = ai.generativeModel(
  modelName = remoteConfig.getString("model_name"),
  systemInstruction = content { text(remoteConfig.getString("system_instructions")) }
)

// To generate text output, call `generateContent` with the text input
// The text in the prompt will be sourced from Remote Config
val response = model.generateContent(remoteConfig.getString("prompt"))
print(response.text)

Java

// Initialize the Gemini Developer API backend service
// The Gemini Developer API doesn't support setting the location of a model
FirebaseAI ai = FirebaseAI.getInstance(GenerativeBackend.googleAI());

// Create a `GenerativeModel` and add system instructions into its config
// Both the model name and the system instructions will be sourced from Remote Config
GenerativeModel gm = ai.generativeModel(
        /* modelName */ remoteConfig.getString("model_name"),
        /* generationConfig (optional) */ null,
        /* safetySettings (optional) */ null,
        /* tools (optional) */ null,
        /* toolsConfig (optional) */ null,
        /* systemInstruction (optional) */ new Content.Builder().addText(
                remoteConfig.getString("system_instructions")).build(),
        /* requestOptions (optional) */ new RequestOptions()
);
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

// Provide a prompt that contains text
// The text in the prompt will be sourced from Remote Config
Content userPrompt = new Content.Builder()
        .addText(remoteConfig.getString("prompt"))
        .build();

// To generate text output, call `generateContent` with the text input
ListenableFuture<GenerateContentResponse> response = model.generateContent(userPrompt);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
    @Override
    public void onSuccess(GenerateContentResponse result) {
        String resultText = result.getText();
        System.out.println(resultText);
    }

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
}, executor);

Web

// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service
// The Gemini Developer API doesn't support setting the location of a model
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Create a `GenerativeModel` and add system instructions into its config
// Both the model name and the system instructions will be sourced from Remote Config
const model = getGenerativeModel(ai, {
  model: modelName,
  systemInstruction: systemInstruction
});

// Wrap in an async function so you can use await
async function run() {
  // Provide a prompt that contains text
  // The text in the prompt will be sourced from Remote Config
  const userPrompt = prompt;

  // To generate text output, call `generateContent` with the text input
  const result = await model.generateContent(userPrompt);

  const response = result.response;
  const text = response.text();
  console.log(text);
}

Dart

// Initialize the Gemini Developer API backend service
// The Gemini Developer API doesn't support setting the location of a model
final ai = await FirebaseAI.googleAI();

// Create a `GenerativeModel` and add system instructions into its config
// Both the model name and the system instructions will be sourced from Remote Config
final model =
      ai.generativeModel(
        model: _modelName,
        systemInstruction: Content.system(_systemInstructions),
      );

// Provide a prompt that contains text
// The text in the prompt will be sourced from Remote Config
final _userPrompt = [Content.text(_prompt)];

// To generate text output, call `generateContent` with the text input
final response = await model.generateContent(_userPrompt);
print(response.text);

Unity

// Initialize the Gemini Developer API backend service
// The Gemini Developer API doesn't support setting the location of a model
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());

// Create a `GenerativeModel` and add system instructions into its config
// Both the model name and the system instructions will be sourced from Remote Config
var modelName = remoteConfig.GetValue("model_name").StringValue;
var systemInstructions = remoteConfig.GetValue("system_instructions").StringValue;

var model = ai.GetGenerativeModel(
  modelName: modelName,
  systemInstruction: ModelContent.Text(systemInstructions)
);

// Provide a prompt that contains text
// The text in the prompt will be sourced from Remote Config
var userPrompt = remoteConfig.GetValue("prompt").StringValue;

// To generate text output, call `GenerateContentAsync` with the text input
var response = await model.GenerateContentAsync(userPrompt);
UnityEngine.Debug.Log(response.Text ?? "No text in response.");

7단계: 앱 실행

앱을 빌드하고 실행하여 작동하는지 확인합니다. Firebase Console의 Remote Config 페이지에서 구성을 변경하고 변경사항을 게시한 후 결과를 확인합니다.

다음 단계

  • Remote Config를 자세히 알아보세요.

  • 클라이언트 코드에 Google Analytics를 추가하여 타겟팅을 사용 설정합니다.

  • 모바일 앱 및 게임의 경우:

    • Remote ConfigA/B Testing로 다양한 모델 설정을 테스트합니다.

    • Remote Config 출시를 사용하여 모델 파라미터 변경사항을 점진적으로 출시합니다 (iOS+ 및 Android만 해당).

    • Remote Config 맞춤설정을 사용하여 머신러닝을 통해 개별 사용자에게 가장 적합한 설정을 결정합니다 (iOS+, Android, Unity만 해당).