Chapters

Hide chapters

Practical Android AI

First Edition · Android 13 · Kotlin 2.0 · Android Studio Otter

6. Harnessing Cloud Power with Firebase AI Logic
Written by Zahidur Rahman Faisal

Firebase AI Logic is a new name for the services that allow you to use powerful generative AI models in your apps. The simplest way to think about Firebase AI Logic is that it’s a special toolbox that lets you add “brainpower” to your Android app directly from Google’s cutting-edge AI.

Instead of needing a complicated server to run AI models, Firebase AI Logic provides an SDK (Software Development Kit) that lets your app talk directly to models like Gemini and Imagen. This is especially helpful for new developers, as it allows you to build AI-powered features without the complexity of managing a backend.

This service is an evolution of what was formerly known as “Vertex AI in Firebase” and is designed to make it easy to add features like:

  • Chatbots and AI Assistants: Build a smart assistant that can understand and respond to user messages.

  • Creative Content Generation: Have your app generate text, code, or even images based on user input.

  • Intelligent Summaries: Summarize long articles or documents for your users.

The Offerings of Firebase AI Logic

Multimodal and Natural Language Input

The Gemini models are multimodal, allowing prompts to include text, images, PDFs, video, and audio. Some Gemini models can also generate multimodal output. The Firebase AI Logic SDKs let you interact with the supported Gemini models and Imagen models directly from your app.

Here’s a brief overview of the supported models for Firebase AI Logic and their latest stable models at the time of writing this book:

Specialty Description Model A balance between price and performance. Offers well-rounded capabilities, for example, describing images and processing audio. gemini-2.5- flash Advanced reasoning model. The most advanced model, capable of solving complex problems such as analyzing live video streams and taking necessary actions in 
different situations. gemini-2.5- pro Most cost efficient model Optimized for low-latency use cases, such as text generation or rewriting. gemini-2.5- flash-lite

All the models above support these input and output formats:

  • Input: Text, code, PDFs, images, video, audio.

  • Output: Text, code, JSON.

Growing Suite of Capabilities

Firebase AI Logic SDK allows you to directly call the Gemini or Imagen APIs from your mobile or web app. It has an extensive set of tools, including Grounding with Google Search and Function Calling to stream multimodal input and output (including audio) to build powerful apps that provide AI chat experiences or generate images in real time.

Robust infrastructure

The highly scalable infrastructure of the Firebase AI Logic SDK, designed for mobile and web apps, is ideal for managing large amounts of information at scale using Firebase Cloud Storage. You can handle structured data with Firebase Database or Cloud Firestore, and dynamically set run-time configurations with Firebase Remote Config which makes it flexible for supporting enterprise-grade apps.

Security and Restrictions

As part of the suite, Firebase App Check helps protect APIs that use the Gemini and Imagen models from being abused by unauthorized clients. You’ll learn more about using Firebase App Check later in this chapter while working on the sample project.

Firebase AI Logic also gives you full control over API usage. The default request limit is 100 requests per minute (RPM) per user. These per-user rate limits are configurable. If you want to adjust your per-user rate limit, you need to adjust the quota settings for the Firebase AI Logic API.

Why Choose Firebase AI Logic Over On-Device AI?

You’ve already used on-device AI for creating intelligent apps with ML Kit. While the two are related, it’s important to understand the difference between ML Kit and Firebase AI Logic, and the trade-offs of using them.

ML Kit is for on-device, pre-packaged machine-learning tasks, such as face detection, barcode scanning, or text recognition in images. You use it when you have a specific, well-defined task.

Firebase AI Logic, on the other hand, is for generative tasks. You use it when you want the AI to create something new and respond creatively to user input.

The table below summarizes the key differences between On-Device AI and Firebase AI Logic:

