Переход на Firebase AI Logic SDKs с клиентских AI SDK Google


Перейдите непосредственно к инструкциям по миграции.

Почему стоит перейти на использование 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 и подключите к нему ваше приложение.

  1. Войдите в консоль Firebase , а затем выберите свой проект Firebase.

  2. В консоли Firebase перейдите в раздел AI Services > AI Logic .

  3. Нажмите « Начать» , чтобы запустить пошаговый рабочий процесс, который поможет вам настроить необходимые API и ресурсы для вашего проекта.

  4. Выберите API разработчика Gemini . При желании вы всегда сможете настроить и использовать другой поставщик API позже.

    Консоль активирует необходимые API и создаст новый, выделенный ключ API Gemini в вашем проекте.
    Не добавляйте этот новый ключ API Gemini в код вашего приложения. Узнайте больше.

  5. Если в процессе работы консоли появится соответствующее сообщение, следуйте инструкциям на экране, чтобы зарегистрировать ваше приложение и подключить его к Firebase.

  6. Продолжите выполнение инструкций в этом руководстве по миграции, чтобы обновить библиотеку и выполнить инициализацию в вашем приложении.

Шаг 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 или более поздняя.

  1. В Xcode, открыв проект приложения, перейдите в меню File > Add Package Dependencies .

  2. При появлении запроса добавьте репозиторий Firebase Apple Platforms SDK:

    https://github.com/firebase/firebase-ios-sdk
    
  3. Выберите последнюю версию SDK.

  4. Выберите библиотеку 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.

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.

Web

Библиотека Firebase AI Logic предоставляет доступ к API для взаимодействия с моделями Gemini . Библиотека входит в состав Firebase JavaScript SDK для веб-приложений.

  1. Установите Firebase JS SDK для веб-разработки с помощью npm:

    npm install firebase
    
  2. Инициализируйте 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 .

  1. Для установки плагинов Firebase AI Logic и App Check из каталога вашего проекта Flutter выполните следующую команду:

    flutter pub add firebase_ai firebase_app_check
    
  2. В файле 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';
    
  3. Также в файле lib/main.dart убедитесь, что вы инициализировали Firebase, используя объект DefaultFirebaseOptions , экспортируемый из файла конфигурации:

    await Firebase.initializeApp(
      options: DefaultFirebaseOptions.currentPlatform,
    );
    
  4. Пересоберите ваше Flutter-приложение:

    flutter run
    

Единство

Поддержка Unity отсутствовала в SDK клиента Google AI .

Узнайте, как начать работу с Firebase AI Logic SDK для Unity .

Удалите старый SDK из вашего приложения.

После завершения миграции приложения (см. остальные разделы этого руководства) обязательно удалите старую библиотеку.

Быстрый

Удалите старую библиотеку:

  1. В Xcode, открыв проект приложения, перейдите в панель «Пакеты и зависимости» .

  2. Выберите пакет generative-ai-swift из списка зависимостей пакетов.

  3. Нажмите кнопку - внизу списка и нажмите «Удалить» для подтверждения.

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 .

Быстрый

// BEFORE
import 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

// BEFORE
import 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

// BEFORE
import 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

