To avoid service disruption, update to anewer model (for example,
gemini-2.5-flash-lite
).Learn more. Migrate to the Firebase AI Logic SDKs from the Preview version of Vertex AI in Firebase SDKs Stay organized with collections Save and categorize content based on your preferences.
These client SDKs are available in Swift for Apple platforms, Kotlin and Java for Android, JavaScript for Web, Dart for Flutter, and Unity.
If you're using a GA version of a "Vertex AI in Firebase" SDK, then go to the guide formigrating from the GA version of the SDK.
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 theGemini Developer API!),we renamed and repackaged our services intoFirebase AI Logic.
To securely access Google's generative AI models directly fromyour mobile or web apps,you can now choose a "Gemini API" provider —either the long-availableVertex AI Gemini API ornow theGemini Developer API. This means that you now have the optionto use theGemini Developer API, which provides ano-cost tierwith reasonable rate limits and quotas.
Overview of steps to migrate to theFirebase 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 theVertex AI Gemini API.
The newFirebase AI Logic SDKs let you choose which"Gemini API" provider you want to call directly from your mobile or webapp – either theGemini Developer API or theVertex AI Gemini API.
Review thedifferences between using the twoGemini API providers,especially in terms of supported features, pricing, and rate limits.For just one example, theGemini Developer API doesn't support providingfiles usingCloud Storage URLs, but it might be a good choice if you want totake advantage of its no-cost tier and reasonable quota.
Important: If you want to use the "free tier" for theGemini Developer API, you need todowngrade the Firebase project that you currently use with the client SDKs to the no-cost Spark pricing plan (that is, unlink theCloud Billing account). Before downgrading, make sure that you're not depending on any other services or quotas that require the Blaze pricing plan.If your Firebase project stays on the Blaze pricing plan, then you'll be on one of the"paid tiers" for theGemini Developer API.
Step 2: Enable the required APIs
Ensure that all required APIs are enabled in your Firebase project to useyour chosen "Gemini API" provider.
Note that you can have both of API providers enabled in your project at the sametime.
Sign into theFirebase console,and then select your Firebase project.
In theFirebase console, go to theFirebase AI Logic page.
ClickGet started to launch a guided workflow that helps you set up therequired APIsand resources for your project.
Select the "Gemini API" provider that you'd like to use with theFirebase AI Logic SDKs. You can always set up and use the otherAPI 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 aGemini API key in your project.
Donot add thisGemini API key into your app's codebase.Learn more.Vertex AI Gemini API —billing required(requires the pay-as-you-go Blaze pricing plan)
The console's workflow will enable therequired APIs in your project.
Continue in this migration guide to update the library and initialization inyour app.
Step 3: Update the library used in your app
Update your app's codebase to use theFirebase AI Logic library.
Swift
In Xcode, with your app project open, update your Firebase package tov11.13.0 or later using one of the following options:
Option 1: Update all packages: Navigate toFile > Packages > Update to Latest Package Versions.
Option 2: Update Firebase individually: Navigate to the Firebasepackage in the section calledPackage Dependencies. Right-click onthe Firebase package, and then selectUpdate Package.
Make sure that the Firebase package now shows v11.13.0 or later. If itdoesn't, verify that your specifiedPackage Requirements allow updating to v11.13.0 or later.
Select your app's target in the Project Editor, and then navigate to theFrameworks, Libraries, and Embedded Content section.
Add the new library: Select the+ button, and then addFirebaseAIfrom the Firebase package.
After you've finished migrating your app (see the remaining sections inthis guide), make sure to remove the old library:
SelectFirebaseVertexAI-Preview,and then press the— button.
Kotlin
In yourmodule (app-level) Gradle file (usually
<project>/<app-module>/build.gradle.kts
or<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 (seethe remaining sections in this guide) before deleting the old dependency.
// BEFOREdependencies{
implementation("com.google.firebase:firebase-vertexai:16.0.0-betaXX")}// AFTERdependencies{// Import theBoM for the Firebase platformimplementation(platform("com.google.firebase:firebase-bom:34.3.0"))// Add the dependency for theFirebase AI Logic library// When using theBoM, you don't specify versions in Firebase library dependenciesimplementation("com.google.firebase:firebase-ai")}Sync your Android project with Gradle files.
Note that if you choose to not use theFirebase Android BoM, then just addthe dependency for thefirebase-ai
library and accept the latest versionthat's suggested by Android Studio.
Java
In yourmodule (app-level) Gradle file (usually
<project>/<app-module>/build.gradle.kts
or<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 (seethe remaining sections in this guide) before deleting the old dependency.
// BEFOREdependencies{
implementation("com.google.firebase:firebase-vertexai:16.0.0-betaXX")}// AFTERdependencies{// Import theBoM for the Firebase platformimplementation(platform("com.google.firebase:firebase-bom:34.3.0"))// Add the dependency for theFirebase AI Logic library// When using theBoM, you don't specify versions in Firebase library dependenciesimplementation("com.google.firebase:firebase-ai")}Sync your Android project with Gradle files.
Note that if you choose to not use theFirebase Android BoM, then just addthe dependency for thefirebase-ai
library and accept the latest versionthat's suggested by Android Studio.
Web
Get the latest version of the Firebase JS SDK for Web using npm:
npm i firebase@latest
OR
yarn add firebase@latest
Wherever you've imported the library, update your import statements to use
firebase/ai
instead.Note that it might be easier to migrate your app's codebase (see theremaining sections in this guide) before deleting the old imports.
// BEFOREimport{initializeApp}from"firebase/app";
import{getVertexAI,getGenerativeModel}from"firebase/vertexai-preview";// AFTERimport{initializeApp}from"firebase/app";import{getAI,getGenerativeModel}from"firebase/ai";
Dart
Update to the use the
firebase_ai
package in yourpubspec.yaml
file byrunning 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 inthis guide), make sure to delete the old package:
flutter pub remove firebase_vertexai
Unity
Support for Unity wasn't available from"Vertex AI in Firebase".
Learn how toget started with theFirebase AI Logic SDK for Unity.
Step 4: Update the initialization in your app
Click yourGemini API provider to view provider-specific content and code on this page. |
Update how you initialize the service for your chosen API provider andcreate aGenerativeModel
instance.
Swift
importFirebaseAI// Initialize the Gemini Developer API backend serviceletai=FirebaseAI.firebaseAI(backend:.googleAI())// Create a `GenerativeModel` instance with a model that supports your use caseletmodel=ai.generativeModel(modelName:"gemini-2.5-flash")
Kotlin
// Initialize the Gemini Developer API backend service// Create a `GenerativeModel` instance with a model that supports your use casevalmodel=Firebase.ai(backend=GenerativeBackend.googleAI()).generativeModel("gemini-2.5-flash")
Java
// Initialize the Gemini Developer API backend service// Create a `GenerativeModel` instance with a model that supports your use caseGenerativeModelai=FirebaseAI.getInstance(GenerativeBackend.googleAI()).generativeModel("gemini-2.5-flash");// Use the GenerativeModelFutures Java compatibility layer which offers// support for ListenableFuture and Publisher APIsGenerativeModelFuturesmodel=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-objectconstfirebaseConfig={// ...};// Initialize FirebaseAppconstfirebaseApp=initializeApp(firebaseConfig);// Initialize the Gemini Developer API backend serviceconstai=getAI(firebaseApp,{backend:newGoogleAIBackend()});// Create a `GenerativeModel` instance with a model that supports your use caseconstmodel=getGenerativeModel(ai,{model:"gemini-2.5-flash"});
Dart
import'package:firebase_ai/firebase_ai.dart';import'package:firebase_core/firebase_core.dart';import'firebase_options.dart';// Initialize FirebaseAppawaitFirebase.initializeApp(options:DefaultFirebaseOptions.currentPlatform,);// Initialize the Gemini Developer API backend service// Create a `GenerativeModel` instance with a model that supports your use casefinalmodel=FirebaseAI.googleAI().generativeModel(model:'gemini-2.5-flash');
Unity
Support for Unity wasn't available from "Vertex AI in Firebase".
Learn how toget started with theFirebase AI Logic SDK for Unity.
Note thatdepending on the capability you're using, you might not alwayscreate aGenerativeModel
instance.
- Toaccess anImagen model,create an
ImagenModel
instance.
Step 5: Update your code depending on features that you use
This step describes changes that may be required depending on which features youuse.
If you useCloud Storage URLsand you swapped to use theGemini Developer API in this migration, then you must update yourmultimodal requests toinclude 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 theFirebase AI Logic SDKs. Review the following lists for any changesthat you might need to make in your code to accommodate taking up theFirebase AI Logic SDK.
Required for all languages and platforms
Function calling
If you implemented this feature before GA, then you'll need to make updates tohow you define your schema. We recommend reviewing the updatedfunction calling guide to learn how towrite your function declarations.Generating structured output (like JSON) using
responseSchema
If you implemented this feature before GA, then you'll need to make updates tohow you define your schema. We recommend reviewing the newstructured output guide to learnhow to write JSON schemas.Timeout
- Changed the default timeout for requests to be 180 seconds.
Required based on platform or language
Swift
Enumerations
Replaced most
enum
types withstruct
s with static variables. Thischange allows more flexibility for evolving the API in abackward-compatible way. When usingswitch
statements, you must nowinclude adefault:
case to cover unknown or unhandled values,including new values that are added to the SDK in the future.Renamed the
BlockThreshold
enumeration toHarmBlockThreshold
; thistype is now astruct
.Removed
unknown
andunspecified
cases from the followingenumerations (nowstruct
s):HarmCategory
,HarmBlockThreshold
,HarmProbability
,BlockReason
, andFinishReason
.Replaced the enumeration
ModelContent.Part
with a protocol namedPart
to allow new types to be added in a backward-compatible way. Thischange is described in greater detail in theContent parts section.
Content parts
Removed the
ThrowingPartsRepresentable
protocol, and simplifiedthe initializers forModelContent
to avoid occasional compiler errors.Images that don't encode properly will still throw errors when beingused ingenerateContent
.Replaced the
ModelContent.Part
cases with the followingstruct
typesconforming to thePart
protocol:.text
toTextPart
.data
toInlineDataPart
.fileData
toFileDataPart
.functionCall
toFunctionCallPart
.functionResponse
toFunctionResponsePart
Harm category
- Changed the
HarmCategory
to no longer be nested in theSafetySetting
type. If you're referring to it asSafetySetting.HarmCategory
, thatcan be replaced withHarmCategory
.
- Changed the
Safety feedback
- Removed the
SafetyFeedback
type, since it wasn't used in any of theresponses.
- Removed the
Citation metadata
- Renamed the
citationSources
property tocitations
inCitationMetadata
.
- Renamed the
Total billable characters
- Changed the
totalBillableCharacters
property inCountTokensResponse
to be optional to reflect situations where no characters are sent.
- Changed the
Candidate response
- Renamed
CandidateResponse
toCandidate
to match other platforms.
- Renamed
Generation configuration
- Changed the public properties of
GenerationConfig
tointernal
. Theyall remain configurable in the initializer.
- Changed the public properties of
Kotlin
Enumerations
Replaced
enum
classes andsealed
classes with regular classes. Thischange allows more flexibility for evolving the API in a backwardcompatible way.Renamed the
BlockThreshold
enumeration toHarmBlockThreshold
.Removed values from the following enumerations:
HarmBlockThreshold
,HarmProbability
,HarmSeverity
,BlockReason
, andFinishReason
.
Blob methods
- Renamed all methods that included
Blob
as part of their name to useInlineData
instead.
- Renamed all methods that included
Safety settings
- Changed the field
method
to be nullable.
- Changed the field
Duration class
- Removed all usages of Kotlin's
Duration
class, 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
CitationMetadata
into anew class calledCitation
. Citations can be found in the list calledcitations
inCitationMetadata
. This change allows better alignmentof types across platforms.
- Wrapped all the fields previously declared in
Count tokens
- Changed the field
totalBillableCharacters
to be nullable.
- Changed the field
Total billable characters
- Changed the
totalBillableCharacters
property inCountTokensResponse
to be optional to reflect situations where no characters are sent.
- Changed the
Instantiating a model
- Moved the
requestOptions
parameter to the end of the parameter list toalign with other platforms.
- Moved the
Live API
Removed
UNSPECIFIED
value for enum classResponseModality
. Insteadusenull
.Renamed
LiveGenerationConfig.setResponseModalities
toLiveGenerationConfig.setResponseModality
.Removed the
LiveContentResponse.Status
class, and instead have nestedthe status fields as properties ofLiveContentResponse
.Removed the
LiveContentResponse
class, and instead have providedsubclasses ofLiveServerMessage
that match the responses from themodel.Changed
LiveModelFutures.connect
to returnListenableFuture<LiveSessionFutures>
instead ofListenableFuture<LiveSession>
.
Java
Enumerations
Replaced
enum
classes andsealed
classes with regular classes. Thischange allows more flexibility for evolving the API in a backwardcompatible way.Renamed the
BlockThreshold
enumeration toHarmBlockThreshold
.Removed values from the following enumerations:
HarmBlockThreshold
,HarmProbability
,HarmSeverity
,BlockReason
, andFinishReason
.
Blob methods
- Renamed all methods that included
Blob
as part of their name to useInlineData
instead.
- Renamed all methods that included
Safety settings
- Changed the field
method
to be nullable.
- Changed the field
Duration class
- Removed all usages of Kotlin's
Duration
class, 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
CitationMetadata
into anew class calledCitation
. Citations can be found in the list calledcitations
inCitationMetadata
. This change allows better alignmentof types across platforms.
- Wrapped all the fields previously declared in
Count tokens
- Changed the field
totalBillableCharacters
to be nullable.
- Changed the field
Total billable characters
- Changed the
totalBillableCharacters
property inCountTokensResponse
to be optional to reflect situations where no characters are sent.
- Changed the
Instantiating a model
- Moved the
requestOptions
parameter to the end of the parameter list toalign with other platforms.
- Moved the
Live API
Removed
UNSPECIFIED
value for enum classResponseModality
. Insteadusenull
.Renamed
LiveGenerationConfig.setResponseModalities
toLiveGenerationConfig.setResponseModality
.Removed the
LiveContentResponse.Status
class, and instead have nestedthe status fields as properties ofLiveContentResponse
.Removed the
LiveContentResponse
class, and instead have providedsubclasses ofLiveServerMessage
that match the responses from themodel.Changed
LiveModelFutures.connect
to returnListenableFuture<LiveSessionFutures>
instead ofListenableFuture<LiveSession>
.
Changed various Java builder methods to now correctly return the instanceof their class, instead of
void
.
Web
Enumerations
- Removed values from the following enumerations:
HarmCategory
,BlockThreshold
,HarmProbability
,HarmSeverity
,BlockReason
, andFinishReason
.
- Removed values from the following enumerations:
Block reason
- Changed
blockReason
inPromptFeedback
to be optional.
- Changed
Changes requiredonly if you're starting to use theGemini Developer API (instead of theVertex AI Gemini API):
Safety settings
- 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
Enumerations
- Removed values from the following enumerations:
HarmCategory
,HarmProbability
,BlockReason
, andFinishReason
.
- Removed values from the following enumerations:
Data part
- Renamed
DataPart
toInlineDataPart
, and thestatic
data
functiontoinlineData
to align with other platforms.
- Renamed
Request options
- Removed
RequestOptions
sincetimeout
wasn't functional. It will bere-added in the near future, but it will be moved to theGenerativeModel
type to match other platforms.
- Removed
Stop sequences
- Changed the
stopSequences
parameter inGenerationConfig
to beoptional and to default tonull
instead of an empty array.
- Changed the
Citations
- Renamed the
citationSources
property tocitations
inCitationMetadata
. TheCitationSource
type was renamed toCitation
to match other platforms.
- Renamed the
Unnecessary public types, methods, and properties
- Removed the following types, methods, and properties which wereunintentionally exposed:
defaultTimeout
,CountTokensResponseFields
,parseCountTokensResponse
,parseEmbedContentResponse
,parseGenerateContentResponse
,parseContent
,BatchEmbedContentsResponse
,ContentEmbedding
,EmbedContentRequest
,andEmbedContentResponse
.
- Removed the following types, methods, and properties which wereunintentionally exposed:
Count tokens
- Removed extra fields from the
countTokens
function that are no longernecessary. Onlycontents
is needed.
- Removed extra fields from the
Instantiating a model
- Moved the
systemInstruction
parameter to the end of the parameter listto align with other platforms.
- Moved the
Embedding functionality
- Removed unsupported embedding functionality (
embedContent
andbatchEmbedContents
) from the model.
- Removed unsupported embedding functionality (
Unity
Support for Unity wasn't available from"Vertex AI in Firebase".
Learn how toget started with theFirebase AI Logic SDK for Unity.
Possible errors related to migrating
As you're migrating to use the GA version ofFirebase AI Logic, you mightencounter errors if you haven't completed all of the required changes asdescribed in this migration guide.
403 Error:Requests to this API firebasevertexai.googleapis.com ... are blocked.
If you receive a 403 error that saysRequests to this API firebasevertexai.googleapis.com ... are blocked.
,it usually means that the Firebase API key in yourFirebase configuration file or object doesn't have a required API in itsallowlist for the product that you're trying to use.
Make sure that the Firebase API key used by your app has all therequired APIs included in the key's "API restrictions" allowlist.ForFirebase AI Logic, your Firebase API key needs to have at minimum theFirebase AI Logic API in its allowlist. This API should havebeen automatically added to your API key's allowlist when youenabled the required APIs in theFirebase console.
You can view all your API keys in theAPIs & Services >Credentials panel in theGoogle Cloud console.
Note: Firebase-related APIs use API keys only toidentify the Firebaseproject or app,not for authorization to call the API(like some other APIs allow). Authorization for Firebase-related APIs is handledseparately from the API key, either throughGoogle Cloud IAM permissions,Firebase Security Rules, orFirebase App Check. Learn more aboutFirebase API keys.Give feedback about your experience withFirebase AI Logic
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-10-03 UTC.