Firebase AI Logic On-device AI Factor Variable (100 ms to several seconds) — depends on network quality and server load. Not suitable for use cases that require immediate visual feedback. Ultra-low, making it ideal for real-time UI feedback, AR overlays, and live camera processing. Latency Firebase AI Logic, Cloud Functions ML Kit, Custom TensorFlow Lite (TFLite) Type Pay-as-you-go model. Costs scale directly with usage (API calls and compute time). More economical for low-volume or compute-intensive tasks that would be infeasible to run on-device. No per-inference cost. Primary costs lie in initial development and model optimization. More economical for high-volume, low-complexity tasks. Cost Model Requires a stable internet connection. Features fail when the user is offline. Fully functional offline. A major advantage for applications that must be reliable in all environments. Offline Capability Virtually unlimited. Provides access to large, state-of-the-art models (such as Gemini 1.5 Pro) that are too big and complex to run on mobile devices. Limited by the device’s computational power, memory, and battery life. Models must be small and highly optimized (e.g., TensorFlow Lite). Model Complexity & Power Instantaneous. Models, prompts, and parameters can be updated on the server at any time, with changes immediately reflected for all users. More difficult. Updating a bundled model requires a full app update. Over-the-air updates via Firebase ML Model Deployment are possible but more complex than server-side changes. Model Updatability Lower. Data must be transmitted to a server for processing, introducing potential privacy and data-sovereignty concerns for sensitive information. High. Sensitive data is processed locally and never leaves the user’s device, enhancing user trust and simplifying compliance with regulations such as GDPR. Data Privacy Highly scalable. Google’s managed backend automatically handles millions of concurrent users and requests. Scaling is device-dependent. Performance varies with hardware, and distributing updates to millions of users typically relies on app-store delivery. Scalability

Creating Intelligent Apps with Firebase AI Logic

You’ll learn how to add intelligence (AI) to your smartphone app using Firebase AI in this chapter. You’ll use Google’s latest GenAI models through Firebase, such as:

  • Imagen 4 for image generation.

  • Gemini 2.5 (Flash) for generating text from a given prompt.

You can reuse the Kodeco Kats app that you’ve built in previous chapters. Using Firebase AI Logic, you’ll generate descriptions for a selected cat breed as well as an image thumbnail of the cat (exciting, right?).

Note that you have some prerequisites to use these models:

  1. Subscribe to the Firebase Blaze Plan.

  2. Enable the Gemini Developer API after connecting the project with Firebase.

  3. Use the latest Firebase AI dependency.

To get started, download and launch the starter project.

Step 1: Open the Firebase Assistant

In Android Studio, go to the top menu and select Tools > Firebase. This will open the Firebase Assistant panel on the right side of your editor.

Step 2: Select and Set Up Firebase AI

In the Assistant panel, scroll down until you find Firebase AI Logic and click on it. Select the Get started with the Firebase AI Logic link.

Firebase AI Logic
Firebase AI Logic

Step 3: Connect Your App to Firebase

  1. The assistant will first prompt you to connect your app to a Firebase project. Click the Connect to Firebase button.

  2. This will launch the Web Connect Flow. A browser window will open, asking you to log in to your Google account if you’re not already logged into your Firebase console.

  3. After logging in, you will be prompted to either create a new Firebase project or select an existing one. Choose Create a new Firebase Project.

Create a Project
Create a Project

  1. Provide a descriptive name for the project. Firebase will automatically generate a globally unique Project ID based on this name. This ID is immutable after project creation and is used in public-facing URLs, so review the auto-generated ID and edit it if necessary.

Naming a Project
Naming a Project

  1. Once the setup is complete, you’ll see a confirmation from Firebase. Tap Connect on the confirmation screen.

Firebase Connect
Firebase Connect

  1. After you click Connect, Android Studio will automatically configure your project. The Firebase console will display a message if the connection is successful.

Firebase Confirmation
Firebase Confirmation

Step 4: Review Billing Plan in the Firebase Console

This step is required for image generation. Setting up a billing plan is a prerequisite for using Imagen API. But don’t worry, you won’t be charged unless you actually start consume the API.

