Firebase AI Logic и его клиентские SDK ранее назывались " Vertex AI in Firebase ". Чтобы лучше отразить расширение наших сервисов и функций (например, теперь мы поддерживаем API для разработчиков Gemini !), мы переименовали и переупаковали наши сервисы в Firebase AI Logic .
Для безопасного доступа к моделям генеративного ИИ Google непосредственно из ваших мобильных или веб-приложений теперь можно выбрать поставщика « Gemini API » — либо давно доступный Agent Platform Gemini API (ранее Vertex AI) , либо Gemini Developer API . Это означает, что теперь у вас есть возможность использовать Gemini Developer API , который предоставляет бесплатный уровень с разумными ограничениями скорости и квотами.
Обзор шагов по миграции на SDK Firebase AI Logic .
Шаг 1 : Выберите лучшего поставщика "Gemini API" для вашего приложения и сценариев использования.
Шаг 2 : Включите необходимые API.
Шаг 3 : Обновите библиотеку, используемую в вашем приложении.
Шаг 4 : Обновите параметры инициализации в вашем приложении.
Шаг 5 : Обновите свой код в зависимости от используемых вами функций.
Шаг 1 : Выберите лучшего поставщика "Gemini API" для вашего приложения.
В результате этой миграции у вас есть выбор поставщика " Gemini API ":
Старые SDK " Vertex AI in Firebase " могли использовать только API Gemini Agent Platform (ранее Vertex AI) .
Новые SDK Firebase AI Logic позволяют выбирать, к какому поставщику « Gemini API » вы хотите обращаться напрямую из своего мобильного или веб-приложения — либо к Gemini Developer API , либо к Agent Platform Gemini API (ранее Vertex AI) .
Ознакомьтесь с различиями между использованием двух API-провайдеров Gemini , особенно в отношении поддерживаемых функций, ценообразования и ограничений скорости. Например, API для разработчиков Gemini не поддерживает предоставление файлов с использованием URL-адресов Cloud Storage , но это может быть хорошим выбором, если вы хотите воспользоваться его бесплатным уровнем и разумным лимитом трафика.
Шаг 2 : Включите необходимые API.
Убедитесь, что в вашем проекте Firebase включены все необходимые API для использования выбранного вами поставщика " Gemini API ".
Обратите внимание, что в вашем проекте можно одновременно включить оба поставщика API.
Войдите в консоль Firebase , а затем выберите свой проект Firebase.
В консоли Firebase перейдите в раздел AI Services > AI Logic .
Нажмите « Начать» , чтобы запустить пошаговый рабочий процесс, который поможет вам настроить необходимые API и ресурсы для вашего проекта.
Выберите поставщика "Gemini API", которого вы хотите использовать с SDK Firebase AI Logic . При желании вы всегда можете настроить и использовать другого поставщика API позже.
API для разработчиков Gemini — оплата необязательна (доступно в бесплатном тарифном плане Spark).
В процессе работы консоли будут активированы необходимые API и создан ключ API Gemini в вашем проекте.
Не добавляйте этот API-ключ Gemini в код вашего приложения. Узнайте больше.API Gemini Agent Platform (ранее Vertex AI) — требуется оплата (требуется тарифный план Blaze с оплатой по факту использования)
Рабочий процесс консоли активирует необходимые API в вашем проекте.
Продолжите выполнение инструкций в этом руководстве по миграции, чтобы обновить библиотеку и выполнить инициализацию в вашем приложении.
Шаг 3 : Обновите библиотеку, используемую в вашем приложении.
Обновите код своего приложения, чтобы использовать библиотеку Firebase AI Logic .
Быстрый
В Xcode, открыв проект приложения, обновите пакет Firebase до версии 11.13.0 или более поздней, используя один из следующих вариантов:
Вариант 1 : Обновить все пакеты: Перейдите в меню Файл > Пакеты > Обновить до последних версий пакетов .
Вариант 2 : Обновите Firebase по отдельности: Перейдите к пакету Firebase в разделе « Зависимости пакета» . Щелкните правой кнопкой мыши по пакету Firebase и выберите «Обновить пакет» .
Убедитесь, что в списке необходимых пакетов Firebase отображается версия 11.13.0 или более поздняя. Если это не так, проверьте, позволяют ли указанные вами требования к пакету обновить его до версии 11.13.0 или более поздней.
В редакторе проектов выберите целевой объект вашего приложения, а затем перейдите в раздел «Фреймворки, библиотеки и встроенный контент» .
Добавьте новую библиотеку: выберите кнопку «+» , а затем добавьте FirebaseAI из пакета Firebase.
После завершения миграции вашего приложения (см. остальные разделы этого руководства) обязательно удалите старую библиотеку:
Выберите FirebaseVertexAI-Preview , а затем нажмите кнопку — .
Kotlin
В файле Gradle вашего модуля (уровня приложения) (обычно
<project>/<app-module>/build.gradle.ktsили<project>/<app-module>/build.gradle) замените старые зависимости (если применимо) следующими.Обратите внимание, что, возможно, будет проще перенести кодовую базу вашего приложения (см. остальные разделы этого руководства) до удаления старой зависимости.
// BEFORE dependencies {
implementation("com.google.firebase:firebase-vertexai:16.0.0-betaXX")} // AFTER dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.18.0")) // Add the dependency for the Firebase AI Logic library // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-ai") }Синхронизируйте свой Android-проект с файлами Gradle.
Обратите внимание, что если вы решите не использовать Firebase Android BoM , просто добавьте зависимость для библиотеки firebase-ai и примите последнюю версию, предложенную Android Studio.
Java
В файле Gradle вашего модуля (уровня приложения) (обычно
<project>/<app-module>/build.gradle.ktsили<project>/<app-module>/build.gradle) замените старые зависимости (если применимо) следующими.Обратите внимание, что, возможно, будет проще перенести кодовую базу вашего приложения (см. остальные разделы этого руководства) до удаления старой зависимости.
// BEFORE dependencies {
implementation("com.google.firebase:firebase-vertexai:16.0.0-betaXX")} // AFTER dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.18.0")) // Add the dependency for the Firebase AI Logic library // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-ai") }Синхронизируйте свой Android-проект с файлами Gradle.
Обратите внимание, что если вы решите не использовать Firebase Android BoM , просто добавьте зависимость для библиотеки firebase-ai и примите последнюю версию, предложенную Android Studio.
Web
Получите последнюю версию Firebase JS SDK для веб-разработки с помощью npm:
npm i firebase@latest
ИЛИ
yarn add firebase@latest
Везде, где вы импортировали библиотеку, обновите операторы импорта, используя
firebase/aiвместо этого.Обратите внимание, что, возможно, будет проще перенести кодовую базу вашего приложения (см. остальные разделы этого руководства) до удаления старых импортов.
// BEFORE import { initializeApp } from "firebase/app";
import { getVertexAI, getGenerativeModel } from "firebase/vertexai-preview";// AFTER import { initializeApp } from "firebase/app"; import { getAI, getGenerativeModel } from "firebase/ai";
Dart
Для обновления и добавления пакета
firebase_aiв файлpubspec.yamlвыполните следующую команду из каталога вашего проекта Flutter:flutter pub add firebase_ai
Пересоберите свой проект Flutter:
flutter run
После завершения миграции вашего приложения (см. остальные разделы этого руководства) обязательно удалите старый пакет:
flutter pub remove firebase_vertexai
Единство
Поддержка Unity в " Vertex AI in Firebase " отсутствовала.
Узнайте, как начать работу с Firebase AI Logic SDK для Unity .
Шаг 4 : Обновите инициализацию в вашем приложении.
Чтобы просмотреть контент и код, относящиеся к вашему поставщику API Gemini , нажмите на него. |
Обновите способ инициализации сервиса для выбранного вами API-провайдера и создайте экземпляр GenerativeModel .
Быстрый
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
// 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
// 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
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
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 в " Vertex AI in Firebase " отсутствовала.
Узнайте, как начать работу с Firebase AI Logic SDK для Unity .
Обратите внимание, что в зависимости от используемых возможностей вам может не всегда потребоваться создать экземпляр GenerativeModel . Для потоковой передачи входных и выходных данных с помощью Gemini Live API создайте экземпляр LiveModel .
Шаг 5 : Обновите свой код в зависимости от используемых вами функций.
На этом шаге описываются изменения, которые могут потребоваться в зависимости от используемых вами функций.
Если вы используете URL-адреса Cloud Storage и в ходе миграции перешли на использование API разработчика Gemini , вам необходимо обновить ваши мультимодальные запросы, чтобы включать файлы в качестве встроенных данных (или использовать URL-адреса YouTube для видео).
В общедоступные версии SDK " Vertex AI in Firebase " были внесены некоторые изменения. Эти же изменения необходимы для использования 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перемещен в конец списка параметров для соответствия требованиям других платформ.
- Параметр
Live API
Удалено значение
UNSPECIFIEDдля класса перечисленияResponseModality. Вместо него используйтеnull.Переименована
LiveGenerationConfig.setResponseModalitiesвLiveGenerationConfig.setResponseModality.Класс
LiveContentResponse.Statusбыл удалён, и вместо него поля статуса вложены в свойства классаLiveContentResponse.Класс
LiveContentResponseбыл удален, и вместо него предоставлены подклассыLiveServerMessage, которые соответствуют ответам от модели.Изменено значение в
LiveModelFutures.connect: теперь он возвращаетListenableFuture<LiveSessionFutures>вместоListenableFuture<LiveSession>.
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перемещен в конец списка параметров для соответствия требованиям других платформ.
- Параметр
Live API
Удалено значение
UNSPECIFIEDдля класса перечисленияResponseModality. Вместо него используйтеnull.Переименована
LiveGenerationConfig.setResponseModalitiesвLiveGenerationConfig.setResponseModality.Класс
LiveContentResponse.Statusбыл удалён, и вместо него поля статуса вложены в свойства классаLiveContentResponse.Класс
LiveContentResponseбыл удален, и вместо него предоставлены подклассыLiveServerMessage, которые соответствуют ответам от модели.Изменено значение в
LiveModelFutures.connect: теперь он возвращаетListenableFuture<LiveSessionFutures>вместоListenableFuture<LiveSession>.
Изменены различные методы Java-конструктора, теперь они корректно возвращают экземпляр своего класса, а не
void.
Web
Перечисления
- Удалены значения из следующих перечислений:
HarmCategory,BlockThreshold,HarmProbability,HarmSeverity,BlockReasonиFinishReason.
- Удалены значения из следующих перечислений:
Причина блокировки
- Изменено
blockReasonвPromptFeedback, теперь он является необязательным.
- Изменено
Изменения требуются только в том случае, если вы начинаете использовать API разработчика Gemini (вместо API платформы агентов Gemini (ранее Vertex AI) ):
Настройки безопасности
- Удалены случаи использования неподдерживаемого метода
SafetySetting.method.
- Удалены случаи использования неподдерживаемого метода
Встроенные данные
- Удалены случаи использования неподдерживаемого объекта
InlineDataPart.videoMetadata.
- Удалены случаи использования неподдерживаемого объекта
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 в " Vertex AI in Firebase " отсутствовала.
Узнайте, как начать работу с Firebase AI Logic SDK для Unity .
Возможные ошибки, связанные с миграцией.
При переходе на общедоступную версию Firebase AI Logic вы можете столкнуться с ошибками, если не внесли все необходимые изменения, описанные в этом руководстве по миграции.
Ошибка 403: Requests to this API firebasevertexai.googleapis.com ... are blocked.
Если вы получаете ошибку 403 с сообщением « Requests to this API firebasevertexai.googleapis.com ... are blocked. , это обычно означает, что ключ API Firebase в вашем файле конфигурации Firebase или объекте не содержит требуемый API в списке разрешенных для продукта, который вы пытаетесь использовать.
Убедитесь, что ключ API Firebase, используемый вашим приложением, содержит все необходимые API, включенные в список разрешенных API в разделе «Ограничения API» . Для Firebase AI Logic ваш ключ API Firebase должен содержать как минимум API Firebase AI Logic в списке разрешенных API. Этот API должен был быть автоматически добавлен в список разрешенных API вашего ключа API при включении необходимых API в консоли Firebase .
Все ваши API-ключи можно просмотреть на панели «API и сервисы» > «Учетные данные» в консоли Google Cloud .
Оставьте отзыв о вашем опыте использования Firebase AI Logic.
Firebase AI Logic и его клиентские SDK ранее назывались " Vertex AI in Firebase ". Чтобы лучше отразить расширение наших сервисов и функций (например, теперь мы поддерживаем API для разработчиков Gemini !), мы переименовали и переупаковали наши сервисы в Firebase AI Logic .
Для безопасного доступа к моделям генеративного ИИ Google непосредственно из ваших мобильных или веб-приложений теперь можно выбрать поставщика « Gemini API » — либо давно доступный Agent Platform Gemini API (ранее Vertex AI) , либо Gemini Developer API . Это означает, что теперь у вас есть возможность использовать Gemini Developer API , который предоставляет бесплатный уровень с разумными ограничениями скорости и квотами.
Обзор шагов по миграции на SDK Firebase AI Logic .
Шаг 1 : Выберите лучшего поставщика "Gemini API" для вашего приложения и сценариев использования.
Шаг 2 : Включите необходимые API.
Шаг 3 : Обновите библиотеку, используемую в вашем приложении.
Шаг 4 : Обновите параметры инициализации в вашем приложении.
Шаг 5 : Обновите свой код в зависимости от используемых вами функций.
Шаг 1 : Выберите лучшего поставщика "Gemini API" для вашего приложения.
В результате этой миграции у вас есть выбор поставщика " Gemini API ":
Старые SDK " Vertex AI in Firebase " могли использовать только API Gemini Agent Platform (ранее Vertex AI) .
Новые SDK Firebase AI Logic позволяют выбирать, к какому поставщику « Gemini API » вы хотите обращаться напрямую из своего мобильного или веб-приложения — либо к Gemini Developer API , либо к Agent Platform Gemini API (ранее Vertex AI) .
Ознакомьтесь с различиями между использованием двух API-провайдеров Gemini , особенно в отношении поддерживаемых функций, ценообразования и ограничений скорости. Например, API для разработчиков Gemini не поддерживает предоставление файлов с использованием URL-адресов Cloud Storage , но это может быть хорошим выбором, если вы хотите воспользоваться его бесплатным уровнем и разумным лимитом трафика.
Шаг 2 : Включите необходимые API.
Убедитесь, что в вашем проекте Firebase включены все необходимые API для использования выбранного вами поставщика " Gemini API ".
Обратите внимание, что в вашем проекте можно одновременно включить оба поставщика API.
Войдите в консоль Firebase , а затем выберите свой проект Firebase.
В консоли Firebase перейдите в раздел AI Services > AI Logic .
Нажмите « Начать» , чтобы запустить пошаговый рабочий процесс, который поможет вам настроить необходимые API и ресурсы для вашего проекта.
Выберите поставщика "Gemini API", которого вы хотите использовать с SDK Firebase AI Logic . При желании вы всегда можете настроить и использовать другого поставщика API позже.
API для разработчиков Gemini — оплата необязательна (доступно в бесплатном тарифном плане Spark).
В процессе работы консоли будут активированы необходимые API и создан ключ API Gemini в вашем проекте.
Не добавляйте этот API-ключ Gemini в код вашего приложения. Узнайте больше.API Gemini Agent Platform (ранее Vertex AI) — требуется оплата (требуется тарифный план Blaze с оплатой по факту использования)
Рабочий процесс консоли активирует необходимые API в вашем проекте.
Продолжите выполнение инструкций в этом руководстве по миграции, чтобы обновить библиотеку и выполнить инициализацию в вашем приложении.
Шаг 3 : Обновите библиотеку, используемую в вашем приложении.
Обновите код своего приложения, чтобы использовать библиотеку Firebase AI Logic .
Быстрый
В Xcode, открыв проект приложения, обновите пакет Firebase до версии 11.13.0 или более поздней, используя один из следующих вариантов:
Вариант 1 : Обновить все пакеты: Перейдите в меню Файл > Пакеты > Обновить до последних версий пакетов .
Вариант 2 : Обновите Firebase по отдельности: Перейдите к пакету Firebase в разделе « Зависимости пакета» . Щелкните правой кнопкой мыши по пакету Firebase и выберите «Обновить пакет» .
Убедитесь, что в списке необходимых пакетов Firebase отображается версия 11.13.0 или более поздняя. Если это не так, проверьте, позволяют ли указанные вами требования к пакету обновить его до версии 11.13.0 или более поздней.
В редакторе проектов выберите целевой объект вашего приложения, а затем перейдите в раздел «Фреймворки, библиотеки и встроенный контент» .
Добавьте новую библиотеку: выберите кнопку «+» , а затем добавьте FirebaseAI из пакета Firebase.
После завершения миграции вашего приложения (см. остальные разделы этого руководства) обязательно удалите старую библиотеку:
Выберите FirebaseVertexAI-Preview , а затем нажмите кнопку — .
Kotlin
В файле Gradle вашего модуля (уровня приложения) (обычно
<project>/<app-module>/build.gradle.ktsили<project>/<app-module>/build.gradle) замените старые зависимости (если применимо) следующими.Обратите внимание, что, возможно, будет проще перенести кодовую базу вашего приложения (см. остальные разделы этого руководства) до удаления старой зависимости.
// BEFORE dependencies {
implementation("com.google.firebase:firebase-vertexai:16.0.0-betaXX")} // AFTER dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.18.0")) // Add the dependency for the Firebase AI Logic library // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-ai") }Синхронизируйте свой Android-проект с файлами Gradle.
Обратите внимание, что если вы решите не использовать Firebase Android BoM , просто добавьте зависимость для библиотеки firebase-ai и примите последнюю версию, предложенную Android Studio.
Java
В файле Gradle вашего модуля (уровня приложения) (обычно
<project>/<app-module>/build.gradle.ktsили<project>/<app-module>/build.gradle) замените старые зависимости (если применимо) следующими.Обратите внимание, что, возможно, будет проще перенести кодовую базу вашего приложения (см. остальные разделы этого руководства) до удаления старой зависимости.
// BEFORE dependencies {
implementation("com.google.firebase:firebase-vertexai:16.0.0-betaXX")} // AFTER dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.18.0")) // Add the dependency for the Firebase AI Logic library // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-ai") }Синхронизируйте свой Android-проект с файлами Gradle.
Обратите внимание, что если вы решите не использовать Firebase Android BoM , просто добавьте зависимость для библиотеки firebase-ai и примите последнюю версию, предложенную Android Studio.
Web
Получите последнюю версию Firebase JS SDK для веб-разработки с помощью npm:
npm i firebase@latest
ИЛИ
yarn add firebase@latest
Везде, где вы импортировали библиотеку, обновите операторы импорта, используя
firebase/aiвместо этого.Обратите внимание, что, возможно, будет проще перенести кодовую базу вашего приложения (см. остальные разделы этого руководства) до удаления старых импортов.
// BEFORE import { initializeApp } from "firebase/app";
import { getVertexAI, getGenerativeModel } from "firebase/vertexai-preview";// AFTER import { initializeApp } from "firebase/app"; import { getAI, getGenerativeModel } from "firebase/ai";
Dart
Для обновления и добавления пакета
firebase_aiв файлpubspec.yamlвыполните следующую команду из каталога вашего проекта Flutter:flutter pub add firebase_ai
Пересоберите свой проект Flutter:
flutter run
После завершения миграции вашего приложения (см. остальные разделы этого руководства) обязательно удалите старый пакет:
flutter pub remove firebase_vertexai
Единство
Поддержка Unity в " Vertex AI in Firebase " отсутствовала.
Узнайте, как начать работу с Firebase AI Logic SDK для Unity .
Шаг 4 : Обновите инициализацию в вашем приложении.
Чтобы просмотреть контент и код, относящиеся к вашему поставщику API Gemini , нажмите на него. |
Обновите способ инициализации сервиса для выбранного вами API-провайдера и создайте экземпляр GenerativeModel .
Быстрый
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
// 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
// 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
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
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 в " Vertex AI in Firebase " отсутствовала.
Узнайте, как начать работу с Firebase AI Logic SDK для Unity .
Обратите внимание, что в зависимости от используемых возможностей вам может не всегда потребоваться создать экземпляр GenerativeModel . Для потоковой передачи входных и выходных данных с помощью Gemini Live API создайте экземпляр LiveModel .
Шаг 5 : Обновите свой код в зависимости от используемых вами функций.
На этом шаге описываются изменения, которые могут потребоваться в зависимости от используемых вами функций.
Если вы используете URL-адреса Cloud Storage и в ходе миграции перешли на использование API разработчика Gemini , вам необходимо обновить ваши мультимодальные запросы, чтобы включать файлы в качестве встроенных данных (или использовать URL-адреса YouTube для видео).
В общедоступные версии SDK " Vertex AI in Firebase " были внесены некоторые изменения. Эти же изменения необходимы для использования 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перемещен в конец списка параметров для соответствия требованиям других платформ.
- Параметр
Live API
Удалено значение
UNSPECIFIEDдля класса перечисленияResponseModality. Вместо него используйтеnull.Переименована
LiveGenerationConfig.setResponseModalitiesвLiveGenerationConfig.setResponseModality.Класс
LiveContentResponse.Statusбыл удалён, и вместо него поля статуса вложены в свойства классаLiveContentResponse.Removed the
LiveContentResponseclass, and instead have provided subclasses ofLiveServerMessagethat match the responses from the model.Changed
LiveModelFutures.connectto returnListenableFuture<LiveSessionFutures>instead ofListenableFuture<LiveSession>.
Java
Перечисления
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
Citation metadata
- 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
Live API
Removed
UNSPECIFIEDvalue for enum classResponseModality. Instead usenull.Renamed
LiveGenerationConfig.setResponseModalitiestoLiveGenerationConfig.setResponseModality.Removed the
LiveContentResponse.Statusclass, and instead have nested the status fields as properties ofLiveContentResponse.Removed the
LiveContentResponseclass, and instead have provided subclasses ofLiveServerMessagethat match the responses from the model.Changed
LiveModelFutures.connectto returnListenableFuture<LiveSessionFutures>instead ofListenableFuture<LiveSession>.
Changed various Java builder methods to now correctly return the instance of their class, instead of
void.
Web
Перечисления
- Removed values from the following enumerations:
HarmCategory,BlockThreshold,HarmProbability,HarmSeverity,BlockReason, andFinishReason.
- Removed values from the following enumerations:
Причина блокировки
- Changed
blockReasoninPromptFeedbackto be optional.
- Changed
Changes required only if you're starting to use the Gemini Developer API (instead of the Agent Platform Gemini API (formerly Vertex AI) ):
Настройки безопасности
- Removed usages of the unsupported
SafetySetting.method.
- Removed usages of the unsupported
Inline data
- Removed usages of the unsupported
InlineDataPart.videoMetadata.
- Removed usages of the unsupported
Dart
Перечисления
- 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
Request options
- 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
Стоп-последовательности
- 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 " Vertex AI in Firebase ".
Learn how to get started with the Firebase AI Logic SDK for Unity .
Possible errors related to migrating
As you're migrating to use the GA version of Firebase AI Logic , you might encounter errors if you haven't completed all of the required changes as described in this migration guide.
403 Error: Requests to this API firebasevertexai.googleapis.com ... are blocked.
If you receive a 403 error that says Requests to this API firebasevertexai.googleapis.com ... are blocked. , it usually means that the Firebase API key in your Firebase configuration file or object doesn't have a required API in its allowlist for the product that you're trying to use.
Make sure that the Firebase API key used by your app has all the required APIs included in the key's "API restrictions" allowlist . For Firebase AI Logic , your Firebase API key needs to have at minimum the Firebase AI Logic API in its allowlist. This API should have been automatically added to your API key's allowlist when you enabled the required APIs in the Firebase console .
You can view all your API keys in the APIs & Services > Credentials panel in the Google Cloud console.
Give feedback about your experience with Firebase AI Logic
Firebase AI Logic and its client SDKs were formerly called " Vertex AI in Firebase ". To better reflect our expanded services and features (for example, we now support the Gemini Developer API !), we renamed and repackaged our services into Firebase AI Logic .
To securely access Google's generative AI models directly from your mobile or web apps, you can now choose a " Gemini API " provider — either the long-available Agent Platform Gemini API (formerly Vertex AI) or now the Gemini Developer API . This means that you now have the option to use the Gemini Developer API , which provides a no-cost tier with reasonable rate limits and quotas.
Overview of steps to migrate to the Firebase AI Logic SDKs
Step 1 : Choose the best "Gemini API" provider for your app and use cases.
Step 2 : Enable the required APIs.
Step 3 : Update the library used in your app.
Step 4 : Update the initialization in your app.
Step 5 : Update your code depending on the features that you use.
Step 1 : Choose the best "Gemini API" provider for your app
With this migration, you have a choice in " Gemini API " provider:
The old " Vertex AI in Firebase " SDKs could only use the Agent Platform Gemini API (formerly Vertex AI) .
The new Firebase AI Logic SDKs let you choose which " Gemini API " provider you want to call directly from your mobile or web app – either the Gemini Developer API or the Agent Platform Gemini API (formerly Vertex AI) .
Review the differences between using the two Gemini API providers , especially in terms of supported features, pricing, and rate limits. For just one example, the Gemini Developer API doesn't support providing files using Cloud Storage URLs, but it might be a good choice if you want to take advantage of its no-cost tier and reasonable quota.
Step 2 : Enable the required APIs
Ensure that all required APIs are enabled in your Firebase project to use your chosen " Gemini API " provider.
Note that you can have both of API providers enabled in your project at the same time.
Sign into the Firebase console , and then select your Firebase project.
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 API" provider that you'd like to use with the Firebase AI Logic SDKs. You can always set up and use the other API provider later, if you'd like.
Gemini Developer API — billing optional (available on the no-cost Spark pricing plan)
The console's workflow will enable the required APIs and create a Gemini API key in your project.
Do not add this Gemini API key into your app's codebase. Learn more.Agent Platform Gemini API (formerly Vertex AI) — billing required (requires the pay-as-you-go Blaze pricing plan)
The console's workflow will enable the required APIs in your project.
Continue in this migration guide to update the library and initialization in your app.
Step 3 : Update the library used in your app
Update your app's codebase to use the Firebase AI Logic library.
Быстрый
In Xcode, with your app project open, update your Firebase package to v11.13.0 or later using one of the following options:
Option 1 : Update all packages: Navigate to File > Packages > Update to Latest Package Versions .
Option 2 : Update Firebase individually: Navigate to the Firebase package in the section called Package Dependencies . Right-click on the Firebase package, and then select Update Package .
Make sure that the Firebase package now shows v11.13.0 or later. If it doesn't, verify that your specified Package Requirements allow updating to v11.13.0 or later.
Select your app's target in the Project Editor, and then navigate to the Frameworks, Libraries, and Embedded Content section.
Add the new library: Select the + button, and then add FirebaseAI from the Firebase package.
After you've finished migrating your app (see the remaining sections in this guide), make sure to remove the old library:
Select FirebaseVertexAI-Preview , and then press the — button.
Kotlin
In your module (app-level) Gradle file (usually
<project>/<app-module>/build.gradle.ktsor<project>/<app-module>/build.gradle), replace old dependencies (as applicable) with the following.Note that it might be easier to migrate your app's codebase (see the remaining sections in this guide) before deleting the old dependency.
// BEFORE dependencies {
implementation("com.google.firebase:firebase-vertexai:16.0.0-betaXX")} // AFTER dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.18.0")) // Add the dependency for the Firebase AI Logic library // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-ai") }Sync your Android project with Gradle files.
Note that if you choose to not use the Firebase Android BoM , then just add the dependency for the firebase-ai library and accept the latest version that's suggested by Android Studio.
Java
In your module (app-level) Gradle file (usually
<project>/<app-module>/build.gradle.ktsor<project>/<app-module>/build.gradle), replace old dependencies (as applicable) with the following.Note that it might be easier to migrate your app's codebase (see the remaining sections in this guide) before deleting the old dependency.
// BEFORE dependencies {
implementation("com.google.firebase:firebase-vertexai:16.0.0-betaXX")} // AFTER dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.18.0")) // Add the dependency for the Firebase AI Logic library // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-ai") }Sync your Android project with Gradle files.
Note that if you choose to not use the Firebase Android BoM , then just add the dependency for the firebase-ai library and accept the latest version that's suggested by Android Studio.
Web
Get the latest version of the Firebase JS SDK for Web using npm:
npm i firebase@latest
ИЛИ
yarn add firebase@latest
Wherever you've imported the library, update your import statements to use
firebase/aiinstead.Note that it might be easier to migrate your app's codebase (see the remaining sections in this guide) before deleting the old imports.
// BEFORE import { initializeApp } from "firebase/app";
import { getVertexAI, getGenerativeModel } from "firebase/vertexai-preview";// AFTER import { initializeApp } from "firebase/app"; import { getAI, getGenerativeModel } from "firebase/ai";
Dart
Update to the use the
firebase_aipackage in yourpubspec.yamlfile by running the following command from your Flutter project directory:flutter pub add firebase_ai
Rebuild your Flutter project:
flutter run
After you've finished migrating your app (see the remaining sections in this guide), make sure to delete the old package:
flutter pub remove firebase_vertexai
Единство
Support for Unity wasn't available from " Vertex AI in Firebase ".
Learn how to get started with the Firebase AI Logic SDK for Unity .
Step 4 : Update the initialization in your app
Click your Gemini API provider to view provider-specific content and code on this page. |
Update how you initialize the service for your chosen API provider and create a GenerativeModel instance.
Быстрый
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
// 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
// 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
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
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 " Vertex AI in Firebase ".
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 5 : Update your code depending on features that you use
This step describes changes that may be required depending on which features you use.
If you use Cloud Storage URLs and you swapped to use the Gemini Developer API in this migration, then you must update your multimodal requests to include files as inline data (or use YouTube URLs for videos).
Several changes were introduced for the GA versions of the " Vertex AI in Firebase " SDKs. These same changes are required to use the Firebase AI Logic SDKs. Review the following lists for any changes that you might need to make in your code to accommodate taking up the Firebase AI Logic SDK.
Required for all languages and platforms
Вызов функции
If you implemented this feature before GA, 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 before GA, 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
Быстрый
Перечисления
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
Citation metadata
- 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
Перечисления
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
Citation metadata
- 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
Live API
Removed
UNSPECIFIEDvalue for enum classResponseModality. Instead usenull.Renamed
LiveGenerationConfig.setResponseModalitiestoLiveGenerationConfig.setResponseModality.Removed the
LiveContentResponse.Statusclass, and instead have nested the status fields as properties ofLiveContentResponse.Removed the
LiveContentResponseclass, and instead have provided subclasses ofLiveServerMessagethat match the responses from the model.Changed
LiveModelFutures.connectto returnListenableFuture<LiveSessionFutures>instead ofListenableFuture<LiveSession>.
Java
Перечисления
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
Citation metadata
- 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
Live API
Removed
UNSPECIFIEDvalue for enum classResponseModality. Instead usenull.Renamed
LiveGenerationConfig.setResponseModalitiestoLiveGenerationConfig.setResponseModality.Removed the
LiveContentResponse.Statusclass, and instead have nested the status fields as properties ofLiveContentResponse.Removed the
LiveContentResponseclass, and instead have provided subclasses ofLiveServerMessagethat match the responses from the model.Changed
LiveModelFutures.connectto returnListenableFuture<LiveSessionFutures>instead ofListenableFuture<LiveSession>.
Changed various Java builder methods to now correctly return the instance of their class, instead of
void.
Web
Перечисления
- Removed values from the following enumerations:
HarmCategory,BlockThreshold,HarmProbability,HarmSeverity,BlockReason, andFinishReason.
- Removed values from the following enumerations:
Причина блокировки
- Changed
blockReasoninPromptFeedbackto be optional.
- Changed
Changes required only if you're starting to use the Gemini Developer API (instead of the Agent Platform Gemini API (formerly Vertex AI) ):
Настройки безопасности
- Removed usages of the unsupported
SafetySetting.method.
- Removed usages of the unsupported
Inline data
- Removed usages of the unsupported
InlineDataPart.videoMetadata.
- Removed usages of the unsupported
Dart
Перечисления
- 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
Request options
- 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
Стоп-последовательности
- 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 " Vertex AI in Firebase ".
Learn how to get started with the Firebase AI Logic SDK for Unity .
Possible errors related to migrating
As you're migrating to use the GA version of Firebase AI Logic , you might encounter errors if you haven't completed all of the required changes as described in this migration guide.
403 Error: Requests to this API firebasevertexai.googleapis.com ... are blocked.
If you receive a 403 error that says Requests to this API firebasevertexai.googleapis.com ... are blocked. , it usually means that the Firebase API key in your Firebase configuration file or object doesn't have a required API in its allowlist for the product that you're trying to use.
Make sure that the Firebase API key used by your app has all the required APIs included in the key's "API restrictions" allowlist . For Firebase AI Logic , your Firebase API key needs to have at minimum the Firebase AI Logic API in its allowlist. This API should have been automatically added to your API key's allowlist when you enabled the required APIs in the Firebase console .
You can view all your API keys in the APIs & Services > Credentials panel in the Google Cloud console.
Give feedback about your experience with Firebase AI Logic
Firebase AI Logic and its client SDKs were formerly called " Vertex AI in Firebase ". To better reflect our expanded services and features (for example, we now support the Gemini Developer API !), we renamed and repackaged our services into Firebase AI Logic .
To securely access Google's generative AI models directly from your mobile or web apps, you can now choose a " Gemini API " provider — either the long-available Agent Platform Gemini API (formerly Vertex AI) or now the Gemini Developer API . This means that you now have the option to use the Gemini Developer API , which provides a no-cost tier with reasonable rate limits and quotas.
Overview of steps to migrate to the Firebase AI Logic SDKs
Step 1 : Choose the best "Gemini API" provider for your app and use cases.
Step 2 : Enable the required APIs.
Step 3 : Update the library used in your app.
Step 4 : Update the initialization in your app.
Step 5 : Update your code depending on the features that you use.
Step 1 : Choose the best "Gemini API" provider for your app
With this migration, you have a choice in " Gemini API " provider:
The old " Vertex AI in Firebase " SDKs could only use the Agent Platform Gemini API (formerly Vertex AI) .
The new Firebase AI Logic SDKs let you choose which " Gemini API " provider you want to call directly from your mobile or web app – either the Gemini Developer API or the Agent Platform Gemini API (formerly Vertex AI) .
Review the differences between using the two Gemini API providers , especially in terms of supported features, pricing, and rate limits. For just one example, the Gemini Developer API doesn't support providing files using Cloud Storage URLs, but it might be a good choice if you want to take advantage of its no-cost tier and reasonable quota.
Step 2 : Enable the required APIs
Ensure that all required APIs are enabled in your Firebase project to use your chosen " Gemini API " provider.
Note that you can have both of API providers enabled in your project at the same time.
Sign into the Firebase console , and then select your Firebase project.
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 API" provider that you'd like to use with the Firebase AI Logic SDKs. You can always set up and use the other API provider later, if you'd like.
Gemini Developer API — billing optional (available on the no-cost Spark pricing plan)
The console's workflow will enable the required APIs and create a Gemini API key in your project.
Do not add this Gemini API key into your app's codebase. Learn more.Agent Platform Gemini API (formerly Vertex AI) — billing required (requires the pay-as-you-go Blaze pricing plan)
The console's workflow will enable the required APIs in your project.
Continue in this migration guide to update the library and initialization in your app.
Step 3 : Update the library used in your app
Update your app's codebase to use the Firebase AI Logic library.
Быстрый
In Xcode, with your app project open, update your Firebase package to v11.13.0 or later using one of the following options:
Option 1 : Update all packages: Navigate to File > Packages > Update to Latest Package Versions .
Option 2 : Update Firebase individually: Navigate to the Firebase package in the section called Package Dependencies . Right-click on the Firebase package, and then select Update Package .
Make sure that the Firebase package now shows v11.13.0 or later. If it doesn't, verify that your specified Package Requirements allow updating to v11.13.0 or later.
Select your app's target in the Project Editor, and then navigate to the Frameworks, Libraries, and Embedded Content section.
Add the new library: Select the + button, and then add FirebaseAI from the Firebase package.
After you've finished migrating your app (see the remaining sections in this guide), make sure to remove the old library:
Select FirebaseVertexAI-Preview , and then press the — button.
Kotlin
In your module (app-level) Gradle file (usually
<project>/<app-module>/build.gradle.ktsor<project>/<app-module>/build.gradle), replace old dependencies (as applicable) with the following.Note that it might be easier to migrate your app's codebase (see the remaining sections in this guide) before deleting the old dependency.
// BEFORE dependencies {
implementation("com.google.firebase:firebase-vertexai:16.0.0-betaXX")} // AFTER dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.18.0")) // Add the dependency for the Firebase AI Logic library // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-ai") }Sync your Android project with Gradle files.
Note that if you choose to not use the Firebase Android BoM , then just add the dependency for the firebase-ai library and accept the latest version that's suggested by Android Studio.
Java
In your module (app-level) Gradle file (usually
<project>/<app-module>/build.gradle.ktsor<project>/<app-module>/build.gradle), replace old dependencies (as applicable) with the following.Note that it might be easier to migrate your app's codebase (see the remaining sections in this guide) before deleting the old dependency.
// BEFORE dependencies {
implementation("com.google.firebase:firebase-vertexai:16.0.0-betaXX")} // AFTER dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.18.0")) // Add the dependency for the Firebase AI Logic library // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-ai") }Sync your Android project with Gradle files.
Note that if you choose to not use the Firebase Android BoM , then just add the dependency for the firebase-ai library and accept the latest version that's suggested by Android Studio.
Web
Get the latest version of the Firebase JS SDK for Web using npm:
npm i firebase@latest
ИЛИ
yarn add firebase@latest
Wherever you've imported the library, update your import statements to use
firebase/aiinstead.Note that it might be easier to migrate your app's codebase (see the remaining sections in this guide) before deleting the old imports.
// BEFORE import { initializeApp } from "firebase/app";
import { getVertexAI, getGenerativeModel } from "firebase/vertexai-preview";// AFTER import { initializeApp } from "firebase/app"; import { getAI, getGenerativeModel } from "firebase/ai";
Dart
Update to the use the
firebase_aipackage in yourpubspec.yamlfile by running the following command from your Flutter project directory:flutter pub add firebase_ai
Rebuild your Flutter project:
flutter run
After you've finished migrating your app (see the remaining sections in this guide), make sure to delete the old package:
flutter pub remove firebase_vertexai
Единство
Support for Unity wasn't available from " Vertex AI in Firebase ".
Learn how to get started with the Firebase AI Logic SDK for Unity .
Step 4 : Update the initialization in your app
Click your Gemini API provider to view provider-specific content and code on this page. |
Update how you initialize the service for your chosen API provider and create a GenerativeModel instance.
Быстрый
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
// 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
// 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
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
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 " Vertex AI in Firebase ".
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 5 : Update your code depending on features that you use
This step describes changes that may be required depending on which features you use.
If you use Cloud Storage URLs and you swapped to use the Gemini Developer API in this migration, then you must update your multimodal requests to include files as inline data (or use YouTube URLs for videos).
Several changes were introduced for the GA versions of the " Vertex AI in Firebase " SDKs. These same changes are required to use the Firebase AI Logic SDKs. Review the following lists for any changes that you might need to make in your code to accommodate taking up the Firebase AI Logic SDK.
Required for all languages and platforms
Вызов функции
If you implemented this feature before GA, 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 before GA, 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
Быстрый
Перечисления
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
Citation metadata
- 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
Перечисления
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
Citation metadata
- 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
Live API
Removed
UNSPECIFIEDvalue for enum classResponseModality. Instead usenull.Renamed
LiveGenerationConfig.setResponseModalitiestoLiveGenerationConfig.setResponseModality.Removed the
LiveContentResponse.Statusclass, and instead have nested the status fields as properties ofLiveContentResponse.Removed the
LiveContentResponseclass, and instead have provided subclasses ofLiveServerMessagethat match the responses from the model.Changed
LiveModelFutures.connectto returnListenableFuture<LiveSessionFutures>instead ofListenableFuture<LiveSession>.
Java
Перечисления
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
Citation metadata
- 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
Live API
Removed
UNSPECIFIEDvalue for enum classResponseModality. Instead usenull.Renamed
LiveGenerationConfig.setResponseModalitiestoLiveGenerationConfig.setResponseModality.Removed the
LiveContentResponse.Statusclass, and instead have nested the status fields as properties ofLiveContentResponse.Removed the
LiveContentResponseclass, and instead have provided subclasses ofLiveServerMessagethat match the responses from the model.Changed
LiveModelFutures.connectto returnListenableFuture<LiveSessionFutures>instead ofListenableFuture<LiveSession>.
Changed various Java builder methods to now correctly return the instance of their class, instead of
void.
Web
Перечисления
- Removed values from the following enumerations:
HarmCategory,BlockThreshold,HarmProbability,HarmSeverity,BlockReason, andFinishReason.
- Removed values from the following enumerations:
Причина блокировки
- Changed
blockReasoninPromptFeedbackto be optional.
- Changed
Changes required only if you're starting to use the Gemini Developer API (instead of the Agent Platform Gemini API (formerly Vertex AI) ):
Настройки безопасности
- Removed usages of the unsupported
SafetySetting.method.
- Removed usages of the unsupported
Inline data
- Removed usages of the unsupported
InlineDataPart.videoMetadata.
- Removed usages of the unsupported
Dart
Перечисления
- 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
Request options
- 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
Стоп-последовательности
- 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 " Vertex AI in Firebase ".
Learn how to get started with the Firebase AI Logic SDK for Unity .
Possible errors related to migrating
As you're migrating to use the GA version of Firebase AI Logic , you might encounter errors if you haven't completed all of the required changes as described in this migration guide.
403 Error: Requests to this API firebasevertexai.googleapis.com ... are blocked.
If you receive a 403 error that says Requests to this API firebasevertexai.googleapis.com ... are blocked. , it usually means that the Firebase API key in your Firebase configuration file or object doesn't have a required API in its allowlist for the product that you're trying to use.
Make sure that the Firebase API key used by your app has all the required APIs included in the key's "API restrictions" allowlist . For Firebase AI Logic , your Firebase API key needs to have at minimum the Firebase AI Logic API in its allowlist. This API should have been automatically added to your API key's allowlist when you enabled the required APIs in the Firebase console .
You can view all your API keys in the APIs & Services > Credentials panel in the Google Cloud console.
Give feedback about your experience with Firebase AI Logic