// BEFORE
import { 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

// BEFORE
import '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 :

      • .text to TextPart
      • .data to InlineDataPart
      • .fileData to FileDataPart
      • .functionCall to FunctionCallPart
      • .functionResponse to FunctionResponsePart
  • Категория вреда

    • Изменено представление 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 , а функцию static data — в 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 и подключите к нему ваше приложение.

  1. Войдите в консоль Firebase , а затем выберите свой проект Firebase.

  2. В консоли Firebase перейдите в раздел AI Services > AI Logic .

  3. Нажмите « Начать» , чтобы запустить пошаговый рабочий процесс, который поможет вам настроить необходимые API и ресурсы для вашего проекта.

  4. Выберите API разработчика Gemini . При желании вы всегда сможете настроить и использовать другой поставщик API позже.

    Консоль активирует необходимые API и создаст новый, выделенный ключ API Gemini в вашем проекте.
    Не добавляйте этот новый ключ API Gemini в код вашего приложения. Узнайте больше.

  5. Если в процессе работы консоли появится соответствующее сообщение, следуйте инструкциям на экране, чтобы зарегистрировать ваше приложение и подключить его к Firebase.

  6. Продолжите выполнение инструкций в этом руководстве по миграции, чтобы обновить библиотеку и выполнить инициализацию в вашем приложении.

Шаг 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 или более поздняя.

  1. В Xcode, открыв проект приложения, перейдите в меню File > Add Package Dependencies .

  2. При появлении запроса добавьте репозиторий Firebase Apple Platforms SDK:

    https://github.com/firebase/firebase-ios-sdk
    
  3. Выберите последнюю версию SDK.

  4. Выберите библиотеку 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.

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.

Web

Библиотека Firebase AI Logic предоставляет доступ к API для взаимодействия с моделями Gemini . Библиотека входит в состав Firebase JavaScript SDK для веб-приложений.

  1. Установите Firebase JS SDK для веб-разработки с помощью npm:

    npm install firebase
    
  2. Инициализируйте 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 .

  1. Для установки плагинов Firebase AI Logic и App Check из каталога вашего проекта Flutter выполните следующую команду:

    flutter pub add firebase_ai firebase_app_check
    
  2. В файле 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';
    
  3. Также в файле lib/main.dart убедитесь, что вы инициализировали Firebase, используя объект DefaultFirebaseOptions , экспортируемый из файла конфигурации:

    await Firebase.initializeApp(
      options: DefaultFirebaseOptions.currentPlatform,
    );
    
  4. Пересоберите ваше Flutter-приложение:

    flutter run
    

Единство

Поддержка Unity отсутствовала в SDK клиента Google AI .

Узнайте, как начать работу с Firebase AI Logic SDK для Unity .

Удалите старый SDK из вашего приложения.

После завершения миграции приложения (см. остальные разделы этого руководства) обязательно удалите старую библиотеку.

Быстрый

Удалите старую библиотеку:

  1. В Xcode, открыв проект приложения, перейдите в панель «Пакеты и зависимости» .

  2. Выберите пакет generative-ai-swift из списка зависимостей пакетов.

  3. Нажмите кнопку - внизу списка и нажмите «Удалить» для подтверждения.

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 .

Быстрый

// BEFORE
import 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

// BEFORE
import 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

// BEFORE
import 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

// BEFORE
import { 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

// BEFORE
import '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 :

      • .text to TextPart
      • .data to InlineDataPart
      • .fileData to FileDataPart
      • .functionCall to FunctionCallPart
      • .functionResponse to FunctionResponsePart
  • Категория вреда

    • Изменено представление 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 totalBillableCharacters property in CountTokensResponse to be optional to reflect situations where no characters are sent.
  • Instantiating a model

    • Moved the requestOptions parameter to the end of the parameter list to align with other platforms.

Java

  • Enumerations

    • Replaced enum classes and sealed classes with regular classes. This change allows more flexibility for evolving the API in a backward compatible way.

    • Renamed the BlockThreshold enumeration to HarmBlockThreshold .

    • Removed values from the following enumerations: HarmBlockThreshold , HarmProbability , HarmSeverity , BlockReason , and FinishReason .

  • Blob methods

    • Renamed all methods that included Blob as part of their name to use InlineData instead.
  • Настройки безопасности

    • Changed the field method to be nullable.
  • Duration class

    • Removed all usages of Kotlin's Duration class, and replaced it with long . This change provides better interoperability with Java.
  • Метаданные цитирования

    • Wrapped all the fields previously declared in CitationMetadata into a new class called Citation . Citations can be found in the list called citations in CitationMetadata . This change allows better alignment of types across platforms.
  • Подсчет токенов

    • Changed the field totalBillableCharacters to be nullable.
  • Total billable characters

    • Changed the totalBillableCharacters property in CountTokensResponse to be optional to reflect situations where no characters are sent.
  • Instantiating a model

    • Moved the requestOptions parameter to the end of the parameter list to align with other platforms.

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 , and FinishReason .
  • Block reason

    • Changed blockReason in PromptFeedback to be optional.
  • 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 to AIError .

Dart

  • Enumerations

    • Removed values from the following enumerations: HarmCategory , HarmProbability , BlockReason , and FinishReason .
  • Data part

    • Renamed DataPart to InlineDataPart , and the static data function to inlineData to align with other platforms.
  • Варианты запроса

    • Removed RequestOptions since timeout wasn't functional. It will be re-added in the near future, but it will be moved to the GenerativeModel type to match other platforms.
  • Stop sequences

    • Changed the stopSequences parameter in GenerationConfig to be optional and to default to null instead of an empty array.
  • Цитаты

    • Renamed the citationSources property to citations in CitationMetadata . The CitationSource type was renamed to Citation to match other platforms.
  • 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 , and EmbedContentResponse .
  • Подсчет токенов

    • Removed extra fields from the countTokens function that are no longer necessary. Only contents is needed.
  • Instantiating a model

    • Moved the systemInstruction parameter to the end of the parameter list to align with other platforms.
  • Embedding functionality

    • Removed unsupported embedding functionality ( embedContent and batchEmbedContents ) from the model.

Единство

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

  1. Sign into the Firebase console , and then select your Firebase project.

  2. In the Firebase console, go to AI Services > AI Logic .

  3. Click Get started to launch a guided workflow that helps you set up the required APIs and resources for your project.

  4. 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.

  5. If prompted in the console's workflow, follow the on-screen instructions to register your app and connect it to Firebase.

  6. 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.

  1. In Xcode, with your app project open, navigate to File > Add Package Dependencies .

  2. When prompted, add the Firebase Apple platforms SDK repository:

    https://github.com/firebase/firebase-ios-sdk
    
  3. Select the latest SDK version.

  4. Select the FirebaseAILogic library and the FirebaseAppCheck library.

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.

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.

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.

  1. Install the Firebase JS SDK for Web using npm:

    npm install firebase
    
  2. Initialize 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.

  1. 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_check
    
  2. In your lib/main.dart file, 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';
    
  3. Also in your lib/main.dart file, make sure that you've initialized Firebase using the DefaultFirebaseOptions object exported by the configuration file:

    await Firebase.initializeApp(
      options: DefaultFirebaseOptions.currentPlatform,
    );
    
  4. Пересоберите ваше 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:

  1. In Xcode, with your app project open, navigate to the Packages Dependencies pane.

  2. Select the generative-ai-swift package from the list of package dependencies.

  3. 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.

Быстрый

// BEFORE
import 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

// BEFORE
import 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

// BEFORE
import 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

// BEFORE
import { 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

// BEFORE
import '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 enum types with struct s with static variables. This change allows more flexibility for evolving the API in a backward-compatible way. When using switch statements, you must now include a default: case to cover unknown or unhandled values, including new values that are added to the SDK in the future.

    • Renamed the BlockThreshold enumeration to HarmBlockThreshold ; this type is now a struct .

    • Removed unknown and unspecified cases from the following enumerations (now struct s): HarmCategory , HarmBlockThreshold , HarmProbability , BlockReason , and FinishReason .

    • Replaced the enumeration ModelContent.Part with a protocol named Part to 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 ThrowingPartsRepresentable protocol, and simplified the initializers for ModelContent to avoid occasional compiler errors. Images that don't encode properly will still throw errors when being used in generateContent .

    • Replaced the ModelContent.Part cases with the following struct types conforming to the Part protocol:

      • .text to TextPart
      • .data to InlineDataPart
      • .fileData to FileDataPart
      • .functionCall to FunctionCallPart
      • .functionResponse to FunctionResponsePart
  • Harm category

    • Changed the HarmCategory to no longer be nested in the SafetySetting type. If you're referring to it as SafetySetting.HarmCategory , that can be replaced with HarmCategory .
  • Safety feedback

    • Removed the SafetyFeedback type, since it wasn't used in any of the responses.
  • Метаданные цитирования

    • Renamed the citationSources property to citations in CitationMetadata .
  • Total billable characters

    • Changed the totalBillableCharacters property in CountTokensResponse to be optional to reflect situations where no characters are sent.
  • Candidate response

    • Renamed CandidateResponse to Candidate to match other platforms.
  • Generation configuration

    • Changed the public properties of GenerationConfig to internal . They all remain configurable in the initializer.

Kotlin

  • Enumerations

    • Replaced enum classes and sealed classes with regular classes. This change allows more flexibility for evolving the API in a backward compatible way.

    • Renamed the BlockThreshold enumeration to HarmBlockThreshold .

    • Removed values from the following enumerations: HarmBlockThreshold , HarmProbability , HarmSeverity , BlockReason , and FinishReason .

  • Blob methods

    • Renamed all methods that included Blob as part of their name to use InlineData instead.
  • Настройки безопасности

    • Changed the field method to be nullable.
  • Duration class

    • Removed all usages of Kotlin's Duration class, and replaced it with long . This change provides better interoperability with Java.
  • Метаданные цитирования

    • Wrapped all the fields previously declared in CitationMetadata into a new class called Citation . Citations can be found in the list called citations in CitationMetadata . This change allows better alignment of types across platforms.
  • Подсчет токенов

    • Changed the field totalBillableCharacters to be nullable.
  • Total billable characters

    • Changed the totalBillableCharacters property in CountTokensResponse to be optional to reflect situations where no characters are sent.
  • Instantiating a model

    • Moved the requestOptions parameter to the end of the parameter list to align with other platforms.

Java

  • Enumerations

    • Replaced enum classes and sealed classes with regular classes. This change allows more flexibility for evolving the API in a backward compatible way.

    • Renamed the BlockThreshold enumeration to HarmBlockThreshold .

    • Removed values from the following enumerations: HarmBlockThreshold , HarmProbability , HarmSeverity , BlockReason , and FinishReason .

  • Blob methods

    • Renamed all methods that included Blob as part of their name to use InlineData instead.
  • Настройки безопасности

    • Changed the field method to be nullable.
  • Duration class

    • Removed all usages of Kotlin's Duration class, and replaced it with long . This change provides better interoperability with Java.
  • Метаданные цитирования

    • Wrapped all the fields previously declared in CitationMetadata into a new class called Citation . Citations can be found in the list called citations in CitationMetadata . This change allows better alignment of types across platforms.
  • Подсчет токенов

    • Changed the field totalBillableCharacters to be nullable.
  • Total billable characters

    • Changed the totalBillableCharacters property in CountTokensResponse to be optional to reflect situations where no characters are sent.
  • Instantiating a model

    • Moved the requestOptions parameter to the end of the parameter list to align with other platforms.

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 , and FinishReason .
  • Block reason

    • Changed blockReason in PromptFeedback to be optional.
  • 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 to AIError .

Dart

  • Enumerations

    • Removed values from the following enumerations: HarmCategory , HarmProbability , BlockReason , and FinishReason .
  • Data part

    • Renamed DataPart to InlineDataPart , and the static data function to inlineData to align with other platforms.
  • Варианты запроса

    • Removed RequestOptions since timeout wasn't functional. It will be re-added in the near future, but it will be moved to the GenerativeModel type to match other platforms.
  • Stop sequences

    • Changed the stopSequences parameter in GenerationConfig to be optional and to default to null instead of an empty array.
  • Цитаты

    • Renamed the citationSources property to citations in CitationMetadata . The CitationSource type was renamed to Citation to match other platforms.
  • 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 , and EmbedContentResponse .
  • Подсчет токенов

    • Removed extra fields from the countTokens function that are no longer necessary. Only contents is needed.
  • Instantiating a model

    • Moved the systemInstruction parameter to the end of the parameter list to align with other platforms.
  • Embedding functionality

    • Removed unsupported embedding functionality ( embedContent and batchEmbedContents ) from the model.

Единство

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

  1. Sign into the Firebase console , and then select your Firebase project.

  2. In the Firebase console, go to AI Services > AI Logic .

  3. Click Get started to launch a guided workflow that helps you set up the required APIs and resources for your project.

  4. 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.

  5. If prompted in the console's workflow, follow the on-screen instructions to register your app and connect it to Firebase.

  6. 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.

  1. In Xcode, with your app project open, navigate to File > Add Package Dependencies .

  2. When prompted, add the Firebase Apple platforms SDK repository:

    https://github.com/firebase/firebase-ios-sdk
    
  3. Select the latest SDK version.

  4. Select the FirebaseAILogic library and the FirebaseAppCheck library.

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.

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.

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.

  1. Install the Firebase JS SDK for Web using npm:

    npm install firebase
    
  2. Initialize 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.

  1. 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_check
    
  2. In your lib/main.dart file, 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';
    
  3. Also in your lib/main.dart file, make sure that you've initialized Firebase using the DefaultFirebaseOptions object exported by the configuration file:

    await Firebase.initializeApp(
      options: DefaultFirebaseOptions.currentPlatform,
    );
    
  4. Пересоберите ваше 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:

  1. In Xcode, with your app project open, navigate to the Packages Dependencies pane.

  2. Select the generative-ai-swift package from the list of package dependencies.

  3. 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.

Быстрый

// BEFORE
import 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

// BEFORE
import 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

// BEFORE
import 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

// BEFORE
import { 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

// BEFORE
import '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 enum types with struct s with static variables. This change allows more flexibility for evolving the API in a backward-compatible way. When using switch statements, you must now include a default: case to cover unknown or unhandled values, including new values that are added to the SDK in the future.

    • Renamed the BlockThreshold enumeration to HarmBlockThreshold ; this type is now a struct .

    • Removed unknown and unspecified cases from the following enumerations (now struct s): HarmCategory , HarmBlockThreshold , HarmProbability , BlockReason , and FinishReason .

    • Replaced the enumeration ModelContent.Part with a protocol named Part to 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 ThrowingPartsRepresentable protocol, and simplified the initializers for ModelContent to avoid occasional compiler errors. Images that don't encode properly will still throw errors when being used in generateContent .

    • Replaced the ModelContent.Part cases with the following struct types conforming to the Part protocol:

      • .text to TextPart
      • .data to InlineDataPart
      • .fileData to FileDataPart
      • .functionCall to FunctionCallPart
      • .functionResponse to FunctionResponsePart
  • Harm category

    • Changed the HarmCategory to no longer be nested in the SafetySetting type. If you're referring to it as SafetySetting.HarmCategory , that can be replaced with HarmCategory .
  • Safety feedback

    • Removed the SafetyFeedback type, since it wasn't used in any of the responses.
  • Метаданные цитирования

    • Renamed the citationSources property to citations in CitationMetadata .
  • Total billable characters

    • Changed the totalBillableCharacters property in CountTokensResponse to be optional to reflect situations where no characters are sent.
  • Candidate response

    • Renamed CandidateResponse to Candidate to match other platforms.
  • Generation configuration

    • Changed the public properties of GenerationConfig to internal . They all remain configurable in the initializer.

Kotlin

  • Enumerations

    • Replaced enum classes and sealed classes with regular classes. This change allows more flexibility for evolving the API in a backward compatible way.

    • Renamed the BlockThreshold enumeration to HarmBlockThreshold .

    • Removed values from the following enumerations: HarmBlockThreshold , HarmProbability , HarmSeverity , BlockReason , and FinishReason .

  • Blob methods

    • Renamed all methods that included Blob as part of their name to use InlineData instead.
  • Настройки безопасности

    • Changed the field method to be nullable.
  • Duration class

    • Removed all usages of Kotlin's Duration class, and replaced it with long . This change provides better interoperability with Java.
  • Метаданные цитирования

    • Wrapped all the fields previously declared in CitationMetadata into a new class called Citation . Citations can be found in the list called citations in CitationMetadata . This change allows better alignment of types across platforms.
  • Подсчет токенов

    • Changed the field totalBillableCharacters to be nullable.
  • Total billable characters

    • Changed the totalBillableCharacters property in CountTokensResponse to be optional to reflect situations where no characters are sent.
  • Instantiating a model

    • Moved the requestOptions parameter to the end of the parameter list to align with other platforms.

Java

  • Enumerations

    • Replaced enum classes and sealed classes with regular classes. This change allows more flexibility for evolving the API in a backward compatible way.

    • Renamed the BlockThreshold enumeration to HarmBlockThreshold .

    • Removed values from the following enumerations: HarmBlockThreshold , HarmProbability , HarmSeverity , BlockReason , and FinishReason .

  • Blob methods

    • Renamed all methods that included Blob as part of their name to use InlineData instead.
  • Настройки безопасности

    • Changed the field method to be nullable.
  • Duration class

    • Removed all usages of Kotlin's Duration class, and replaced it with long . This change provides better interoperability with Java.
  • Метаданные цитирования

    • Wrapped all the fields previously declared in CitationMetadata into a new class called Citation . Citations can be found in the list called citations in CitationMetadata . This change allows better alignment of types across platforms.
  • Подсчет токенов

    • Changed the field totalBillableCharacters to be nullable.
  • Total billable characters

    • Changed the totalBillableCharacters property in CountTokensResponse to be optional to reflect situations where no characters are sent.
  • Instantiating a model

    • Moved the requestOptions parameter to the end of the parameter list to align with other platforms.

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 , and FinishReason .
  • Block reason

    • Changed blockReason in PromptFeedback to be optional.
  • 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 to AIError .

Dart

  • Enumerations

    • Removed values from the following enumerations: HarmCategory , HarmProbability , BlockReason , and FinishReason .
  • Data part

    • Renamed DataPart to InlineDataPart , and the static data function to inlineData to align with other platforms.
  • Варианты запроса

    • Removed RequestOptions since timeout wasn't functional. It will be re-added in the near future, but it will be moved to the GenerativeModel type to match other platforms.
  • Stop sequences

    • Changed the stopSequences parameter in GenerationConfig to be optional and to default to null instead of an empty array.
  • Цитаты

    • Renamed the citationSources property to citations in CitationMetadata . The CitationSource type was renamed to Citation to match other platforms.
  • 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 , and EmbedContentResponse .
  • Подсчет токенов

    • Removed extra fields from the countTokens function that are no longer necessary. Only contents is needed.
  • Instantiating a model

    • Moved the systemInstruction parameter to the end of the parameter list to align with other platforms.
  • Embedding functionality

    • Removed unsupported embedding functionality ( embedContent and batchEmbedContents ) from the model.

Единство

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