Note: Review the Imagen4 Pricing Info for image generation.

  1. Open the Project Overview page in the Firebase console.

  2. By default, the billing plan is set to the Spark plan. Tap the plan information to change it to Blaze plan.

Default Plan
Default Plan

  1. In the Firebase pricing plans window, select Blaze plan.

Select Plan
Select Plan

  1. Click Create a Cloud Billing account and complete the billing setup.

Create a Cloud Billing
Create a Cloud Billing

  1. Before linking the Cloud Billing account, remember to set a billing budget. You can set the budget as low as you prefer — this helps prevent accidental charges while testing your app. Firebase will notify you via email at 50%, 90%, and 100% of your budget usage so you can take preventive action.

Billing Budget
Billing Budget

  1. Once your billing account is successfully connected and the project is upgraded to the Blaze plan, a confirmation message will appear. Press Done to return to the Project Overview page.

Blaze Plan Successful
Blaze Plan Successful

Step 5: Enable Gemini Developer API in the Firebase Console

  1. From the Project Overview page, select Product categories > AI > AI Logic. Tap the Get started button.

Get Started AI Logic
Get Started AI Logic

  1. In the next window, select Get started with this API under the Gemini Developer API panel, and then press Enable. This will create API keys and enable the necessary APIs.

Gemini Developer API
Gemini Developer API

  1. Tap Continue to finish the setup. You’re now ready to consume Firebase AI Logic APIs from the app.

Step 6: Add Firebase AI Logic from Android Studio

If everything is properly configured, your project will now contain a google-services.json file inside the app directory. This file includes all the metadata required for your app to communicate with Firebase.

google-services
google-services

Note: If you try out the final project for this chapter, remember to replace the included google-services.json file with your own configuration file.

At this point, you should see a Connected status at the top of the Firebase Assistant panel, indicating that Android Studio has successfully linked your project with Firebase.

Add Firebase AI Logic
Add Firebase AI Logic

  1. Click Add the Firebase AI Logic to your app button there.

  2. Tap Accept Changes in the popup dialog. Android Studio will automatically add the necessary dependencies for Firebase AI Logic.

Firebase AI Logic Dependencies
Firebase AI Logic Dependencies

This will sync your project with Gradle and start downloading the required dependencies.

Step 7: Initialize Firebase AI Instance

Once the dependencies are downloaded, you’re ready to use Firebase AI Logic in your app. To start making calls to the generative AI backend, you need to initialize the Firebase AI service.

Open the MainViewModel.kt and add the following imports at the top of the file:

import com.google.firebase.Firebase
import com.google.firebase.ai.ai
import com.google.firebase.ai.type.GenerativeBackend

Now, add the following code inside the MainViewModel class:

val firebaseAI = Firebase.ai(
  backend = GenerativeBackend.googleAI(),
  useLimitedUseAppCheckTokens = true
)

The firebaseAI instance provides access to the Firebase AI APIs for interacting with Gemini and Imagen models directly from your app.

  • The backend parameter defines that you’re using Google’s Generative AI backend, which is the recommended API provider for Android Developers.

  • Setting useLimitedUseAppCheckTokens = true ensures that Firebase App Check is enabled to limit token misuse when sending requests to the backend. Firebase App Check helps prevent API calls from unauthorized clients by verifying the integrity of your app.

Here’s how your app interacts with AI models through Firebase AI Logic:

Firebase Firebase Android SDK Android App Cloud Gemini Developer API Google Cloud Platform Gemini Pro & Flash Gemini Pro & Flash Vertex AI
Firebase AI Logic Integration

You’re now ready to make your first API call to Firebase AI!

Generating Images with Imagen 4

Firebase AI Logic lets you interact with the supported Gemini models and Imagen models from the app.

The key difference between Gemini and Imagen models is that Gemini models are multimodal because they can process and generate multiple modalities, such as text, code, PDFs, images, video, and audio. Imagen models, on the other hand, are trained for image generation and modification.

