Перейдите непосредственно к инструкциям по миграции.
Почему стоит перейти на использование SDK Firebase AI Logic ?
Возможно, вы уже пробовали альтернативный набор SDK для мобильных или веб-приложений, который предоставлял вам доступ к API разработчика Gemini .
Эти клиентские SDK не были интегрированы в мощную экосистему Firebase, предоставляющую критически важные сервисы для мобильных и веб-приложений. Теперь они устарели в пользу клиентских SDK Firebase AI Logic , которые предоставляют доступ к API разработчика Gemini .
Функции безопасности для мобильных и веб-приложений
Для мобильных и веб-приложений безопасность имеет решающее значение и требует особого внимания, поскольку ваш код, включая вызовы к API Gemini , выполняется в незащищенной среде. Вы можете использовать Firebase App Check для защиты API от злоупотреблений со стороны неавторизованных клиентов.
При использовании Firebase App Check с Firebase AI Logic вы никогда не добавляете свой ключ API Gemini для Gemini Developer API непосредственно в код вашего мобильного или веб-приложения. Вместо этого ключ API Gemini остается на сервере, недоступном для злоумышленников.
Экосистема, созданная для мобильных и веб-приложений.
Firebase — это платформа Google для разработки мобильных и веб-приложений. Использование Firebase AI Logic означает, что ваши приложения находятся в экосистеме, ориентированной на потребности разработчиков и разработчиков, работающих с полным стеком технологий. Например:
С помощью Firebase Remote Config вы можете динамически устанавливать параметры во время выполнения или заменять значения в вашем приложении (например, имя модели и версию) без выпуска новой версии приложения.
Используйте Cloud Storage for Firebase для включения больших файлов в ваши многомодальные запросы (если вы используете API Agent Platform Gemini (ранее Vertex AI) ). Клиентские SDK Cloud Storage помогут вам обрабатывать загрузку и скачивание файлов (даже в условиях плохой сети) и обеспечат более высокую безопасность данных ваших конечных пользователей. Подробнее см. в нашем руководстве по использованию Cloud Storage for Firebase .
Управляйте структурированными данными с помощью SDK для баз данных, разработанных для мобильных и веб-приложений (например, Cloud Firestore ).
Переход на SDK Firebase AI Logic
Обзор шагов по миграции на SDK Firebase AI Logic :
Шаг 1 : Создайте новый или подключите существующий проект Firebase к Firebase.
Шаг 2 : Добавьте SDK Firebase AI Logic в ваше приложение.
Шаг 3 : Обновите импорт и инициализацию в вашем приложении.
Шаг 4 : Обновите свой код в зависимости от используемых вами функций.
Шаг 1 : Создайте проект Firebase и подключите к нему ваше приложение.
Войдите в консоль Firebase , а затем выберите свой проект Firebase.
Если у вас еще нет проекта Firebase, нажмите кнопку для создания нового проекта Firebase, а затем воспользуйтесь одним из следующих вариантов:
Вариант 1 : Создайте совершенно новый проект Firebase (и автоматически сформируйте для него базовый проект Google Cloud ), указав новое имя проекта на первом шаге рабочего процесса.
Вариант 2 : "Добавить Firebase" в существующий проект Google Cloud , нажав кнопку "Добавить Firebase в проект Google Cloud" (внизу страницы). На первом шаге процесса начните вводить название существующего проекта, а затем выберите проект из отображаемого списка.
При желании вы можете добавить Firebase в проект, который был создан автоматически при создании ключа API Gemini в Google AI Studio .
Выполните оставшиеся шаги отображаемого на экране процесса, чтобы создать проект Firebase. Обратите внимание, что при появлении соответствующего запроса вам не потребуется настраивать Google Analytics для использования SDK Firebase AI Logic .
В консоли Firebase перейдите в раздел AI Services > AI Logic .
Нажмите « Начать» , чтобы запустить пошаговый рабочий процесс, который поможет вам настроить необходимые API и ресурсы для вашего проекта.
Выберите API разработчика Gemini . При желании вы всегда сможете настроить и использовать другой поставщик API позже.
Консоль активирует необходимые API и создаст новый, выделенный ключ API Gemini в вашем проекте.
Не добавляйте этот новый ключ API Gemini в код вашего приложения. Узнайте больше.Если в процессе работы консоли появится соответствующее сообщение, следуйте инструкциям на экране, чтобы зарегистрировать ваше приложение и подключить его к Firebase.
Продолжите выполнение инструкций в этом руководстве по миграции, чтобы обновить библиотеку и выполнить инициализацию в вашем приложении.
Шаг 2 : Добавьте SDK Firebase AI Logic в ваше приложение.
После настройки проекта Firebase и подключения приложения к Firebase (см. предыдущий шаг) вы можете добавить SDK Firebase AI Logic в свое приложение.
Быстрый
Используйте Swift Package Manager для установки и управления зависимостями Firebase. При необходимости ознакомьтесь с другими вариантами установки .
Библиотека Firebase AI Logic предоставляет доступ к API для взаимодействия с моделями Gemini . Библиотека входит в состав Firebase SDK для платформ Apple ( firebase-ios-sdk ).
Если вы уже используете Firebase, убедитесь, что версия вашего пакета Firebase — 12.5.0 или более поздняя.
В Xcode, открыв проект приложения, перейдите в меню File > Add Package Dependencies .
При появлении запроса добавьте репозиторий Firebase Apple Platforms SDK:
https://github.com/firebase/firebase-ios-sdkВыберите последнюю версию SDK.
Выберите библиотеку
FirebaseAILogicи библиотекуFirebaseAppCheck.
После завершения Xcode автоматически начнет разрешение и загрузку ваших зависимостей в фоновом режиме.
Kotlin
SDK Firebase AI Logic для Android ( firebase-ai ) предоставляет доступ к API для взаимодействия с моделями Gemini .
В файле Gradle вашего модуля (уровня приложения) (например, <project>/<app-module>/build.gradle.kts ) добавьте зависимости для библиотек Firebase AI Logic и App Check для Android. Мы рекомендуем использовать Firebase Android BoM для управления версиями библиотек.
dependencies { // ... other androidx dependencies // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.18.0")) // Add the dependencies for the Firebase AI Logic and App Check libraries // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-ai") implementation("com.google.firebase:firebase-appcheck-debug") }
Использование Firebase Android BoM , что ваше приложение всегда будет использовать совместимые версии библиотек Firebase Android.
Если вы решите не использовать Firebase BoM , вам необходимо указать версию каждой библиотеки Firebase в строке зависимости.
Обратите внимание, что если вы используете несколько библиотек Firebase в своем приложении, мы настоятельно рекомендуем использовать BoM для управления версиями библиотек, что гарантирует совместимость всех версий.
dependencies { // Add the dependencies for the Firebase AI Logic and App Check libraries // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-ai:17.16.0") implementation("com.google.firebase:firebase-appcheck-debug:19.4.1") }
Java
SDK Firebase AI Logic для Android ( firebase-ai ) предоставляет доступ к API для взаимодействия с моделями Gemini .
В файле Gradle вашего модуля (уровня приложения) (например, <project>/<app-module>/build.gradle.kts ) добавьте зависимости для библиотек Firebase AI Logic и App Check для Android. Мы рекомендуем использовать Firebase Android BoM для управления версиями библиотек.
Для Java необходимо добавить две дополнительные библиотеки.
dependencies { // ... other androidx dependencies // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.18.0")) // Add the dependencies for the Firebase AI Logic and App Check libraries // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-ai") implementation("com.google.firebase:firebase-appcheck-debug") // Required for one-shot operations (to use `ListenableFuture` from Guava Android) implementation("com.google.guava:guava:31.0.1-android") // Required for streaming operations (to use `Publisher` from Reactive Streams) implementation("org.reactivestreams:reactive-streams:1.0.4") }
Использование Firebase Android BoM , что ваше приложение всегда будет использовать совместимые версии библиотек Firebase Android.
Если вы решите не использовать Firebase BoM , вам необходимо указать версию каждой библиотеки Firebase в строке зависимости.
Обратите внимание, что если вы используете несколько библиотек Firebase в своем приложении, мы настоятельно рекомендуем использовать BoM для управления версиями библиотек, что гарантирует совместимость всех версий.
dependencies { // Add the dependencies for the Firebase AI Logic and App Check libraries // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-ai:17.16.0") implementation("com.google.firebase:firebase-appcheck-debug:19.4.1") }
Web
Библиотека Firebase AI Logic предоставляет доступ к API для взаимодействия с моделями Gemini . Библиотека входит в состав Firebase JavaScript SDK для веб-приложений.
Установите Firebase JS SDK для веб-разработки с помощью npm:
npm install firebaseИнициализируйте Firebase в своем приложении:
import { initializeApp } from "firebase/app"; import { initializeAppCheck, DebugProvider } from "firebase/app-check"; // TODO(developer) Replace the following with your app's Firebase configuration // See: https://firebase.google.com/docs/web/learn-more#config-object const firebaseConfig = { // ... }; // Initialize FirebaseApp const firebaseApp = initializeApp(firebaseConfig);
Dart
Плагин Firebase AI Logic для Flutter ( firebase_ai ) предоставляет доступ к API для взаимодействия с моделями Gemini .
Для установки плагинов Firebase AI Logic и App Check из каталога вашего проекта Flutter выполните следующую команду:
flutter pub add firebase_ai firebase_app_checkВ файле
lib/main.dartимпортируйте плагины Firebase AI Logic и App Check :import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_ai/firebase_ai.dart'; import 'package:firebase_app_check/firebase_app_check.dart'; import 'firebase_options.dart';Также в файле
lib/main.dartубедитесь, что вы инициализировали Firebase, используя объектDefaultFirebaseOptions, экспортируемый из файла конфигурации:await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, );Пересоберите ваше Flutter-приложение:
flutter run
Единство
Поддержка Unity отсутствовала в SDK клиента Google AI .
Узнайте, как начать работу с Firebase AI Logic SDK для Unity .
Удалите старый SDK из вашего приложения.
После завершения миграции приложения (см. остальные разделы этого руководства) обязательно удалите старую библиотеку.
Быстрый
Удалите старую библиотеку:
В Xcode, открыв проект приложения, перейдите в панель «Пакеты и зависимости» .
Выберите пакет
generative-ai-swiftиз списка зависимостей пакетов.Нажмите кнопку
-внизу списка и нажмите «Удалить» для подтверждения.
Kotlin
dependencies {
implementation("com.google.ai.client.generativeai:generativeai:VERSION")
}
Java
dependencies {
implementation("com.google.ai.client.generativeai:generativeai:VERSION")
}
Web
// BEFORE
import { initializeApp } from "firebase/app";
import { GoogleGenerativeAI } from "@google/generative-ai";
Dart
Удалите старый пакет:
flutter pub remove google_generative_ai
Единство
Поддержка Unity отсутствовала в клиентских SDK Google AI .
Узнайте, как начать работу с Firebase AI Logic SDK для Unity .
Шаг 3 : Обновите импорт и инициализацию в вашем приложении.
Обновите импорт и способ инициализации бэкэнд-сервиса Gemini Developer API , а также создайте экземпляр GenerativeModel .
Быстрый
// BEFOREimport GoogleGenerativeAI let model = GenerativeModel(name: "MODEL_NAME", apiKey: APIKey.default)// AFTER import FirebaseAILogic // Initialize the Gemini Developer API backend service let ai = FirebaseAI.firebaseAI(backend: .googleAI()) // Create a `GenerativeModel` instance with a model that supports your use case let model = ai.generativeModel(modelName: "gemini-3.7-flash")
Kotlin
// BEFOREimport com.google.ai.client.generativeai.Chat import com.google.ai.client.generativeai.type.Content import com.google.ai.client.generativeai.java.GenerativeModuleFutures...val generativeModel = GenerativeModel(modelName = "MODEL_NAME", // Access your API key as a Build Configuration variable apiKey = BuildConfig.apiKey )// AFTER import com.google.firebase.Firebase import com.google.firebase.ai.ai import com.google.firebase.ai.type.GenerativeBackend ... // Initialize the Gemini Developer API backend service. // Create a `GenerativeModel` instance with a model that supports your use case. val model = Firebase.ai(backend = GenerativeBackend.googleAI()) .generativeModel("gemini-3.7-flash")
Java
// BEFOREimport com.google.ai.client.generativeai.Chat; import com.google.ai.client.generativeai.type.Content; import com.google.ai.client.generativeai.java.GenerativeModuleFutures;...GenerativeModel gm = new GenerativeModel("MODEL_NAME", // Access your API key as a Build Configuration variable BuildConfig.apiKey ); GenerativeModelFutures model = GenerativeModelFutures.from(gm);// AFTER import com.google.firebase.ai.FirebaseAI; import com.google.firebase.ai.GenerativeModel; import com.google.firebase.ai.java.GenerativeModelFutures; import com.google.firebase.ai.type.GenerativeBackend; ... // Initialize the Gemini Developer API backend service. // Create a `GenerativeModel` instance with a model that supports your use case. GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI()) .generativeModel("gemini-3.7-flash"); // Use the GenerativeModelFutures Java compatibility layer which offers // support for ListenableFuture and Publisher APIs GenerativeModelFutures model = GenerativeModelFutures.from(ai);
Web
// BEFOREimport { GoogleGenerativeAI } from "@google/generative-ai"; // Fetch your API_KEY and access your API const API_KEY = "..."; const genAI = new GoogleGenerativeAI(API_KEY);...const model = genAI.getGenerativeModel({ model: "MODEL_NAME"});// AFTER import { initializeApp } from "firebase/app"; import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai"; // TODO(developer): Replace the following with your app's Firebase configuration // See: https://firebase.google.com/docs/web/learn-more#config-object const firebaseConfig = { // ... }; // Initialize FirebaseApp const firebaseApp = initializeApp(firebaseConfig); // Initialize the Gemini Developer API backend service. const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() }); // Create a `GenerativeModel` instance with a model that supports your use case. const model = getGenerativeModel(ai, { model: "gemini-3.7-flash" });
Dart
// BEFOREimport 'package:google_generative_ai/google_generative_ai.dart'; final apiKey = Platform.environment['API_KEY']; if (apiKey == null) { print('No \$API_KEY environment variable'); exit(1); } final model = GenerativeModel(model: 'MODEL_NAME', apiKey: apiKey);// AFTER import 'package:firebase_ai/firebase_ai.dart'; import 'package:firebase_core/firebase_core.dart'; import 'firebase_options.dart'; // Initialize FirebaseApp await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); // Initialize the Gemini Developer API backend service // Create a `GenerativeModel` instance with a model that supports your use case final model = FirebaseAI.googleAI().generativeModel(model: 'gemini-3.7-flash');
Единство
Поддержка Unity отсутствовала в клиентских SDK Google AI .
Узнайте, как начать работу с Firebase AI Logic SDK для Unity .
Обратите внимание, что в зависимости от используемых возможностей вам может не всегда потребоваться создать экземпляр GenerativeModel . Для потоковой передачи входных и выходных данных с помощью Gemini Live API создайте экземпляр LiveModel .
Шаг 4 : Обновите код в зависимости от используемых вами функций.
На этом шаге описываются изменения, которые могут потребоваться в зависимости от используемых вами функций.
SDK клиента Firebase AI Logic не поддерживают выполнение кода. Если вы используете эту функцию, убедитесь, что она учтена в вашем приложении.
Ознакомьтесь со следующими списками, чтобы узнать, какие изменения вам, возможно, потребуется внести в свой код для перехода на клиентские SDK Firebase AI Logic .
Требуется для всех языков и платформ.
Вызов функции
Если вы реализовали эту функцию, вам потребуется внести изменения в определение схемы. Мы рекомендуем ознакомиться с обновленным руководством по вызову функций , чтобы узнать, как правильно писать объявления функций.Генерация структурированного вывода (например, в формате JSON) с использованием
responseSchema
Если вы внедрили эту функцию, вам потребуется внести изменения в определение схемы. Мы рекомендуем ознакомиться с новым руководством по структурированному выводу, чтобы узнать, как писать JSON-схемы.Тайм-аут
- Изменено значение тайм-аута по умолчанию для запросов на 180 секунд.
Требуется в зависимости от платформы или языка.
Быстрый
Перечисления
Большинство типов
enumзамененыstructсо статическими переменными. Это изменение обеспечивает большую гибкость при развитии API с сохранением обратной совместимости. При использовании операторовswitchтеперь необходимо указывать значениеdefault:case) для обработки неизвестных или необработанных значений, включая новые значения, которые будут добавлены в SDK в будущем.Переименование перечисления
BlockThresholdвHarmBlockThreshold; теперь этот тип являетсяstruct.Из следующих перечислений (теперь
struct) удаленыunknownиunspecifiedслучаи:HarmCategory,HarmBlockThreshold,HarmProbability,BlockReasonиFinishReason.Заменено перечисление
ModelContent.Partпротоколом с именемPart, позволяющим добавлять новые типы с сохранением обратной совместимости. Это изменение более подробно описано в разделе «Части контента» .
Содержание
Удалён протокол
ThrowingPartsRepresentable, а инициализаторы дляModelContentупрощены, чтобы избежать случайных ошибок компиляции. Изображения, которые некорректно кодируются, по-прежнему будут вызывать ошибки при использовании вgenerateContent.Заменены экземпляры
ModelContent.Partследующимиstructтипами, соответствующими протоколуPart:-
.texttoTextPart -
.datatoInlineDataPart -
.fileDatatoFileDataPart -
.functionCalltoFunctionCallPart -
.functionResponsetoFunctionResponsePart
-
Категория вреда
- Изменено представление
HarmCategoryтаким образом, чтобы оно больше не было вложено в типSafetySetting. Если вы имеете в видуSafetySetting.HarmCategory, то это можно заменить наHarmCategory.
- Изменено представление
Обратная связь по вопросам безопасности
- Удалён тип
SafetyFeedback, поскольку он не использовался ни в одном из ответов.
- Удалён тип
Метаданные цитирования
- Свойство
citationSourcesвCitationMetadataпереименовано вcitations.
- Свойство
Общее количество персонажей, за которых можно платить
- Изменено свойство
totalBillableCharactersвCountTokensResponseна необязательное, чтобы отражать ситуации, когда символы не отправляются.
- Изменено свойство
Ответ кандидата
- Название
CandidateResponseбыло переименовано вCandidate, чтобы соответствовать другим платформам.
- Название
Конфигурация поколения
- Изменены общедоступные свойства
GenerationConfigнаinternal. Все они по-прежнему доступны для настройки в инициализаторе.
- Изменены общедоступные свойства
Kotlin
Перечисления
Заменены классы-
enumиsealedклассы на обычные классы. Это изменение обеспечивает большую гибкость при развитии API с сохранением обратной совместимости.Переименовано перечисление
BlockThresholdвHarmBlockThreshold.Удалены значения из следующих перечислений:
HarmBlockThreshold,HarmProbability,HarmSeverity,BlockReasonиFinishReason.
Методы Blob
- Все методы, в названии которых присутствовало слово
Blobбыли переименованы с использованиемInlineData.
- Все методы, в названии которых присутствовало слово
Настройки безопасности
- Изменен
methodполя, теперь оно допускает значение NULL.
- Изменен
Класс продолжительности
- Удалены все упоминания класса
Durationиз Kotlin и заменены наlong. Это изменение обеспечивает лучшую совместимость с Java.
- Удалены все упоминания класса
Метаданные цитирования
- Все поля, ранее объявленные в
CitationMetadataбыли объединены в новый класс под названиемCitation. Цитаты можно найти в списке под названиемcitationsвCitationMetadata. Это изменение позволяет лучше согласовывать типы данных на разных платформах.
- Все поля, ранее объявленные в
Подсчет токенов
- Изменено поле
totalBillableCharactersтаким образом, чтобы оно могло принимать значение null.
- Изменено поле
Общее количество персонажей, за которых можно платить
- Изменено свойство
totalBillableCharactersвCountTokensResponseна необязательное, чтобы отражать ситуации, когда символы не отправляются.
- Изменено свойство
Создание экземпляра модели
- Параметр
requestOptionsперемещен в конец списка параметров для соответствия требованиям других платформ.
- Параметр
Java
Перечисления
Заменены классы-
enumиsealedклассы на обычные классы. Это изменение обеспечивает большую гибкость при развитии API с сохранением обратной совместимости.Переименовано перечисление
BlockThresholdвHarmBlockThreshold.Удалены значения из следующих перечислений:
HarmBlockThreshold,HarmProbability,HarmSeverity,BlockReasonиFinishReason.
Методы Blob
- Все методы, в названии которых присутствовало слово
Blobбыли переименованы с использованиемInlineData.
- Все методы, в названии которых присутствовало слово
Настройки безопасности
- Изменен
methodполя, теперь оно допускает значение NULL.
- Изменен
Класс продолжительности
- Удалены все упоминания класса
Durationиз Kotlin и заменены наlong. Это изменение обеспечивает лучшую совместимость с Java.
- Удалены все упоминания класса
Метаданные цитирования
- Все поля, ранее объявленные в
CitationMetadataбыли объединены в новый класс под названиемCitation. Цитаты можно найти в списке под названиемcitationsвCitationMetadata. Это изменение позволяет лучше согласовывать типы данных на разных платформах.
- Все поля, ранее объявленные в
Подсчет токенов
- Изменено поле
totalBillableCharactersтаким образом, чтобы оно могло принимать значение null.
- Изменено поле
Общее количество персонажей, за которых можно платить
- Изменено свойство
totalBillableCharactersвCountTokensResponseна необязательное, чтобы отражать ситуации, когда символы не отправляются.
- Изменено свойство
Создание экземпляра модели
- Параметр
requestOptionsперемещен в конец списка параметров для соответствия требованиям других платформ.
- Параметр
Web
Обратите внимание, что клиентский SDK Google AI для JavaScript претерпел множество изменений с тех пор, как от него отделились клиентские SDK Firebase AI Logic . Ниже приведен список некоторых потенциальных изменений, которые вам, возможно, потребуется учесть при миграции на клиентские SDK Firebase AI Logic .
Перечисления
- Удалены значения из следующих перечислений:
HarmCategory,BlockThreshold,HarmProbability,HarmSeverity,BlockReasonиFinishReason.
- Удалены значения из следующих перечислений:
Причина блокировки
- Изменено
blockReasonвPromptFeedback, теперь он является необязательным.
- Изменено
Поиск заземления
- Удалено все упоминания этой функции, поскольку она пока не поддерживается в SDK Firebase AI Logic .
Ошибки
- Удалены все упоминания
GoogleGenerativeAIError, и при желании их можно перенести вAIError.
- Удалены все упоминания
Dart
Перечисления
- Удалены значения из следующих перечислений:
HarmCategory,HarmProbability,BlockReasonиFinishReason.
- Удалены значения из следующих перечислений:
Часть данных
- Переименовали
DataPartвInlineDataPart, а функциюstaticdata— вinlineDataдля соответствия другим платформам.
- Переименовали
Варианты запроса
- Удалён
RequestOptionsпосколькуtimeoutне работал. Он будет добавлен обратно в ближайшем будущем, но будет перенесён в типGenerativeModel, чтобы соответствовать другим платформам.
- Удалён
Стоп-последовательности
- Изменен параметр
stopSequencesвGenerationConfigтеперь он необязателен и по умолчанию принимает значениеnullвместо пустого массива.
- Изменен параметр
Цитаты
- Свойство
citationSourcesвCitationMetadataпереименовано вcitations. ТипCitationSourceпереименован вCitation, чтобы соответствовать другим платформам.
- Свойство
Ненужные общедоступные типы, методы и свойства
- Удалены следующие типы, методы и свойства, которые были непреднамеренно раскрыты:
defaultTimeout,CountTokensResponseFields,parseCountTokensResponse,parseEmbedContentResponse,parseGenerateContentResponse,parseContent,BatchEmbedContentsResponse,ContentEmbedding,EmbedContentRequestиEmbedContentResponse.
- Удалены следующие типы, методы и свойства, которые были непреднамеренно раскрыты:
Подсчет токенов
- Из функции
countTokensудалены лишние поля, которые больше не нужны. Требуется толькоcontents.
- Из функции
Создание экземпляра модели
- Параметр
systemInstructionперемещен в конец списка параметров для согласования с другими платформами.
- Параметр
Функциональность встраивания
- Из модели удалены неподдерживаемые функции встраивания (
embedContentиbatchEmbedContents).
- Из модели удалены неподдерживаемые функции встраивания (
Единство
Поддержка Unity отсутствовала в клиентских SDK Google AI .
Узнайте, как начать работу с Firebase AI Logic SDK для Unity .
Оставьте отзыв о вашем опыте использования Firebase AI Logic.
Перейдите непосредственно к инструкциям по миграции.
Почему стоит перейти на использование SDK Firebase AI Logic ?
Возможно, вы уже пробовали альтернативный набор SDK для мобильных или веб-приложений, который предоставлял вам доступ к API разработчика Gemini .
Эти клиентские SDK не были интегрированы в мощную экосистему Firebase, предоставляющую критически важные сервисы для мобильных и веб-приложений. Теперь они устарели в пользу клиентских SDK Firebase AI Logic , которые предоставляют доступ к API разработчика Gemini .
Функции безопасности для мобильных и веб-приложений
Для мобильных и веб-приложений безопасность имеет решающее значение и требует особого внимания, поскольку ваш код, включая вызовы к API Gemini , выполняется в незащищенной среде. Вы можете использовать Firebase App Check для защиты API от злоупотреблений со стороны неавторизованных клиентов.
При использовании Firebase App Check с Firebase AI Logic вы никогда не добавляете свой ключ API Gemini для Gemini Developer API непосредственно в код вашего мобильного или веб-приложения. Вместо этого ключ API Gemini остается на сервере, недоступном для злоумышленников.
Экосистема, созданная для мобильных и веб-приложений.
Firebase — это платформа Google для разработки мобильных и веб-приложений. Использование Firebase AI Logic означает, что ваши приложения находятся в экосистеме, ориентированной на потребности разработчиков и разработчиков, работающих с полным стеком технологий. Например:
С помощью Firebase Remote Config вы можете динамически устанавливать параметры во время выполнения или заменять значения в вашем приложении (например, имя модели и версию) без выпуска новой версии приложения.
Используйте Cloud Storage for Firebase для включения больших файлов в ваши многомодальные запросы (если вы используете API Agent Platform Gemini (ранее Vertex AI) ). Клиентские SDK Cloud Storage помогут вам обрабатывать загрузку и скачивание файлов (даже в условиях плохой сети) и обеспечат более высокую безопасность данных ваших конечных пользователей. Подробнее см. в нашем руководстве по использованию Cloud Storage for Firebase .
Управляйте структурированными данными с помощью SDK для баз данных, разработанных для мобильных и веб-приложений (например, Cloud Firestore ).
Переход на SDK Firebase AI Logic
Обзор шагов по миграции на SDK Firebase AI Logic :
Шаг 1 : Создайте новый или подключите существующий проект Firebase к Firebase.
Шаг 2 : Добавьте SDK Firebase AI Logic в ваше приложение.
Шаг 3 : Обновите импорт и инициализацию в вашем приложении.
Шаг 4 : Обновите свой код в зависимости от используемых вами функций.
Шаг 1 : Создайте проект Firebase и подключите к нему ваше приложение.
Войдите в консоль Firebase , а затем выберите свой проект Firebase.
Если у вас еще нет проекта Firebase, нажмите кнопку для создания нового проекта Firebase, а затем воспользуйтесь одним из следующих вариантов:
Вариант 1 : Создайте совершенно новый проект Firebase (и автоматически сформируйте для него базовый проект Google Cloud ), указав новое имя проекта на первом шаге рабочего процесса.
Вариант 2 : "Добавить Firebase" в существующий проект Google Cloud , нажав кнопку "Добавить Firebase в проект Google Cloud" (внизу страницы). На первом шаге процесса начните вводить название существующего проекта, а затем выберите проект из отображаемого списка.
При желании вы можете добавить Firebase в проект, который был создан автоматически при создании ключа API Gemini в Google AI Studio .
Выполните оставшиеся шаги отображаемого на экране процесса, чтобы создать проект Firebase. Обратите внимание, что при появлении соответствующего запроса вам не потребуется настраивать Google Analytics для использования SDK Firebase AI Logic .
В консоли Firebase перейдите в раздел AI Services > AI Logic .
Нажмите « Начать» , чтобы запустить пошаговый рабочий процесс, который поможет вам настроить необходимые API и ресурсы для вашего проекта.
Выберите API разработчика Gemini . При желании вы всегда сможете настроить и использовать другой поставщик API позже.
Консоль активирует необходимые API и создаст новый, выделенный ключ API Gemini в вашем проекте.
Не добавляйте этот новый ключ API Gemini в код вашего приложения. Узнайте больше.Если в процессе работы консоли появится соответствующее сообщение, следуйте инструкциям на экране, чтобы зарегистрировать ваше приложение и подключить его к Firebase.
Продолжите выполнение инструкций в этом руководстве по миграции, чтобы обновить библиотеку и выполнить инициализацию в вашем приложении.
Шаг 2 : Добавьте SDK Firebase AI Logic в ваше приложение.
После настройки проекта Firebase и подключения приложения к Firebase (см. предыдущий шаг) вы можете добавить SDK Firebase AI Logic в свое приложение.
Быстрый
Используйте Swift Package Manager для установки и управления зависимостями Firebase. При необходимости ознакомьтесь с другими вариантами установки .
Библиотека Firebase AI Logic предоставляет доступ к API для взаимодействия с моделями Gemini . Библиотека входит в состав Firebase SDK для платформ Apple ( firebase-ios-sdk ).
Если вы уже используете Firebase, убедитесь, что версия вашего пакета Firebase — 12.5.0 или более поздняя.
В Xcode, открыв проект приложения, перейдите в меню File > Add Package Dependencies .
При появлении запроса добавьте репозиторий Firebase Apple Platforms SDK:
https://github.com/firebase/firebase-ios-sdkВыберите последнюю версию SDK.
Выберите библиотеку
FirebaseAILogicи библиотекуFirebaseAppCheck.
После завершения Xcode автоматически начнет разрешение и загрузку ваших зависимостей в фоновом режиме.
Kotlin
SDK Firebase AI Logic для Android ( firebase-ai ) предоставляет доступ к API для взаимодействия с моделями Gemini .
В файле Gradle вашего модуля (уровня приложения) (например, <project>/<app-module>/build.gradle.kts ) добавьте зависимости для библиотек Firebase AI Logic и App Check для Android. Мы рекомендуем использовать Firebase Android BoM для управления версиями библиотек.
dependencies { // ... other androidx dependencies // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.18.0")) // Add the dependencies for the Firebase AI Logic and App Check libraries // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-ai") implementation("com.google.firebase:firebase-appcheck-debug") }
Использование Firebase Android BoM , что ваше приложение всегда будет использовать совместимые версии библиотек Firebase Android.
Если вы решите не использовать Firebase BoM , вам необходимо указать версию каждой библиотеки Firebase в строке зависимости.
Обратите внимание, что если вы используете несколько библиотек Firebase в своем приложении, мы настоятельно рекомендуем использовать BoM для управления версиями библиотек, что гарантирует совместимость всех версий.
dependencies { // Add the dependencies for the Firebase AI Logic and App Check libraries // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-ai:17.16.0") implementation("com.google.firebase:firebase-appcheck-debug:19.4.1") }
Java
SDK Firebase AI Logic для Android ( firebase-ai ) предоставляет доступ к API для взаимодействия с моделями Gemini .
В файле Gradle вашего модуля (уровня приложения) (например, <project>/<app-module>/build.gradle.kts ) добавьте зависимости для библиотек Firebase AI Logic и App Check для Android. Мы рекомендуем использовать Firebase Android BoM для управления версиями библиотек.
Для Java необходимо добавить две дополнительные библиотеки.
dependencies { // ... other androidx dependencies // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.18.0")) // Add the dependencies for the Firebase AI Logic and App Check libraries // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-ai") implementation("com.google.firebase:firebase-appcheck-debug") // Required for one-shot operations (to use `ListenableFuture` from Guava Android) implementation("com.google.guava:guava:31.0.1-android") // Required for streaming operations (to use `Publisher` from Reactive Streams) implementation("org.reactivestreams:reactive-streams:1.0.4") }
Использование Firebase Android BoM , что ваше приложение всегда будет использовать совместимые версии библиотек Firebase Android.
Если вы решите не использовать Firebase BoM , вам необходимо указать версию каждой библиотеки Firebase в строке зависимости.
Обратите внимание, что если вы используете несколько библиотек Firebase в своем приложении, мы настоятельно рекомендуем использовать BoM для управления версиями библиотек, что гарантирует совместимость всех версий.
dependencies { // Add the dependencies for the Firebase AI Logic and App Check libraries // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-ai:17.16.0") implementation("com.google.firebase:firebase-appcheck-debug:19.4.1") }
Web
Библиотека Firebase AI Logic предоставляет доступ к API для взаимодействия с моделями Gemini . Библиотека входит в состав Firebase JavaScript SDK для веб-приложений.
Установите Firebase JS SDK для веб-разработки с помощью npm:
npm install firebaseИнициализируйте Firebase в своем приложении:
import { initializeApp } from "firebase/app"; import { initializeAppCheck, DebugProvider } from "firebase/app-check"; // TODO(developer) Replace the following with your app's Firebase configuration // See: https://firebase.google.com/docs/web/learn-more#config-object const firebaseConfig = { // ... }; // Initialize FirebaseApp const firebaseApp = initializeApp(firebaseConfig);
Dart
Плагин Firebase AI Logic для Flutter ( firebase_ai ) предоставляет доступ к API для взаимодействия с моделями Gemini .
Для установки плагинов Firebase AI Logic и App Check из каталога вашего проекта Flutter выполните следующую команду:
flutter pub add firebase_ai firebase_app_checkВ файле
lib/main.dartимпортируйте плагины Firebase AI Logic и App Check :import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_ai/firebase_ai.dart'; import 'package:firebase_app_check/firebase_app_check.dart'; import 'firebase_options.dart';Также в файле
lib/main.dartубедитесь, что вы инициализировали Firebase, используя объектDefaultFirebaseOptions, экспортируемый из файла конфигурации:await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, );Пересоберите ваше Flutter-приложение:
flutter run
Единство
Поддержка Unity отсутствовала в SDK клиента Google AI .
Узнайте, как начать работу с Firebase AI Logic SDK для Unity .
Удалите старый SDK из вашего приложения.
После завершения миграции приложения (см. остальные разделы этого руководства) обязательно удалите старую библиотеку.
Быстрый
Удалите старую библиотеку:
В Xcode, открыв проект приложения, перейдите в панель «Пакеты и зависимости» .
Выберите пакет
generative-ai-swiftиз списка зависимостей пакетов.Нажмите кнопку
-внизу списка и нажмите «Удалить» для подтверждения.
Kotlin
dependencies {
implementation("com.google.ai.client.generativeai:generativeai:VERSION")
}
Java
dependencies {
implementation("com.google.ai.client.generativeai:generativeai:VERSION")
}
Web
// BEFORE
import { initializeApp } from "firebase/app";
import { GoogleGenerativeAI } from "@google/generative-ai";
Dart
Удалите старый пакет:
flutter pub remove google_generative_ai
Единство
Поддержка Unity отсутствовала в клиентских SDK Google AI .
Узнайте, как начать работу с Firebase AI Logic SDK для Unity .
Шаг 3 : Обновите импорт и инициализацию в вашем приложении.
Обновите импорт и способ инициализации бэкэнд-сервиса Gemini Developer API , а также создайте экземпляр GenerativeModel .
Быстрый
// BEFOREimport GoogleGenerativeAI let model = GenerativeModel(name: "MODEL_NAME", apiKey: APIKey.default)// AFTER import FirebaseAILogic // Initialize the Gemini Developer API backend service let ai = FirebaseAI.firebaseAI(backend: .googleAI()) // Create a `GenerativeModel` instance with a model that supports your use case let model = ai.generativeModel(modelName: "gemini-3.7-flash")
Kotlin
// BEFOREimport com.google.ai.client.generativeai.Chat import com.google.ai.client.generativeai.type.Content import com.google.ai.client.generativeai.java.GenerativeModuleFutures...val generativeModel = GenerativeModel(modelName = "MODEL_NAME", // Access your API key as a Build Configuration variable apiKey = BuildConfig.apiKey )// AFTER import com.google.firebase.Firebase import com.google.firebase.ai.ai import com.google.firebase.ai.type.GenerativeBackend ... // Initialize the Gemini Developer API backend service. // Create a `GenerativeModel` instance with a model that supports your use case. val model = Firebase.ai(backend = GenerativeBackend.googleAI()) .generativeModel("gemini-3.7-flash")
Java
// BEFOREimport com.google.ai.client.generativeai.Chat; import com.google.ai.client.generativeai.type.Content; import com.google.ai.client.generativeai.java.GenerativeModuleFutures;...GenerativeModel gm = new GenerativeModel("MODEL_NAME", // Access your API key as a Build Configuration variable BuildConfig.apiKey ); GenerativeModelFutures model = GenerativeModelFutures.from(gm);// AFTER import com.google.firebase.ai.FirebaseAI; import com.google.firebase.ai.GenerativeModel; import com.google.firebase.ai.java.GenerativeModelFutures; import com.google.firebase.ai.type.GenerativeBackend; ... // Initialize the Gemini Developer API backend service. // Create a `GenerativeModel` instance with a model that supports your use case. GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI()) .generativeModel("gemini-3.7-flash"); // Use the GenerativeModelFutures Java compatibility layer which offers // support for ListenableFuture and Publisher APIs GenerativeModelFutures model = GenerativeModelFutures.from(ai);
Web
// BEFOREimport { GoogleGenerativeAI } from "@google/generative-ai"; // Fetch your API_KEY and access your API const API_KEY = "..."; const genAI = new GoogleGenerativeAI(API_KEY);...const model = genAI.getGenerativeModel({ model: "MODEL_NAME"});// AFTER import { initializeApp } from "firebase/app"; import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai"; // TODO(developer): Replace the following with your app's Firebase configuration // See: https://firebase.google.com/docs/web/learn-more#config-object const firebaseConfig = { // ... }; // Initialize FirebaseApp const firebaseApp = initializeApp(firebaseConfig); // Initialize the Gemini Developer API backend service. const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() }); // Create a `GenerativeModel` instance with a model that supports your use case. const model = getGenerativeModel(ai, { model: "gemini-3.7-flash" });
Dart
// BEFOREimport 'package:google_generative_ai/google_generative_ai.dart'; final apiKey = Platform.environment['API_KEY']; if (apiKey == null) { print('No \$API_KEY environment variable'); exit(1); } final model = GenerativeModel(model: 'MODEL_NAME', apiKey: apiKey);// AFTER import 'package:firebase_ai/firebase_ai.dart'; import 'package:firebase_core/firebase_core.dart'; import 'firebase_options.dart'; // Initialize FirebaseApp await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); // Initialize the Gemini Developer API backend service // Create a `GenerativeModel` instance with a model that supports your use case final model = FirebaseAI.googleAI().generativeModel(model: 'gemini-3.7-flash');
Единство
Поддержка Unity отсутствовала в клиентских SDK Google AI .
Узнайте, как начать работу с Firebase AI Logic SDK для Unity .
Обратите внимание, что в зависимости от используемых возможностей вам может не всегда потребоваться создать экземпляр GenerativeModel . Для потоковой передачи входных и выходных данных с помощью Gemini Live API создайте экземпляр LiveModel .
Шаг 4 : Обновите код в зависимости от используемых вами функций.
На этом шаге описываются изменения, которые могут потребоваться в зависимости от используемых вами функций.
SDK клиента Firebase AI Logic не поддерживают выполнение кода. Если вы используете эту функцию, убедитесь, что она учтена в вашем приложении.
Ознакомьтесь со следующими списками, чтобы узнать, какие изменения вам, возможно, потребуется внести в свой код для перехода на клиентские SDK Firebase AI Logic .
Требуется для всех языков и платформ.
Вызов функции
Если вы реализовали эту функцию, вам потребуется внести изменения в определение схемы. Мы рекомендуем ознакомиться с обновленным руководством по вызову функций , чтобы узнать, как правильно писать объявления функций.Генерация структурированного вывода (например, в формате JSON) с использованием
responseSchema
Если вы внедрили эту функцию, вам потребуется внести изменения в определение схемы. Мы рекомендуем ознакомиться с новым руководством по структурированному выводу, чтобы узнать, как писать JSON-схемы.Тайм-аут
- Изменено значение тайм-аута по умолчанию для запросов на 180 секунд.
Требуется в зависимости от платформы или языка.
Быстрый
Перечисления
Большинство типов
enumзамененыstructсо статическими переменными. Это изменение обеспечивает большую гибкость при развитии API с сохранением обратной совместимости. При использовании операторовswitchтеперь необходимо указывать значениеdefault:case) для обработки неизвестных или необработанных значений, включая новые значения, которые будут добавлены в SDK в будущем.Переименование перечисления
BlockThresholdвHarmBlockThreshold; теперь этот тип являетсяstruct.Из следующих перечислений (теперь
struct) удаленыunknownиunspecifiedслучаи:HarmCategory,HarmBlockThreshold,HarmProbability,BlockReasonиFinishReason.Заменено перечисление
ModelContent.Partпротоколом с именемPart, позволяющим добавлять новые типы с сохранением обратной совместимости. Это изменение более подробно описано в разделе «Части контента» .
Содержание
Удалён протокол
ThrowingPartsRepresentable, а инициализаторы дляModelContentупрощены, чтобы избежать случайных ошибок компиляции. Изображения, которые некорректно кодируются, по-прежнему будут вызывать ошибки при использовании вgenerateContent.Заменены экземпляры
ModelContent.Partследующимиstructтипами, соответствующими протоколуPart:-
.texttoTextPart -
.datatoInlineDataPart -
.fileDatatoFileDataPart -
.functionCalltoFunctionCallPart -
.functionResponsetoFunctionResponsePart
-
Категория вреда
- Изменено представление
HarmCategoryтаким образом, чтобы оно больше не было вложено в типSafetySetting. Если вы имеете в видуSafetySetting.HarmCategory, то это можно заменить наHarmCategory.
- Изменено представление
Обратная связь по вопросам безопасности
- Удалён тип
SafetyFeedback, поскольку он не использовался ни в одном из ответов.
- Удалён тип
Метаданные цитирования
- Свойство
citationSourcesвCitationMetadataпереименовано вcitations.
- Свойство
Общее количество персонажей, за которых можно платить
- Изменено свойство
totalBillableCharactersвCountTokensResponseна необязательное, чтобы отражать ситуации, когда символы не отправляются.
- Изменено свойство
Ответ кандидата
- Название
CandidateResponseбыло переименовано вCandidate, чтобы соответствовать другим платформам.
- Название
Конфигурация поколения
- Изменены общедоступные свойства
GenerationConfigнаinternal. Все они по-прежнему доступны для настройки в инициализаторе.
- Изменены общедоступные свойства
Kotlin
Перечисления
Заменены классы-
enumиsealedклассы на обычные классы. Это изменение обеспечивает большую гибкость при развитии API с сохранением обратной совместимости.Переименовано перечисление
BlockThresholdвHarmBlockThreshold.Удалены значения из следующих перечислений:
HarmBlockThreshold,HarmProbability,HarmSeverity,BlockReasonиFinishReason.
Методы Blob
- Все методы, в названии которых присутствовало слово
Blobбыли переименованы с использованиемInlineData.
- Все методы, в названии которых присутствовало слово
Настройки безопасности
- Изменен
methodполя, теперь оно допускает значение NULL.
- Изменен
Класс продолжительности
- Удалены все упоминания класса
Durationиз Kotlin и заменены наlong. Это изменение обеспечивает лучшую совместимость с Java.
- Удалены все упоминания класса
Метаданные цитирования
- Все поля, ранее объявленные в
CitationMetadataбыли объединены в новый класс под названиемCitation. Цитаты можно найти в списке под названиемcitationsвCitationMetadata. Это изменение позволяет лучше согласовывать типы данных на разных платформах.
- Все поля, ранее объявленные в
Подсчет токенов
- Изменено поле
totalBillableCharactersтаким образом, чтобы оно могло принимать значение null.
- Изменено поле
Общее количество персонажей, за которых можно платить
- Changed the
totalBillableCharactersproperty inCountTokensResponseto be optional to reflect situations where no characters are sent.
- Changed the
Instantiating a model
- Moved the
requestOptionsparameter to the end of the parameter list to align with other platforms.
- Moved the
Java
Enumerations
Replaced
enumclasses andsealedclasses with regular classes. This change allows more flexibility for evolving the API in a backward compatible way.Renamed the
BlockThresholdenumeration toHarmBlockThreshold.Removed values from the following enumerations:
HarmBlockThreshold,HarmProbability,HarmSeverity,BlockReason, andFinishReason.
Blob methods
- Renamed all methods that included
Blobas part of their name to useInlineDatainstead.
- Renamed all methods that included
Настройки безопасности
- Changed the field
methodto be nullable.
- Changed the field
Duration class
- Removed all usages of Kotlin's
Durationclass, and replaced it withlong. This change provides better interoperability with Java.
- Removed all usages of Kotlin's
Метаданные цитирования
- Wrapped all the fields previously declared in
CitationMetadatainto a new class calledCitation. Citations can be found in the list calledcitationsinCitationMetadata. This change allows better alignment of types across platforms.
- Wrapped all the fields previously declared in
Подсчет токенов
- Changed the field
totalBillableCharactersto be nullable.
- Changed the field
Total billable characters
- Changed the
totalBillableCharactersproperty inCountTokensResponseto be optional to reflect situations where no characters are sent.
- Changed the
Instantiating a model
- Moved the
requestOptionsparameter to the end of the parameter list to align with other platforms.
- Moved the
Web
Note that the Google AI client SDK for JavaScript has had many changes since the time that the Firebase AI Logic client SDKs branched from it. The following list are some potential changes that you might need to consider as you migrate to the Firebase AI Logic client SDKs.
Enumerations
- Removed values from the following enumerations:
HarmCategory,BlockThreshold,HarmProbability,HarmSeverity,BlockReason, andFinishReason.
- Removed values from the following enumerations:
Block reason
- Changed
blockReasoninPromptFeedbackto be optional.
- Changed
Search Grounding
- Removed all usages of this feature, since it's not yet supported in the Firebase AI Logic SDKs.
Ошибки
- Removed all usages of
GoogleGenerativeAIError, and optionally move toAIError.
- Removed all usages of
Dart
Enumerations
- Removed values from the following enumerations:
HarmCategory,HarmProbability,BlockReason, andFinishReason.
- Removed values from the following enumerations:
Data part
- Renamed
DataParttoInlineDataPart, and thestaticdatafunction toinlineDatato align with other platforms.
- Renamed
Варианты запроса
- Removed
RequestOptionssincetimeoutwasn't functional. It will be re-added in the near future, but it will be moved to theGenerativeModeltype to match other platforms.
- Removed
Stop sequences
- Changed the
stopSequencesparameter inGenerationConfigto be optional and to default tonullinstead of an empty array.
- Changed the
Цитаты
- Renamed the
citationSourcesproperty tocitationsinCitationMetadata. TheCitationSourcetype was renamed toCitationto match other platforms.
- Renamed the
Unnecessary public types, methods, and properties
- Removed the following types, methods, and properties which were unintentionally exposed:
defaultTimeout,CountTokensResponseFields,parseCountTokensResponse,parseEmbedContentResponse,parseGenerateContentResponse,parseContent,BatchEmbedContentsResponse,ContentEmbedding,EmbedContentRequest, andEmbedContentResponse.
- Removed the following types, methods, and properties which were unintentionally exposed:
Подсчет токенов
- Removed extra fields from the
countTokensfunction that are no longer necessary. Onlycontentsis needed.
- Removed extra fields from the
Instantiating a model
- Moved the
systemInstructionparameter to the end of the parameter list to align with other platforms.
- Moved the
Embedding functionality
- Removed unsupported embedding functionality (
embedContentandbatchEmbedContents) from the model.
- Removed unsupported embedding functionality (
Единство
Support for Unity wasn't available from Google AI client SDKs.
Learn how to get started with the Firebase AI Logic SDK for Unity .
Give feedback about your experience with Firebase AI Logic
Go directly to migration instructions
Why migrate to use the Firebase AI Logic SDKs?
You might have tried out an alternative set of mobile or web client SDKs that gave you access to the Gemini Developer API .
Those client SDKs were not integrated into the robust Firebase ecosystem that offers critical services for mobile and web apps. They are now deprecated in favor of the Firebase AI Logic client SDKs, which can give you access to the Gemini Developer API .
Security features for mobile and web apps
For mobile and web apps, security is critical and requires special considerations because your code – including calls to the Gemini API – is running in an unprotected environment. You can use Firebase App Check to protect APIs from abuse by unauthorized clients.
When you use Firebase App Check with Firebase AI Logic , you never add your Gemini API key for the Gemini Developer API directly into your mobile or web app's codebase. Instead, the Gemini API key stays on the server, unexposed to malicious actors.
Ecosystem built for mobile and web apps
Firebase is Google's platform for developing mobile and web apps. Using Firebase AI Logic means that your apps are in an ecosystem that's focused on the needs of full-stack apps and developers. For example:
Dynamically set run-time configurations or swap out values in your app (like a model name and version) without releasing a new app version using Firebase Remote Config .
Use Cloud Storage for Firebase to include large files in your multimodal requests (if you use the Agent Platform Gemini API (formerly Vertex AI) ). The Cloud Storage client SDKs help you handle file uploads and downloads (even in poor network conditions) and offer more security for your end-users' data. Learn more in our solution guide about using Cloud Storage for Firebase .
Manage structured data using database SDKs built for mobile and web apps (like Cloud Firestore ).
Migrate to the Firebase AI Logic SDKs
Overview of steps to migrate to the Firebase AI Logic SDKs:
Step 1 : Set up a new or existing Firebase project and connect your app to Firebase.
Step 2 : Add the Firebase AI Logic SDKs to your app.
Step 3 : Update your imports and initialization in your app.
Step 4 : Update your code depending on the features that you use.
Step 1 : Set up a Firebase project and connect your app
Sign into the Firebase console , and then select your Firebase project.
If you don't already have a Firebase project, click the button to create a new Firebase project, and then use either of the following options:
Option 1 : Create a wholly new Firebase project (and its underlying Google Cloud project automatically) by entering a new project name in the first step of the workflow.
Option 2 : "Add Firebase" to an existing Google Cloud project by clicking Add Firebase to Google Cloud project (at bottom of page). In the first step of the workflow, start entering the project name of the existing project, and then select the project from the displayed list.
If you'd like, you can add Firebase to the project that was created behind the scenes when you created a Gemini API key in Google AI Studio .
Complete the remaining steps of the on-screen workflow to create a Firebase project. Note that when prompted, you do not need to set up Google Analytics to use the Firebase AI Logic SDKs.
In the Firebase console, go to AI Services > AI Logic .
Click Get started to launch a guided workflow that helps you set up the required APIs and resources for your project.
Select the Gemini Developer API . You can always set up and use the other API provider later, if you'd like.
The console will enable the required APIs and create a new, dedicated Gemini API key in your project.
Do not add this new Gemini API key into your app's codebase. Learn more.If prompted in the console's workflow, follow the on-screen instructions to register your app and connect it to Firebase.
Continue in this migration guide to update the library and initialization in your app.
Step 2 : Add the Firebase AI Logic SDK to your app
With your Firebase project set up and your app connected to Firebase (see previous step), you can now add the Firebase AI Logic SDK to your app.
Быстрый
Use Swift Package Manager to install and manage Firebase dependencies. Learn about other installation options , if needed.
The Firebase AI Logic library provides access to the APIs for interacting with Gemini models. The library is included as part of the Firebase SDK for Apple platforms ( firebase-ios-sdk ).
If you're already using Firebase, then make sure your Firebase package is v12.5.0 or later.
In Xcode, with your app project open, navigate to File > Add Package Dependencies .
When prompted, add the Firebase Apple platforms SDK repository:
https://github.com/firebase/firebase-ios-sdkSelect the latest SDK version.
Select the
FirebaseAILogiclibrary and theFirebaseAppChecklibrary.
When finished, Xcode will automatically begin resolving and downloading your dependencies in the background.
Kotlin
The Firebase AI Logic SDK for Android ( firebase-ai ) provides access to the APIs for interacting with Gemini models.
In your module (app-level) Gradle file (like <project>/<app-module>/build.gradle.kts ), add the dependencies for the Firebase AI Logic and App Check libraries for Android. We recommend using the Firebase Android BoM to control library versioning.
dependencies { // ... other androidx dependencies // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.18.0")) // Add the dependencies for the Firebase AI Logic and App Check libraries // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-ai") implementation("com.google.firebase:firebase-appcheck-debug") }
By using the Firebase Android BoM , your app will always use compatible versions of Firebase Android libraries.
If you choose not to use the Firebase BoM , you must specify each Firebase library version in its dependency line.
Note that if you use multiple Firebase libraries in your app, we strongly recommend using the BoM to manage library versions, which ensures that all versions are compatible.
dependencies { // Add the dependencies for the Firebase AI Logic and App Check libraries // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-ai:17.16.0") implementation("com.google.firebase:firebase-appcheck-debug:19.4.1") }
Java
The Firebase AI Logic SDK for Android ( firebase-ai ) provides access to the APIs for interacting with Gemini models.
In your module (app-level) Gradle file (like <project>/<app-module>/build.gradle.kts ), add the dependencies for the Firebase AI Logic and App Check libraries for Android. We recommend using the Firebase Android BoM to control library versioning.
For Java, you need to add two additional libraries.
dependencies { // ... other androidx dependencies // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.18.0")) // Add the dependencies for the Firebase AI Logic and App Check libraries // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-ai") implementation("com.google.firebase:firebase-appcheck-debug") // Required for one-shot operations (to use `ListenableFuture` from Guava Android) implementation("com.google.guava:guava:31.0.1-android") // Required for streaming operations (to use `Publisher` from Reactive Streams) implementation("org.reactivestreams:reactive-streams:1.0.4") }
By using the Firebase Android BoM , your app will always use compatible versions of Firebase Android libraries.
If you choose not to use the Firebase BoM , you must specify each Firebase library version in its dependency line.
Note that if you use multiple Firebase libraries in your app, we strongly recommend using the BoM to manage library versions, which ensures that all versions are compatible.
dependencies { // Add the dependencies for the Firebase AI Logic and App Check libraries // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-ai:17.16.0") implementation("com.google.firebase:firebase-appcheck-debug:19.4.1") }
Web
The Firebase AI Logic library provides access to the APIs for interacting with Gemini models. The library is included as part of the Firebase JavaScript SDK for Web.
Install the Firebase JS SDK for Web using npm:
npm install firebaseInitialize Firebase in your app:
import { initializeApp } from "firebase/app"; import { initializeAppCheck, DebugProvider } from "firebase/app-check"; // TODO(developer) Replace the following with your app's Firebase configuration // See: https://firebase.google.com/docs/web/learn-more#config-object const firebaseConfig = { // ... }; // Initialize FirebaseApp const firebaseApp = initializeApp(firebaseConfig);
Dart
The Firebase AI Logic plugin for Flutter ( firebase_ai ) provides access to the APIs for interacting with Gemini models.
From your Flutter project directory, run the following command to install the Firebase AI Logic and App Check plugins:
flutter pub add firebase_ai firebase_app_checkIn your
lib/main.dartfile, import the Firebase AI Logic and App Check plugins:import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_ai/firebase_ai.dart'; import 'package:firebase_app_check/firebase_app_check.dart'; import 'firebase_options.dart';Also in your
lib/main.dartfile, make sure that you've initialized Firebase using theDefaultFirebaseOptionsobject exported by the configuration file:await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, );Пересоберите ваше Flutter-приложение:
flutter run
Единство
Support for Unity wasn't available from the Google AI client SDKs.
Learn how to get started with the Firebase AI Logic SDK for Unity .
Remove the old SDK from your app
After you've finished migrating your app (see the remaining sections in this guide), make sure to delete the old library.
Быстрый
Remove the old library:
In Xcode, with your app project open, navigate to the Packages Dependencies pane.
Select the
generative-ai-swiftpackage from the list of package dependencies.Click the
-button from the bottom of the list and click Remove to confirm.
Kotlin
dependencies {
implementation("com.google.ai.client.generativeai:generativeai:VERSION")
}
Java
dependencies {
implementation("com.google.ai.client.generativeai:generativeai:VERSION")
}
Web
// BEFORE
import { initializeApp } from "firebase/app";
import { GoogleGenerativeAI } from "@google/generative-ai";
Dart
Delete the old package:
flutter pub remove google_generative_ai
Единство
Support for Unity wasn't available from Google AI client SDKs.
Learn how to get started with the Firebase AI Logic SDK for Unity .
Step 3 : Update your imports and initialization in your app
Update your imports and how you initialize the Gemini Developer API backend service and create a GenerativeModel instance.
Быстрый
// BEFOREimport GoogleGenerativeAI let model = GenerativeModel(name: "MODEL_NAME", apiKey: APIKey.default)// AFTER import FirebaseAILogic // Initialize the Gemini Developer API backend service let ai = FirebaseAI.firebaseAI(backend: .googleAI()) // Create a `GenerativeModel` instance with a model that supports your use case let model = ai.generativeModel(modelName: "gemini-3.7-flash")
Kotlin
// BEFOREimport com.google.ai.client.generativeai.Chat import com.google.ai.client.generativeai.type.Content import com.google.ai.client.generativeai.java.GenerativeModuleFutures...val generativeModel = GenerativeModel(modelName = "MODEL_NAME", // Access your API key as a Build Configuration variable apiKey = BuildConfig.apiKey )// AFTER import com.google.firebase.Firebase import com.google.firebase.ai.ai import com.google.firebase.ai.type.GenerativeBackend ... // Initialize the Gemini Developer API backend service. // Create a `GenerativeModel` instance with a model that supports your use case. val model = Firebase.ai(backend = GenerativeBackend.googleAI()) .generativeModel("gemini-3.7-flash")
Java
// BEFOREimport com.google.ai.client.generativeai.Chat; import com.google.ai.client.generativeai.type.Content; import com.google.ai.client.generativeai.java.GenerativeModuleFutures;...GenerativeModel gm = new GenerativeModel("MODEL_NAME", // Access your API key as a Build Configuration variable BuildConfig.apiKey ); GenerativeModelFutures model = GenerativeModelFutures.from(gm);// AFTER import com.google.firebase.ai.FirebaseAI; import com.google.firebase.ai.GenerativeModel; import com.google.firebase.ai.java.GenerativeModelFutures; import com.google.firebase.ai.type.GenerativeBackend; ... // Initialize the Gemini Developer API backend service. // Create a `GenerativeModel` instance with a model that supports your use case. GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI()) .generativeModel("gemini-3.7-flash"); // Use the GenerativeModelFutures Java compatibility layer which offers // support for ListenableFuture and Publisher APIs GenerativeModelFutures model = GenerativeModelFutures.from(ai);
Web
// BEFOREimport { GoogleGenerativeAI } from "@google/generative-ai"; // Fetch your API_KEY and access your API const API_KEY = "..."; const genAI = new GoogleGenerativeAI(API_KEY);...const model = genAI.getGenerativeModel({ model: "MODEL_NAME"});// AFTER import { initializeApp } from "firebase/app"; import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai"; // TODO(developer): Replace the following with your app's Firebase configuration // See: https://firebase.google.com/docs/web/learn-more#config-object const firebaseConfig = { // ... }; // Initialize FirebaseApp const firebaseApp = initializeApp(firebaseConfig); // Initialize the Gemini Developer API backend service. const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() }); // Create a `GenerativeModel` instance with a model that supports your use case. const model = getGenerativeModel(ai, { model: "gemini-3.7-flash" });
Dart
// BEFOREimport 'package:google_generative_ai/google_generative_ai.dart'; final apiKey = Platform.environment['API_KEY']; if (apiKey == null) { print('No \$API_KEY environment variable'); exit(1); } final model = GenerativeModel(model: 'MODEL_NAME', apiKey: apiKey);// AFTER import 'package:firebase_ai/firebase_ai.dart'; import 'package:firebase_core/firebase_core.dart'; import 'firebase_options.dart'; // Initialize FirebaseApp await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); // Initialize the Gemini Developer API backend service // Create a `GenerativeModel` instance with a model that supports your use case final model = FirebaseAI.googleAI().generativeModel(model: 'gemini-3.7-flash');
Единство
Support for Unity wasn't available from Google AI client SDKs.
Learn how to get started with the Firebase AI Logic SDK for Unity .
Note that depending on the capability you're using, you might not always create a GenerativeModel instance . To stream input and output using the Gemini Live API , create a LiveModel instance.
Step 4 : Update code depending on the features that you use
This step describes changes that may be required depending on which features you use.
The Firebase AI Logic client SDKs don't support code execution. If you use this feature, make sure to accommodate this in your app.
Review the following lists for any changes that you might need to make in your code to accommodate migrating to the Firebase AI Logic client SDKs.
Required for all languages and platforms
Вызов функции
If you implemented this feature, then you'll need to make updates to how you define your schema. We recommend reviewing the updated function calling guide to learn how to write your function declarations.Generating structured output (like JSON) using
responseSchema
If you implemented this feature, then you'll need to make updates to how you define your schema. We recommend reviewing the new structured output guide to learn how to write JSON schemas.Тайм-аут
- Changed the default timeout for requests to be 180 seconds.
Required based on platform or language
Быстрый
Enumerations
Replaced most
enumtypes withstructs with static variables. This change allows more flexibility for evolving the API in a backward-compatible way. When usingswitchstatements, you must now include adefault:case to cover unknown or unhandled values, including new values that are added to the SDK in the future.Renamed the
BlockThresholdenumeration toHarmBlockThreshold; this type is now astruct.Removed
unknownandunspecifiedcases from the following enumerations (nowstructs):HarmCategory,HarmBlockThreshold,HarmProbability,BlockReason, andFinishReason.Replaced the enumeration
ModelContent.Partwith a protocol namedPartto allow new types to be added in a backward-compatible way. This change is described in greater detail in the Content parts section.
Content parts
Removed the
ThrowingPartsRepresentableprotocol, and simplified the initializers forModelContentto avoid occasional compiler errors. Images that don't encode properly will still throw errors when being used ingenerateContent.Replaced the
ModelContent.Partcases with the followingstructtypes conforming to thePartprotocol:-
.texttoTextPart -
.datatoInlineDataPart -
.fileDatatoFileDataPart -
.functionCalltoFunctionCallPart -
.functionResponsetoFunctionResponsePart
-
Harm category
- Changed the
HarmCategoryto no longer be nested in theSafetySettingtype. If you're referring to it asSafetySetting.HarmCategory, that can be replaced withHarmCategory.
- Changed the
Safety feedback
- Removed the
SafetyFeedbacktype, since it wasn't used in any of the responses.
- Removed the
Метаданные цитирования
- Renamed the
citationSourcesproperty tocitationsinCitationMetadata.
- Renamed the
Total billable characters
- Changed the
totalBillableCharactersproperty inCountTokensResponseto be optional to reflect situations where no characters are sent.
- Changed the
Candidate response
- Renamed
CandidateResponsetoCandidateto match other platforms.
- Renamed
Generation configuration
- Changed the public properties of
GenerationConfigtointernal. They all remain configurable in the initializer.
- Changed the public properties of
Kotlin
Enumerations
Replaced
enumclasses andsealedclasses with regular classes. This change allows more flexibility for evolving the API in a backward compatible way.Renamed the
BlockThresholdenumeration toHarmBlockThreshold.Removed values from the following enumerations:
HarmBlockThreshold,HarmProbability,HarmSeverity,BlockReason, andFinishReason.
Blob methods
- Renamed all methods that included
Blobas part of their name to useInlineDatainstead.
- Renamed all methods that included
Настройки безопасности
- Changed the field
methodto be nullable.
- Changed the field
Duration class
- Removed all usages of Kotlin's
Durationclass, and replaced it withlong. This change provides better interoperability with Java.
- Removed all usages of Kotlin's
Метаданные цитирования
- Wrapped all the fields previously declared in
CitationMetadatainto a new class calledCitation. Citations can be found in the list calledcitationsinCitationMetadata. This change allows better alignment of types across platforms.
- Wrapped all the fields previously declared in
Подсчет токенов
- Changed the field
totalBillableCharactersto be nullable.
- Changed the field
Total billable characters
- Changed the
totalBillableCharactersproperty inCountTokensResponseto be optional to reflect situations where no characters are sent.
- Changed the
Instantiating a model
- Moved the
requestOptionsparameter to the end of the parameter list to align with other platforms.
- Moved the
Java
Enumerations
Replaced
enumclasses andsealedclasses with regular classes. This change allows more flexibility for evolving the API in a backward compatible way.Renamed the
BlockThresholdenumeration toHarmBlockThreshold.Removed values from the following enumerations:
HarmBlockThreshold,HarmProbability,HarmSeverity,BlockReason, andFinishReason.
Blob methods
- Renamed all methods that included
Blobas part of their name to useInlineDatainstead.
- Renamed all methods that included
Настройки безопасности
- Changed the field
methodto be nullable.
- Changed the field
Duration class
- Removed all usages of Kotlin's
Durationclass, and replaced it withlong. This change provides better interoperability with Java.
- Removed all usages of Kotlin's
Метаданные цитирования
- Wrapped all the fields previously declared in
CitationMetadatainto a new class calledCitation. Citations can be found in the list calledcitationsinCitationMetadata. This change allows better alignment of types across platforms.
- Wrapped all the fields previously declared in
Подсчет токенов
- Changed the field
totalBillableCharactersto be nullable.
- Changed the field
Total billable characters
- Changed the
totalBillableCharactersproperty inCountTokensResponseto be optional to reflect situations where no characters are sent.
- Changed the
Instantiating a model
- Moved the
requestOptionsparameter to the end of the parameter list to align with other platforms.
- Moved the
Web
Note that the Google AI client SDK for JavaScript has had many changes since the time that the Firebase AI Logic client SDKs branched from it. The following list are some potential changes that you might need to consider as you migrate to the Firebase AI Logic client SDKs.
Enumerations
- Removed values from the following enumerations:
HarmCategory,BlockThreshold,HarmProbability,HarmSeverity,BlockReason, andFinishReason.
- Removed values from the following enumerations:
Block reason
- Changed
blockReasoninPromptFeedbackto be optional.
- Changed
Search Grounding
- Removed all usages of this feature, since it's not yet supported in the Firebase AI Logic SDKs.
Ошибки
- Removed all usages of
GoogleGenerativeAIError, and optionally move toAIError.
- Removed all usages of
Dart
Enumerations
- Removed values from the following enumerations:
HarmCategory,HarmProbability,BlockReason, andFinishReason.
- Removed values from the following enumerations:
Data part
- Renamed
DataParttoInlineDataPart, and thestaticdatafunction toinlineDatato align with other platforms.
- Renamed
Варианты запроса
- Removed
RequestOptionssincetimeoutwasn't functional. It will be re-added in the near future, but it will be moved to theGenerativeModeltype to match other platforms.
- Removed
Stop sequences
- Changed the
stopSequencesparameter inGenerationConfigto be optional and to default tonullinstead of an empty array.
- Changed the
Цитаты
- Renamed the
citationSourcesproperty tocitationsinCitationMetadata. TheCitationSourcetype was renamed toCitationto match other platforms.
- Renamed the
Unnecessary public types, methods, and properties
- Removed the following types, methods, and properties which were unintentionally exposed:
defaultTimeout,CountTokensResponseFields,parseCountTokensResponse,parseEmbedContentResponse,parseGenerateContentResponse,parseContent,BatchEmbedContentsResponse,ContentEmbedding,EmbedContentRequest, andEmbedContentResponse.
- Removed the following types, methods, and properties which were unintentionally exposed:
Подсчет токенов
- Removed extra fields from the
countTokensfunction that are no longer necessary. Onlycontentsis needed.
- Removed extra fields from the
Instantiating a model
- Moved the
systemInstructionparameter to the end of the parameter list to align with other platforms.
- Moved the
Embedding functionality
- Removed unsupported embedding functionality (
embedContentandbatchEmbedContents) from the model.
- Removed unsupported embedding functionality (
Единство
Support for Unity wasn't available from Google AI client SDKs.
Learn how to get started with the Firebase AI Logic SDK for Unity .
Give feedback about your experience with Firebase AI Logic
Go directly to migration instructions
Why migrate to use the Firebase AI Logic SDKs?
You might have tried out an alternative set of mobile or web client SDKs that gave you access to the Gemini Developer API .
Those client SDKs were not integrated into the robust Firebase ecosystem that offers critical services for mobile and web apps. They are now deprecated in favor of the Firebase AI Logic client SDKs, which can give you access to the Gemini Developer API .
Security features for mobile and web apps
For mobile and web apps, security is critical and requires special considerations because your code – including calls to the Gemini API – is running in an unprotected environment. You can use Firebase App Check to protect APIs from abuse by unauthorized clients.
When you use Firebase App Check with Firebase AI Logic , you never add your Gemini API key for the Gemini Developer API directly into your mobile or web app's codebase. Instead, the Gemini API key stays on the server, unexposed to malicious actors.
Ecosystem built for mobile and web apps
Firebase is Google's platform for developing mobile and web apps. Using Firebase AI Logic means that your apps are in an ecosystem that's focused on the needs of full-stack apps and developers. For example:
Dynamically set run-time configurations or swap out values in your app (like a model name and version) without releasing a new app version using Firebase Remote Config .
Use Cloud Storage for Firebase to include large files in your multimodal requests (if you use the Agent Platform Gemini API (formerly Vertex AI) ). The Cloud Storage client SDKs help you handle file uploads and downloads (even in poor network conditions) and offer more security for your end-users' data. Learn more in our solution guide about using Cloud Storage for Firebase .
Manage structured data using database SDKs built for mobile and web apps (like Cloud Firestore ).
Migrate to the Firebase AI Logic SDKs
Overview of steps to migrate to the Firebase AI Logic SDKs:
Step 1 : Set up a new or existing Firebase project and connect your app to Firebase.
Step 2 : Add the Firebase AI Logic SDKs to your app.
Step 3 : Update your imports and initialization in your app.
Step 4 : Update your code depending on the features that you use.
Step 1 : Set up a Firebase project and connect your app
Sign into the Firebase console , and then select your Firebase project.
If you don't already have a Firebase project, click the button to create a new Firebase project, and then use either of the following options:
Option 1 : Create a wholly new Firebase project (and its underlying Google Cloud project automatically) by entering a new project name in the first step of the workflow.
Option 2 : "Add Firebase" to an existing Google Cloud project by clicking Add Firebase to Google Cloud project (at bottom of page). In the first step of the workflow, start entering the project name of the existing project, and then select the project from the displayed list.
If you'd like, you can add Firebase to the project that was created behind the scenes when you created a Gemini API key in Google AI Studio .
Complete the remaining steps of the on-screen workflow to create a Firebase project. Note that when prompted, you do not need to set up Google Analytics to use the Firebase AI Logic SDKs.
In the Firebase console, go to AI Services > AI Logic .
Click Get started to launch a guided workflow that helps you set up the required APIs and resources for your project.
Select the Gemini Developer API . You can always set up and use the other API provider later, if you'd like.
The console will enable the required APIs and create a new, dedicated Gemini API key in your project.
Do not add this new Gemini API key into your app's codebase. Learn more.If prompted in the console's workflow, follow the on-screen instructions to register your app and connect it to Firebase.
Continue in this migration guide to update the library and initialization in your app.
Step 2 : Add the Firebase AI Logic SDK to your app
With your Firebase project set up and your app connected to Firebase (see previous step), you can now add the Firebase AI Logic SDK to your app.
Быстрый
Use Swift Package Manager to install and manage Firebase dependencies. Learn about other installation options , if needed.
The Firebase AI Logic library provides access to the APIs for interacting with Gemini models. The library is included as part of the Firebase SDK for Apple platforms ( firebase-ios-sdk ).
If you're already using Firebase, then make sure your Firebase package is v12.5.0 or later.
In Xcode, with your app project open, navigate to File > Add Package Dependencies .
When prompted, add the Firebase Apple platforms SDK repository:
https://github.com/firebase/firebase-ios-sdkSelect the latest SDK version.
Select the
FirebaseAILogiclibrary and theFirebaseAppChecklibrary.
When finished, Xcode will automatically begin resolving and downloading your dependencies in the background.
Kotlin
The Firebase AI Logic SDK for Android ( firebase-ai ) provides access to the APIs for interacting with Gemini models.
In your module (app-level) Gradle file (like <project>/<app-module>/build.gradle.kts ), add the dependencies for the Firebase AI Logic and App Check libraries for Android. We recommend using the Firebase Android BoM to control library versioning.
dependencies { // ... other androidx dependencies // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.18.0")) // Add the dependencies for the Firebase AI Logic and App Check libraries // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-ai") implementation("com.google.firebase:firebase-appcheck-debug") }
By using the Firebase Android BoM , your app will always use compatible versions of Firebase Android libraries.
If you choose not to use the Firebase BoM , you must specify each Firebase library version in its dependency line.
Note that if you use multiple Firebase libraries in your app, we strongly recommend using the BoM to manage library versions, which ensures that all versions are compatible.
dependencies { // Add the dependencies for the Firebase AI Logic and App Check libraries // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-ai:17.16.0") implementation("com.google.firebase:firebase-appcheck-debug:19.4.1") }
Java
The Firebase AI Logic SDK for Android ( firebase-ai ) provides access to the APIs for interacting with Gemini models.
In your module (app-level) Gradle file (like <project>/<app-module>/build.gradle.kts ), add the dependencies for the Firebase AI Logic and App Check libraries for Android. We recommend using the Firebase Android BoM to control library versioning.
For Java, you need to add two additional libraries.
dependencies { // ... other androidx dependencies // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.18.0")) // Add the dependencies for the Firebase AI Logic and App Check libraries // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-ai") implementation("com.google.firebase:firebase-appcheck-debug") // Required for one-shot operations (to use `ListenableFuture` from Guava Android) implementation("com.google.guava:guava:31.0.1-android") // Required for streaming operations (to use `Publisher` from Reactive Streams) implementation("org.reactivestreams:reactive-streams:1.0.4") }
By using the Firebase Android BoM , your app will always use compatible versions of Firebase Android libraries.
If you choose not to use the Firebase BoM , you must specify each Firebase library version in its dependency line.
Note that if you use multiple Firebase libraries in your app, we strongly recommend using the BoM to manage library versions, which ensures that all versions are compatible.
dependencies { // Add the dependencies for the Firebase AI Logic and App Check libraries // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-ai:17.16.0") implementation("com.google.firebase:firebase-appcheck-debug:19.4.1") }
Web
The Firebase AI Logic library provides access to the APIs for interacting with Gemini models. The library is included as part of the Firebase JavaScript SDK for Web.
Install the Firebase JS SDK for Web using npm:
npm install firebaseInitialize Firebase in your app:
import { initializeApp } from "firebase/app"; import { initializeAppCheck, DebugProvider } from "firebase/app-check"; // TODO(developer) Replace the following with your app's Firebase configuration // See: https://firebase.google.com/docs/web/learn-more#config-object const firebaseConfig = { // ... }; // Initialize FirebaseApp const firebaseApp = initializeApp(firebaseConfig);
Dart
The Firebase AI Logic plugin for Flutter ( firebase_ai ) provides access to the APIs for interacting with Gemini models.
From your Flutter project directory, run the following command to install the Firebase AI Logic and App Check plugins:
flutter pub add firebase_ai firebase_app_checkIn your
lib/main.dartfile, import the Firebase AI Logic and App Check plugins:import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_ai/firebase_ai.dart'; import 'package:firebase_app_check/firebase_app_check.dart'; import 'firebase_options.dart';Also in your
lib/main.dartfile, make sure that you've initialized Firebase using theDefaultFirebaseOptionsobject exported by the configuration file:await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, );Пересоберите ваше Flutter-приложение:
flutter run
Единство
Support for Unity wasn't available from the Google AI client SDKs.
Learn how to get started with the Firebase AI Logic SDK for Unity .
Remove the old SDK from your app
After you've finished migrating your app (see the remaining sections in this guide), make sure to delete the old library.
Быстрый
Remove the old library:
In Xcode, with your app project open, navigate to the Packages Dependencies pane.
Select the
generative-ai-swiftpackage from the list of package dependencies.Click the
-button from the bottom of the list and click Remove to confirm.
Kotlin
dependencies {
implementation("com.google.ai.client.generativeai:generativeai:VERSION")
}
Java
dependencies {
implementation("com.google.ai.client.generativeai:generativeai:VERSION")
}
Web
// BEFORE
import { initializeApp } from "firebase/app";
import { GoogleGenerativeAI } from "@google/generative-ai";
Dart
Delete the old package:
flutter pub remove google_generative_ai
Единство
Support for Unity wasn't available from Google AI client SDKs.
Learn how to get started with the Firebase AI Logic SDK for Unity .
Step 3 : Update your imports and initialization in your app
Update your imports and how you initialize the Gemini Developer API backend service and create a GenerativeModel instance.
Быстрый
// BEFOREimport GoogleGenerativeAI let model = GenerativeModel(name: "MODEL_NAME", apiKey: APIKey.default)// AFTER import FirebaseAILogic // Initialize the Gemini Developer API backend service let ai = FirebaseAI.firebaseAI(backend: .googleAI()) // Create a `GenerativeModel` instance with a model that supports your use case let model = ai.generativeModel(modelName: "gemini-3.7-flash")
Kotlin
// BEFOREimport com.google.ai.client.generativeai.Chat import com.google.ai.client.generativeai.type.Content import com.google.ai.client.generativeai.java.GenerativeModuleFutures...val generativeModel = GenerativeModel(modelName = "MODEL_NAME", // Access your API key as a Build Configuration variable apiKey = BuildConfig.apiKey )// AFTER import com.google.firebase.Firebase import com.google.firebase.ai.ai import com.google.firebase.ai.type.GenerativeBackend ... // Initialize the Gemini Developer API backend service. // Create a `GenerativeModel` instance with a model that supports your use case. val model = Firebase.ai(backend = GenerativeBackend.googleAI()) .generativeModel("gemini-3.7-flash")
Java
// BEFOREimport com.google.ai.client.generativeai.Chat; import com.google.ai.client.generativeai.type.Content; import com.google.ai.client.generativeai.java.GenerativeModuleFutures;...GenerativeModel gm = new GenerativeModel("MODEL_NAME", // Access your API key as a Build Configuration variable BuildConfig.apiKey ); GenerativeModelFutures model = GenerativeModelFutures.from(gm);// AFTER import com.google.firebase.ai.FirebaseAI; import com.google.firebase.ai.GenerativeModel; import com.google.firebase.ai.java.GenerativeModelFutures; import com.google.firebase.ai.type.GenerativeBackend; ... // Initialize the Gemini Developer API backend service. // Create a `GenerativeModel` instance with a model that supports your use case. GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI()) .generativeModel("gemini-3.7-flash"); // Use the GenerativeModelFutures Java compatibility layer which offers // support for ListenableFuture and Publisher APIs GenerativeModelFutures model = GenerativeModelFutures.from(ai);
Web
// BEFOREimport { GoogleGenerativeAI } from "@google/generative-ai"; // Fetch your API_KEY and access your API const API_KEY = "..."; const genAI = new GoogleGenerativeAI(API_KEY);...const model = genAI.getGenerativeModel({ model: "MODEL_NAME"});// AFTER import { initializeApp } from "firebase/app"; import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai"; // TODO(developer): Replace the following with your app's Firebase configuration // See: https://firebase.google.com/docs/web/learn-more#config-object const firebaseConfig = { // ... }; // Initialize FirebaseApp const firebaseApp = initializeApp(firebaseConfig); // Initialize the Gemini Developer API backend service. const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() }); // Create a `GenerativeModel` instance with a model that supports your use case. const model = getGenerativeModel(ai, { model: "gemini-3.7-flash" });
Dart
// BEFOREimport 'package:google_generative_ai/google_generative_ai.dart'; final apiKey = Platform.environment['API_KEY']; if (apiKey == null) { print('No \$API_KEY environment variable'); exit(1); } final model = GenerativeModel(model: 'MODEL_NAME', apiKey: apiKey);// AFTER import 'package:firebase_ai/firebase_ai.dart'; import 'package:firebase_core/firebase_core.dart'; import 'firebase_options.dart'; // Initialize FirebaseApp await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); // Initialize the Gemini Developer API backend service // Create a `GenerativeModel` instance with a model that supports your use case final model = FirebaseAI.googleAI().generativeModel(model: 'gemini-3.7-flash');
Единство
Support for Unity wasn't available from Google AI client SDKs.
Learn how to get started with the Firebase AI Logic SDK for Unity .
Note that depending on the capability you're using, you might not always create a GenerativeModel instance . To stream input and output using the Gemini Live API , create a LiveModel instance.
Step 4 : Update code depending on the features that you use
This step describes changes that may be required depending on which features you use.
The Firebase AI Logic client SDKs don't support code execution. If you use this feature, make sure to accommodate this in your app.
Review the following lists for any changes that you might need to make in your code to accommodate migrating to the Firebase AI Logic client SDKs.
Required for all languages and platforms
Вызов функции
If you implemented this feature, then you'll need to make updates to how you define your schema. We recommend reviewing the updated function calling guide to learn how to write your function declarations.Generating structured output (like JSON) using
responseSchema
If you implemented this feature, then you'll need to make updates to how you define your schema. We recommend reviewing the new structured output guide to learn how to write JSON schemas.Тайм-аут
- Changed the default timeout for requests to be 180 seconds.
Required based on platform or language
Быстрый
Enumerations
Replaced most
enumtypes withstructs with static variables. This change allows more flexibility for evolving the API in a backward-compatible way. When usingswitchstatements, you must now include adefault:case to cover unknown or unhandled values, including new values that are added to the SDK in the future.Renamed the
BlockThresholdenumeration toHarmBlockThreshold; this type is now astruct.Removed
unknownandunspecifiedcases from the following enumerations (nowstructs):HarmCategory,HarmBlockThreshold,HarmProbability,BlockReason, andFinishReason.Replaced the enumeration
ModelContent.Partwith a protocol namedPartto allow new types to be added in a backward-compatible way. This change is described in greater detail in the Content parts section.
Content parts
Removed the
ThrowingPartsRepresentableprotocol, and simplified the initializers forModelContentto avoid occasional compiler errors. Images that don't encode properly will still throw errors when being used ingenerateContent.Replaced the
ModelContent.Partcases with the followingstructtypes conforming to thePartprotocol:-
.texttoTextPart -
.datatoInlineDataPart -
.fileDatatoFileDataPart -
.functionCalltoFunctionCallPart -
.functionResponsetoFunctionResponsePart
-
Harm category
- Changed the
HarmCategoryto no longer be nested in theSafetySettingtype. If you're referring to it asSafetySetting.HarmCategory, that can be replaced withHarmCategory.
- Changed the
Safety feedback
- Removed the
SafetyFeedbacktype, since it wasn't used in any of the responses.
- Removed the
Метаданные цитирования
- Renamed the
citationSourcesproperty tocitationsinCitationMetadata.
- Renamed the
Total billable characters
- Changed the
totalBillableCharactersproperty inCountTokensResponseto be optional to reflect situations where no characters are sent.
- Changed the
Candidate response
- Renamed
CandidateResponsetoCandidateto match other platforms.
- Renamed
Generation configuration
- Changed the public properties of
GenerationConfigtointernal. They all remain configurable in the initializer.
- Changed the public properties of
Kotlin
Enumerations
Replaced
enumclasses andsealedclasses with regular classes. This change allows more flexibility for evolving the API in a backward compatible way.Renamed the
BlockThresholdenumeration toHarmBlockThreshold.Removed values from the following enumerations:
HarmBlockThreshold,HarmProbability,HarmSeverity,BlockReason, andFinishReason.
Blob methods
- Renamed all methods that included
Blobas part of their name to useInlineDatainstead.
- Renamed all methods that included
Настройки безопасности
- Changed the field
methodto be nullable.
- Changed the field
Duration class
- Removed all usages of Kotlin's
Durationclass, and replaced it withlong. This change provides better interoperability with Java.
- Removed all usages of Kotlin's
Метаданные цитирования
- Wrapped all the fields previously declared in
CitationMetadatainto a new class calledCitation. Citations can be found in the list calledcitationsinCitationMetadata. This change allows better alignment of types across platforms.
- Wrapped all the fields previously declared in
Подсчет токенов
- Changed the field
totalBillableCharactersto be nullable.
- Changed the field
Total billable characters
- Changed the
totalBillableCharactersproperty inCountTokensResponseto be optional to reflect situations where no characters are sent.
- Changed the
Instantiating a model
- Moved the
requestOptionsparameter to the end of the parameter list to align with other platforms.
- Moved the
Java
Enumerations
Replaced
enumclasses andsealedclasses with regular classes. This change allows more flexibility for evolving the API in a backward compatible way.Renamed the
BlockThresholdenumeration toHarmBlockThreshold.Removed values from the following enumerations:
HarmBlockThreshold,HarmProbability,HarmSeverity,BlockReason, andFinishReason.
Blob methods
- Renamed all methods that included
Blobas part of their name to useInlineDatainstead.
- Renamed all methods that included
Настройки безопасности
- Changed the field
methodto be nullable.
- Changed the field
Duration class
- Removed all usages of Kotlin's
Durationclass, and replaced it withlong. This change provides better interoperability with Java.
- Removed all usages of Kotlin's
Метаданные цитирования
- Wrapped all the fields previously declared in
CitationMetadatainto a new class calledCitation. Citations can be found in the list calledcitationsinCitationMetadata. This change allows better alignment of types across platforms.
- Wrapped all the fields previously declared in
Подсчет токенов
- Changed the field
totalBillableCharactersto be nullable.
- Changed the field
Total billable characters
- Changed the
totalBillableCharactersproperty inCountTokensResponseto be optional to reflect situations where no characters are sent.
- Changed the
Instantiating a model
- Moved the
requestOptionsparameter to the end of the parameter list to align with other platforms.
- Moved the
Web
Note that the Google AI client SDK for JavaScript has had many changes since the time that the Firebase AI Logic client SDKs branched from it. The following list are some potential changes that you might need to consider as you migrate to the Firebase AI Logic client SDKs.
Enumerations
- Removed values from the following enumerations:
HarmCategory,BlockThreshold,HarmProbability,HarmSeverity,BlockReason, andFinishReason.
- Removed values from the following enumerations:
Block reason
- Changed
blockReasoninPromptFeedbackto be optional.
- Changed
Search Grounding
- Removed all usages of this feature, since it's not yet supported in the Firebase AI Logic SDKs.
Ошибки
- Removed all usages of
GoogleGenerativeAIError, and optionally move toAIError.
- Removed all usages of
Dart
Enumerations
- Removed values from the following enumerations:
HarmCategory,HarmProbability,BlockReason, andFinishReason.
- Removed values from the following enumerations:
Data part
- Renamed
DataParttoInlineDataPart, and thestaticdatafunction toinlineDatato align with other platforms.
- Renamed
Варианты запроса
- Removed
RequestOptionssincetimeoutwasn't functional. It will be re-added in the near future, but it will be moved to theGenerativeModeltype to match other platforms.
- Removed
Stop sequences
- Changed the
stopSequencesparameter inGenerationConfigto be optional and to default tonullinstead of an empty array.
- Changed the
Цитаты
- Renamed the
citationSourcesproperty tocitationsinCitationMetadata. TheCitationSourcetype was renamed toCitationto match other platforms.
- Renamed the
Unnecessary public types, methods, and properties
- Removed the following types, methods, and properties which were unintentionally exposed:
defaultTimeout,CountTokensResponseFields,parseCountTokensResponse,parseEmbedContentResponse,parseGenerateContentResponse,parseContent,BatchEmbedContentsResponse,ContentEmbedding,EmbedContentRequest, andEmbedContentResponse.
- Removed the following types, methods, and properties which were unintentionally exposed:
Подсчет токенов
- Removed extra fields from the
countTokensfunction that are no longer necessary. Onlycontentsis needed.
- Removed extra fields from the
Instantiating a model
- Moved the
systemInstructionparameter to the end of the parameter list to align with other platforms.
- Moved the
Embedding functionality
- Removed unsupported embedding functionality (
embedContentandbatchEmbedContents) from the model.
- Removed unsupported embedding functionality (
Единство
Support for Unity wasn't available from Google AI client SDKs.
Learn how to get started with the Firebase AI Logic SDK for Unity .
Give feedback about your experience with Firebase AI Logic