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 Google AI client 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 or Preview (or beta) version of a "Vertex AI in Firebase" SDK, then go to the guide formigrating from the GA version of the SDK ormigrating from the preview version of the SDK.
Go directly to migration instructions
Why migrate to use theFirebase AI Logic SDKs?
You might have tried out an alternative set of mobile or web client SDKs thatgave you access to theGemini Developer API.
Those client SDKs were not integrated into the robust Firebase ecosystem thatoffers critical services for mobile and web apps. They are now deprecated infavor of theFirebase AI Logic client SDKs, which can give youaccess to theGemini Developer API.
Security features for mobile and web apps
For mobile and web apps, security is critical and requires specialconsiderations because your code – including calls to theGemini API – isrunning in an unprotected environment. You can useFirebase App Check toprotect APIs from abuse by unauthorized clients.
When youuseFirebase App Check withFirebase AI Logic,you never add yourGemini API key for theGemini Developer APIdirectly into your mobile or web app's codebase. Instead, theGemini API key stays on the server, unexposed to malicious actors.
Ecosystem built for mobile and web apps
Firebase is Google's platform for developing mobile and web apps. UsingFirebase AI Logic means that your apps are in an ecosystem that's focused onthe needs of full-stack apps and developers. For example:
Dynamically set run-time configurations or swap out values inyour app (like a model name and version) without releasing a new app versionusingFirebase Remote Config.
UseCloud Storage for Firebase to include large files in your multimodalrequests (if you use theVertex AI Gemini API). TheCloud Storage client SDKs help you handle file uploads and downloads (even inpoor network conditions) and offer more security for your end-users' data.Learn more in oursolution guide about usingCloud Storage for Firebase.
Manage structured data using database SDKs built for mobile and web apps(likeCloud Firestore).
Migrate to theFirebase AI Logic SDKs
Overview of steps to migrate to theFirebase AI Logic SDKs:
Step 1: Set up a new or existing Firebase project and connect your app toFirebase.
Step 2: Add theFirebase AI Logic SDKs to your app.
Step 3: Update your imports and initialization in your app.
Step 4: Update your code depending on the features that you use.
Step 1: Set up a Firebase project and connect your app
Sign into theFirebase console,and then select your Firebase project.
Don't already have a Firebase project?
If you don't already have a Firebase project, click the button to create anew Firebase project, and then use either of the following options:
Option 1: Create a wholly new Firebase project (and its underlyingGoogle Cloud project automatically) by entering a new project name in thefirst step of the workflow.
Option 2: "Add Firebase" to an existingGoogle Cloud project byclickingAdd Firebase to Google Cloud project (at bottom of page).In the first step of the workflow, start entering theproject name ofthe existing project, and then select the project from the displayed list.
If you'd like, you can add Firebase to the project that was created behindthe scenes when you created aGemini API key inGoogle AI Studio.
Complete the remaining steps of the on-screen workflow to create a Firebaseproject. Note that when prompted, you donot need to set upGoogle Analytics to use theFirebase AI Logic SDKs.
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 theGemini Developer API. You can always set up and usethe other API provider later, if you'd like.
The console will enable the required APIs and create a new, dedicatedGemini API key in your project.
Donot add this newGemini API key into your app's codebase.Learn more.If prompted in the console's workflow, follow the on-screen instructions toregister your app and connect it to Firebase.
Continue in this migration guide to update the library and initialization inyour app.
Step 2: Add theFirebase AI Logic SDK to your app
With your Firebase project set up and your app connected to Firebase(see previous step), you can now add theFirebase AI Logic SDK to your app.
Swift
Use Swift Package Manager to install and manage Firebase dependencies.
Note: Visitour installation guide to learnabout the different ways you can add Firebase SDKs to your Apple project,including importing frameworks directly and using CocoaPods.TheFirebase AI Logic library provides access to the APIs for interactingwithGemini andImagen models. The library is includedas part of the Firebase SDK for Apple platforms (firebase-ios-sdk
).
If you're already using Firebase, then make sure your Firebase package isv11.13.0 or later.
In Xcode, with your app project open, navigate toFile > Add Package Dependencies.
When prompted, add the Firebase Apple platforms SDK repository:
https://github.com/firebase/firebase-ios-sdk
Select the latest SDK version.
Select the
FirebaseAI
library.
When finished, Xcode will automatically begin resolving and downloading yourdependencies in the background.
Kotlin
TheFirebase AI Logic SDK for Android (firebase-ai
) providesaccess to the APIs for interacting withGemini andImagen models.
In yourmodule (app-level) Gradle file(like<project>/<app-module>/build.gradle.kts
),add the dependency for theFirebase AI Logic library for Android.We recommend using theFirebase Android BoMto control library versioning.
dependencies{// ... other androidx dependencies// 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")}
By using theFirebase Android BoM,your app will always use compatible versions of Firebase Android libraries.
(Alternative) Add Firebase library dependencies without using theBoM
If you choose not to use theFirebase BoM, you must specify eachFirebase library version in its dependency line.
Note that if you usemultiple Firebase libraries in your app, westrongly recommend using theBoM to manage library versions, whichensures that all versions are compatible.
dependencies{// Add the dependency for theFirebase AI Logic library// When NOT using theBoM, you must specify versions in Firebase library dependenciesimplementation("com.google.firebase:firebase-ai:17.3.0")}
Java
TheFirebase AI Logic SDK for Android (firebase-ai
) providesaccess to the APIs for interacting withGemini andImagen models.
In yourmodule (app-level) Gradle file(like<project>/<app-module>/build.gradle.kts
),add the dependency for theFirebase AI Logic library for Android.We recommend using theFirebase Android BoMto control library versioning.
For Java, you need to add two additional libraries.
dependencies{// ... other androidx dependencies// 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")// Required for one-shot operations (to use `ListenableFuture` from Guava Android)implementation("com.google.guava:guava:31.0.1-android")// Required for streaming operations (to use `Publisher` from Reactive Streams)implementation("org.reactivestreams:reactive-streams:1.0.4")}
By using theFirebase Android BoM,your app will always use compatible versions of Firebase Android libraries.
(Alternative) Add Firebase library dependencies without using theBoM
If you choose not to use theFirebase BoM, you must specify eachFirebase library version in its dependency line.
Note that if you usemultiple Firebase libraries in your app, westrongly recommend using theBoM to manage library versions, whichensures that all versions are compatible.
dependencies{// Add the dependency for theFirebase AI Logic library// When NOT using theBoM, you must specify versions in Firebase library dependenciesimplementation("com.google.firebase:firebase-ai:17.3.0")}
Web
TheFirebase AI Logic library provides access to the APIs for interactingwithGemini andImagen models. The library is includedas part of the Firebase JavaScript SDK for Web.
Install the Firebase JS SDK for Web using npm:
npm install firebase
Initialize Firebase in your app:
import{initializeApp}from"firebase/app";// 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);
Dart
TheFirebase AI Logic plugin for Flutter (firebase_ai
) providesaccess to the APIs for interacting withGemini andImagen models.
From your Flutter project directory, run the following command toinstall the core plugin and theFirebase AI Logic plugin:
flutterpubaddfirebase_corefirebase_ai
In your
lib/main.dart
file, import the Firebase core plugin, theFirebase AI Logic plugin, and the configuration file you generatedearlier:import'package:firebase_core/firebase_core.dart';import'package:firebase_ai/firebase_ai.dart';import'firebase_options.dart';
Also in your
lib/main.dart
file, initialize Firebase using theDefaultFirebaseOptions
object exported by the configuration file:awaitFirebase.initializeApp(options:DefaultFirebaseOptions.currentPlatform,);
Rebuild your Flutter application:
flutterrun
Unity
Support for Unity wasn't available from theGoogle AI client SDKs.
Learn how toget started with theFirebase AI Logic SDK for Unity.
Remove the old SDK from your app
After you've finished migrating your app (see the remaining sections in thisguide), make sure to delete the old library.
Swift
Remove the old library:
In Xcode, with your app project open, navigate to thePackages Dependencies pane.
Select the
generative-ai-swift
package from the list of packagedependencies.Click the
-
button from the bottom of the list and clickRemoveto confirm.
Kotlin
dependencies{implementation("com.google.ai.client.generativeai:generativeai:VERSION")}
Java
dependencies{implementation("com.google.ai.client.generativeai:generativeai:VERSION")}
Web
// BEFOREimport{initializeApp}from"firebase/app";import{GoogleGenerativeAI}from"@google/generative-ai";
Dart
Delete the old package:flutter pub remove google_generative_ai
Unity
Support for Unity wasn't available fromGoogle AI client SDKs.
Learn how toget started with theFirebase AI Logic SDK for Unity.
Step 3: Update your imports and initialization in your app
Update your imports and how you initialize theGemini Developer APIbackend service and create aGenerativeModel
instance.
As soon as you start seriously developing your app,it's critical that youintegrate withFirebase App Check so that only requests from your actual app and verified devices are passed through to the backend.
Swift
// BEFOREimportGoogleGenerativeAIletmodel=GenerativeModel(name:"MODEL_NAME",apiKey:APIKey.default)// AFTERimportFirebaseAI// 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
// BEFOREimportcom.google.ai.client.generativeai.Chatimportcom.google.ai.client.generativeai.type.Contentimportcom.google.ai.client.generativeai.java.GenerativeModuleFutures...valgenerativeModel=GenerativeModel(modelName="MODEL_NAME",// Access your API key as a Build Configuration variableapiKey=BuildConfig.apiKey)// AFTERimportcom.google.firebase.Firebaseimportcom.google.firebase.ai.aiimportcom.google.firebase.ai.type.GenerativeBackend...// 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
// BEFOREimportcom.google.ai.client.generativeai.Chat;importcom.google.ai.client.generativeai.type.Content;importcom.google.ai.client.generativeai.java.GenerativeModuleFutures;...GenerativeModelgm=newGenerativeModel("MODEL_NAME",// Access your API key as a Build Configuration variableBuildConfig.apiKey);GenerativeModelFuturesmodel=GenerativeModelFutures.from(gm);// AFTERimportcom.google.firebase.ai.FirebaseAI;importcom.google.firebase.ai.GenerativeModel;importcom.google.firebase.ai.java.GenerativeModelFutures;importcom.google.firebase.ai.type.GenerativeBackend;...// 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
// BEFOREimport{GoogleGenerativeAI}from"@google/generative-ai";// Fetch your API_KEY and access your APIconstAPI_KEY="...";constgenAI=newGoogleGenerativeAI(API_KEY);...constmodel=genAI.getGenerativeModel({model:"MODEL_NAME"});// AFTERimport{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
// BEFOREimport'package:google_generative_ai/google_generative_ai.dart';finalapiKey=Platform.environment['API_KEY'];if(apiKey==null){print('No\$API_KEY environment variable');exit(1);}finalmodel=GenerativeModel(model:'MODEL_NAME',apiKey:apiKey);// AFTERimport'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 fromGoogle AI client SDKs.
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 4: Update code depending on the features that you use
This step describes changes that may be required depending on which features youuse.
TheFirebase AI Logic client SDKs don't supportcode execution. If you use this feature, make sure to accommodate this inyour app.
Review the following lists for any changes that you might need to make in yourcode to accommodate migrating to theFirebase AI Logic client SDKs.
Required for all languages and platforms
Function calling
If you implemented this feature, 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, 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
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
Web
Note that theGoogle AI client SDK for JavaScript has had manychanges since the time that theFirebase AI Logic client SDKs branched from it. Thefollowing list are some potential changes that you might need to consider asyou migrate to theFirebase AI Logic client SDKs.
Enumerations
- Removed values from the following enumerations:
HarmCategory
,BlockThreshold
,HarmProbability
,HarmSeverity
,BlockReason
, andFinishReason
.
- Removed values from the following enumerations:
Block reason
- Changed
blockReason
inPromptFeedback
to be optional.
- Changed
Search Grounding
- Removed all usages of this feature, since it's not yet supported in theFirebase AI Logic SDKs.
Errors
- Removed all usages of
GoogleGenerativeAIError
, and optionally move toAIError
.
- Removed all usages of
Dart
Enumerations
- Removed values from the following enumerations:
HarmCategory
,HarmProbability
,BlockReason
, andFinishReason
.
- Removed values from the following enumerations:
Data part
- Renamed
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 fromGoogle AI client SDKs.
Learn how toget started with theFirebase AI Logic SDK for Unity.
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.