Imagen is best suited for:

  • Generating images from natural language prompts.
  • Generating images in a wide range of formats and styles.
  • Rendering text within generated images.

Choosing Imagen Model

Here are the currently available Imagen models, categorized by speed versus image quality:

Specialty Model Category Quickly generates low-fidelity images for prototyping or low-latency use cases. imagen-4.0-fast-generate-001 Imagen 4 Fast Generates high-quality images from natural language text prompts. imagen-4.0-generate-001 Imagen 4 Produces photo-realistic, highest-quality images from text prompts. imagen-4.0-ultra-generate-001 Imagen 4 Ultra

When you launch the starter project, you’ll see a list of different cat breeds. You’re probably curious to know how each breed looks! You’ll use Imagen to generate an image for each breed you select from the list.

Run the app and select any cat breed of your choice. It’ll take you to the DetailScreen. Currently, there’s a placeholder for cat image and you’ll see a loader for generating info.

You’ll need to define what sort of image you want to display in the image placeholder - for example, JPEG or PNG, portrait or landscape. The Imagen API lets you set these parameters along with the model configuration.

Configuring Output Image

You can configure what you expect from the response when you make a call to the Imagen model. Open MainViewModel.kt and define the output configuration as follows:

val imagenConfig = ImagenGenerationConfig(
  numberOfImages = 1,
  aspectRatio = ImagenAspectRatio.LANDSCAPE_16x9,
  imageFormat = ImagenImageFormat.png(),
)

This block is self-explanatory:

  • numberOfImages specifies how many images should be generated from a single prompt.

  • aspectRatio defines the proportions of the generated image (portrait, landscape, or square).

  • imageFormat determines the file format or compression type (e.g., JPEG or PNG).

If image generation fails, an error will be logged, so watch your Logcat console. This can happen for various reasons, for example, no internet connection or if the Firebase project is not configured with a Blaze plan.

Defining the Model

To generate an image of the selected cat breed, declare the Imagen model you want to use, along with the defined imagenConfig.

val imagenModel = firebaseAI.imagenModel(
  modelName = "imagen-4.0-fast-generate-001",
  generationConfig = imagenConfig,
)

Using modelName = "imagen-4.0-fast-generate-001" ensures you’re using the fastest and most cost-effective model, since you don’t need ultra-high fidelity for this use case.

Generating Image from Prompt

Ready to create an image from a prompt? Add this function below imagenModel block in MainViewModel.kt:

fun generateCatImage(breed: String) {
  val prompt = "A cat of $breed breed."

  viewModelScope.launch(Dispatchers.IO) {
    try {
      _catImage.value = null

      val response = imagenModel.generateImages(prompt)

      val image = response.images.first()
      _catImage.value = image.asBitmap()
    } catch (e: Exception) {
      Log.e("MainViewModel", "Error generating cat image", e)
    }
  }
}

This function performs the following steps:

  1. Takes the breed name as an input parameter and creates a descriptive prompt.

  2. Calls imagenModel.generateImages() with that prompt to generate an image accordingly.

  3. The response from Imagen model returns a list of images. As you set numberOfImages = 1 in the imagenConfig, there will be only one item in the list; you’re picking the first item from the list.

  4. Updates the _catImage state by converting the image into a Bitmap.

Display the Image

The rest is easy! Go to DetailScreen.kt and add following lines inside the DetailScreen composable:

LaunchedEffect(breedName) {
  viewModel.generateCatImage(breedName)
}

The LaunchedEffect triggers the viewModel to generate an image of the selected cat breed as soon as the Composable is rendered. The catImage state automatically updates the Image placeholder once the generated image is ready and propagated from viewModel.

Using the Imagen API requires your Firebase project to be on the paid “Blaze” (Pay as you go) plan. The Blaze plan includes the same free usage as the Spark plan, plus an additional free tier for paid services like the Imagen API.

Build and run the app, tap on any list item, and navigate to the DetailScreen – you’ll see a freshly generated image of the selected cat breed appear, courtesy of Imagen!

