Migrate to the Firebase AI Logic SDKs from the Preview version of Vertex AI in Firebase SDKs

This guide helps you migrate from the Preview (or beta) versions of the "Vertex AI in Firebase" SDKs to theFirebase AI Logic client SDKs.
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.

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

  2. In theFirebase console, go to theFirebase AI Logic page.

  3. ClickGet started to launch a guided workflow that helps you set up therequired APIsand resources for your project.

  4. 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 APIbilling 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 APIbilling required(requires the pay-as-you-go Blaze pricing plan)
      The console's workflow will enable therequired APIs in your project.

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

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

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

  3. Select your app's target in the Project Editor, and then navigate to theFrameworks, Libraries, and Embedded Content section.

  4. Add the new library: Select the+ button, and then addFirebaseAIfrom the Firebase package.

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

  1. 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")}
  2. 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

  1. 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")}
  2. 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

  1. Get the latest version of the Firebase JS SDK for Web using npm:

    npm i firebase@latest

    OR

    yarn add firebase@latest
  2. Wherever you've imported the library, update your import statements to usefirebase/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

  1. Update to the use thefirebase_ai package in yourpubspec.yaml file byrunning the following command from your Flutter project directory:

    flutter pub add firebase_ai
  2. Rebuild your Flutter project:

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

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) usingresponseSchema
    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 mostenum types withstructs 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 theBlockThreshold enumeration toHarmBlockThreshold; thistype is now astruct.

    • Removedunknown andunspecified cases from the followingenumerations (nowstructs):HarmCategory,HarmBlockThreshold,HarmProbability,BlockReason, andFinishReason.

    • Replaced the enumerationModelContent.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 theThrowingPartsRepresentable protocol, and simplifiedthe initializers forModelContent to avoid occasional compiler errors.Images that don't encode properly will still throw errors when beingused ingenerateContent.

    • Replaced theModelContent.Part cases with the followingstruct typesconforming to thePart protocol:

      • .text toTextPart
      • .data toInlineDataPart
      • .fileData toFileDataPart
      • .functionCall toFunctionCallPart
      • .functionResponse toFunctionResponsePart
  • Harm category

    • Changed theHarmCategory to no longer be nested in theSafetySettingtype. If you're referring to it asSafetySetting.HarmCategory, thatcan be replaced withHarmCategory.
  • Safety feedback

    • Removed theSafetyFeedback type, since it wasn't used in any of theresponses.
  • Citation metadata

    • Renamed thecitationSources property tocitations inCitationMetadata.
  • Total billable characters

    • Changed thetotalBillableCharacters property inCountTokensResponseto be optional to reflect situations where no characters are sent.
  • Candidate response

    • RenamedCandidateResponse toCandidate to match other platforms.
  • Generation configuration

    • Changed the public properties ofGenerationConfig tointernal. Theyall remain configurable in the initializer.

Kotlin

  • Enumerations

    • Replacedenum classes andsealed classes with regular classes. Thischange allows more flexibility for evolving the API in a backwardcompatible way.

    • Renamed theBlockThreshold enumeration toHarmBlockThreshold.

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

  • Blob methods

    • Renamed all methods that includedBlob as part of their name to useInlineData instead.
  • Safety settings

    • Changed the fieldmethod to be nullable.
  • Duration class

    • Removed all usages of Kotlin'sDuration class, and replaced it withlong. This change provides better interoperability with Java.
  • Citation metadata

    • Wrapped all the fields previously declared inCitationMetadata into anew class calledCitation. Citations can be found in the list calledcitations inCitationMetadata. This change allows better alignmentof types across platforms.
  • Count tokens

    • Changed the fieldtotalBillableCharacters to be nullable.
  • Total billable characters

    • Changed thetotalBillableCharacters property inCountTokensResponseto be optional to reflect situations where no characters are sent.
  • Instantiating a model

    • Moved therequestOptions parameter to the end of the parameter list toalign with other platforms.
  • Live API

    • RemovedUNSPECIFIED value for enum classResponseModality. Insteadusenull.

    • RenamedLiveGenerationConfig.setResponseModalities toLiveGenerationConfig.setResponseModality.

    • Removed theLiveContentResponse.Status class, and instead have nestedthe status fields as properties ofLiveContentResponse.

    • Removed theLiveContentResponse class, and instead have providedsubclasses ofLiveServerMessage that match the responses from themodel.

    • ChangedLiveModelFutures.connect to returnListenableFuture<LiveSessionFutures> instead ofListenableFuture<LiveSession>.

Java

  • Enumerations

    • Replacedenum classes andsealed classes with regular classes. Thischange allows more flexibility for evolving the API in a backwardcompatible way.

    • Renamed theBlockThreshold enumeration toHarmBlockThreshold.

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

  • Blob methods

    • Renamed all methods that includedBlob as part of their name to useInlineData instead.
  • Safety settings

    • Changed the fieldmethod to be nullable.
  • Duration class

    • Removed all usages of Kotlin'sDuration class, and replaced it withlong. This change provides better interoperability with Java.
  • Citation metadata

    • Wrapped all the fields previously declared inCitationMetadata into anew class calledCitation. Citations can be found in the list calledcitations inCitationMetadata. This change allows better alignmentof types across platforms.
  • Count tokens

    • Changed the fieldtotalBillableCharacters to be nullable.
  • Total billable characters

    • Changed thetotalBillableCharacters property inCountTokensResponseto be optional to reflect situations where no characters are sent.
  • Instantiating a model

    • Moved therequestOptions parameter to the end of the parameter list toalign with other platforms.
  • Live API

    • RemovedUNSPECIFIED value for enum classResponseModality. Insteadusenull.

    • RenamedLiveGenerationConfig.setResponseModalities toLiveGenerationConfig.setResponseModality.

    • Removed theLiveContentResponse.Status class, and instead have nestedthe status fields as properties ofLiveContentResponse.

    • Removed theLiveContentResponse class, and instead have providedsubclasses ofLiveServerMessage that match the responses from themodel.

    • ChangedLiveModelFutures.connect to returnListenableFuture<LiveSessionFutures> instead ofListenableFuture<LiveSession>.

  • Changed various Java builder methods to now correctly return the instanceof their class, instead ofvoid.

Web

  • Enumerations

    • Removed values from the following enumerations:HarmCategory,BlockThreshold,HarmProbability,HarmSeverity,BlockReason, andFinishReason.
  • Block reason

    • ChangedblockReason inPromptFeedback to be optional.

Changes requiredonly if you're starting to use theGemini Developer API (instead of theVertex AI Gemini API):

  • Safety settings

    • Removed usages of the unsupportedSafetySetting.method.
  • Inline data

    • Removed usages of the unsupportedInlineDataPart.videoMetadata.

Dart

  • Enumerations

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

    • RenamedDataPart toInlineDataPart, and thestaticdata functiontoinlineData to align with other platforms.
  • Request options

    • RemovedRequestOptions sincetimeout wasn't functional. It will bere-added in the near future, but it will be moved to theGenerativeModel type to match other platforms.
  • Stop sequences

    • Changed thestopSequences parameter inGenerationConfig to beoptional and to default tonull instead of an empty array.
  • Citations

    • Renamed thecitationSources property tocitations inCitationMetadata. TheCitationSource type was renamed toCitationto match other platforms.
  • 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.
  • Count tokens

    • Removed extra fields from thecountTokens function that are no longernecessary. Onlycontents is needed.
  • Instantiating a model

    • Moved thesystemInstruction parameter to the end of the parameter listto align with other platforms.
  • Embedding functionality

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

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.