Image generation using Imagen API
Image generation using Imagen API

Generating Description with Gemini Model

Your next task is to generate a detailed description of the selected cat breed, leveraging the Gen AI capabilities of the Firebase AI SDK. Getting started is simple, go back to MainViewModel.kt and define the AI model:

val genAiModel = firebaseAI.generativeModel(modelName = "gemini-2.5-flash-lite")

Here, genAiModel gives you access to the gemini-2.5-flash-lite model for text generation through firebaseAI.

Generating Content from Prompt

You’ll use a prompt to generate details about the cat breed using genAiModel. To do so, add the following function:

fun describeCat(breed: String) {
  val prompt = "Describe the $breed cat."

  viewModelScope.launch(Dispatchers.IO) {
    _isLoading.value = true
    _catDescription.value = "Generating details for $breed cat..."

    val response = genAiModel.generateContent(prompt)
    val responseText = response.text

    _catDescription.value = responseText ?: "Description not available."
    _isLoading.value = false
  }
}

This function works as follows:

  • Creates a prompt from provided breed name to generate description of that breed.

  • Displays a loading state while generating details using genAiModel.

  • genAiModel.generateContent(prompt) does the job – it executes text generation from the text input given to the model as a prompt.

  • Updates _catDescription with the model’s output or a fallback message if generation fails.

Simple as that!

Displaying Content

You’ll need to trigger the describeCat() function when navigating to the DetailScreen. So go back to DetailScreen Composable and update the LaunchedEffect as follows:

LaunchedEffect(breedName) {
  viewModel.generateCatImage(breedName)
  viewModel.describeCat(breedName)
}

By adding viewModel.describeCat(), you instruct the viewModel to generate a textual description for the selected breed.

The val catDescription by viewModel.catDescription.collectAsState() statement at the beginning of the DetailScreen composable ensures that the description is displayed automatically when ready.

Build and run the app again. Navigate to the DetailScreen and you’ll see a generated image of the cat along with a detailed description of its breed!

Cat description generation in Detail Screen
Cat description generation in Detail Screen

Production Readiness Checklist

Deploying an AI feature is not the end of the development process. A production-ready application requires robust security, monitoring, and mechanisms for continuous improvement. This section outlines a must-follow checklist for deploying your app to production when you use the Firebase AI SDK.

Secure with Firebase App Check

Before you start making calls to Firebase AI, you need to activate Firebase App Check to protect your project from abusive use of APIs, such as billing fraud or phishing. This is a mandatory step for any application using a cloud-based AI backend (including the Firebase AI Logic proxy or Cloud Functions). Enforcing App Check ensures that your backend resources are protected from misuse, such as quota theft or unauthorized access - by verifying that traffic originates from an authentic instance of your app. Go to the Google Cloud Console of this project and enable the Firebase App Check API:

Firebase App Check API
Firebase App Check API

Note: Firebase App Check is strongly recommend when you’re using Firebase AI Logic. Visit the official docs for more details on configuring Firebase App Check.

Dynamic Updates with Firebase Remote Config

Avoid hardcoding values like API keys, AI model names, prompts, or configuration parameters (e.g., temperature, top-K) in the app. Instead, store these in Firebase Remote Config. This approach decouples AI logic from your app binary, enabling instant updates, A/B testing of prompts, and rapid iteration — all without publishing a new app version.

API Restrictions

In the Google Cloud Console, go to “APIs & Services > Credentials”. Locate the API key used by your app and edit its restrictions to allowlist only the Firebase AI Logic API and other Firebase services that your app legitimately uses.

Conclusion

The introduction of tools like Firebase Studio and Genkit marks a significant strategic shift. Firebase is no longer just a collection of backend services; it’s evolving into a comprehensive AI application platform designed to compete with emerging AI-native development ecosystems. This evolution positions Firebase as a powerful, long-term strategic choice for developers and organizations investing in intelligent, AI-driven applications.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2026 Kodeco Inc.