Gemini in your app with Firebase AI Logic

How to call Gemini from Android with Firebase AI Logic: the client SDK, streaming Flow, chat history, function calling, and Firebase App Check protection. About 25 minutes.

Why it matters

  • Firebase AI Logic is the Google-supported way to call Gemini from an Android app without shipping a secret key. Interviewers at product companies ask how you keep the key off the device and what happens when a user decompiles the APK.
  • Streaming with generateContentStream returns a Kotlin Flow<GenerateContentResponse>. Getting the cancellation and partial-text rendering right in Compose is a common mid-to-senior screen question.
  • Function calling and JSON-schema output turn a chat widget into an agent. Knowing the request-response loop and the step limit separates a demo from a shipped feature.
  • Firebase App Check is the gate. Your Firebase config ships inside the APK, so without enforced App Check anyone can copy it and call the model on your bill. This is the first thing a security reviewer checks.

The simple explanation

  • Firebase AI Logic is a receptionist at a hotel.
  • You (the app) ask the receptionist for a room (a Gemini call).
  • The receptionist checks your ID (Firebase App Check) and talks to the hotel manager (Google's servers) using a key you never see.
  • The manager sends the answer back in small envelopes (streaming chunks).
  • You open each envelope and read the text as it arrives, instead of waiting for one big letter.
  • If you leave the lobby (user navigates away), the receptionist stops delivering envelopes (Flow cancellation).

Firebase AI Logic is a client SDK. You never put a Gemini API key in the app. The call path is: app → Firebase AI Logic proxy → Gemini API. When App Check is enforced, the proxy rejects requests without a valid App Check token.

Entry point: Firebase.ai(backend = GenerativeBackend.googleAI()) returns a FirebaseAI instance. Call .generativeModel(modelName) to get a GenerativeModel. Check the current Firebase docs for supported model names and device requirements; they change often.

CallReturnsUse case
generateContent(prompt)GenerateContentResponseOne-shot, non-streaming
generateContentStream(prompt)Flow<GenerateContentResponse>Token-by-token UI
startChat(history)ChatMulti-turn; then sendMessage / sendMessageStream
generativeModel(name, tools = ...)GenerativeModelDeclare callable functions

Function calling loop: the response's functionCalls list holds FunctionCallPart items with a name and JSON args. Your code runs the function, wraps the result in a FunctionResponsePart, and sends it back with chat.sendMessage. Repeat until the model returns text or you hit your own step limit (a small number like 3-5). Guard against infinite loops.

JSON output: set responseMimeType = "application/json" and a responseSchema (built with Schema.obj(...)) in the model's generationConfig so the model returns structured data you can parse without regex.

Protection: add Firebase App Check to the app (Play Integrity provider for release, debug provider for local builds) and enforce it for Firebase AI Logic in the console. Once enforced, requests without a valid token are blocked. The Gemini key never touches the device, so a decompiled APK cannot extract it.

Notes

  • The entry point is Firebase.ai(backend = GenerativeBackend.googleAI()). No Gemini API key string appears in your code.
  • generateContentStream returns a Flow<GenerateContentResponse>. Collect it inside viewModelScope so the flow is cancelled when the ViewModel is cleared. Always re-throw CancellationException.
  • startChat(history) keeps multi-turn context; send turns with sendMessage or sendMessageStream. Store your own history and persist it to Room. Trim or summarise old turns before the context window fills; check the current docs for the window size.
  • Function calling: build FunctionDeclaration objects and pass them as tools = listOf(Tool.functionDeclarations(...)) when you create the model. The response's functionCalls hold a name and an args map of JSON values. Run the function, send the result back as a FunctionResponsePart, and loop with a hard step limit.
  • JSON output: set responseMimeType and responseSchema in generationConfig when you create the model. Parse the text with kotlinx.serialization; never regex the output.
  • Install an App Check provider in the app (Play Integrity for release, debug for development) and enforce App Check for Firebase AI Logic in the console. Once enforced, requests from builds without App Check are blocked. Test a real Play-signed build, not just a debug APK.
  • Never put a Gemini or any provider API key in BuildConfig, local.properties, or a string resource. For Claude, OpenAI, or other providers, call your own backend that holds the key, enforces auth and rate limits, and streams back with server-sent events or a chunked HTTP response.
  • Model names and supported devices change frequently. Read the current Firebase AI Logic docs before shipping. Do not hardcode a versioned model id in a constant that survives a release.
  • Treat all model output as untrusted text. Validate and sanitise before rendering in Compose. Never execute model output as a command or SQL string.
  • For non-Google providers (Claude, OpenAI), do not call them from the app with a secret key. The app calls your backend; the backend calls the provider. Stream to the app with SSE or a chunked response read via OkHttp or Ktor.

Code example

This ViewModel collects a streaming generateContentStream into a StateFlow-backed UI state, handles cancellation, and shows the partial text. A Compose LaunchedEffect collects the state.

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.firebase.Firebase
import com.google.firebase.ai.ai
import com.google.firebase.ai.type.Content
import com.google.firebase.ai.type.GenerativeBackend
import com.google.firebase.ai.type.content
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.CancellationException
 
class ChatViewModel(modelName: String) : ViewModel() {
 
    // Pass the model name in from Remote Config; check the docs for current names.
    private val model = Firebase.ai(backend = GenerativeBackend.googleAI())
        .generativeModel(modelName)
 
    private val _ui = MutableStateFlow(ChatUi())
    val ui = _ui.asStateFlow()
 
    fun send(prompt: String) {
        viewModelScope.launch {
            _ui.update { it.copy(loading = true, error = null, reply = "") }
            try {
                val chat = model.startChat(history = _ui.value.history)
                chat.sendMessageStream(prompt).collect { resp ->
                    val chunk = resp.text ?: return@collect
                    _ui.update { s -> s.copy(reply = s.reply + chunk, loading = false) }
                }
                // Save both turns so the next startChat has the context.
                _ui.update { s ->
                    s.copy(history = s.history +
                        content(role = "user") { text(prompt) } +
                        content(role = "model") { text(s.reply) })
                }
            } catch (e: CancellationException) {
                throw e // let viewModelScope cancellation propagate
            } catch (e: Exception) {
                _ui.update { it.copy(loading = false, error = e.message) }
            }
        }
    }
}
 
data class ChatUi(
    val history: List<Content> = emptyList(),
    val reply: String = "",
    val loading: Boolean = false,
    val error: String? = null
)
  • viewModelScope.launch ties the Flow collection to the ViewModel lifecycle; when the VM is cleared the flow is cancelled automatically.
  • CancellationException is re-thrown so the coroutine framework can clean up; swallowing it leaves the flow in a half-collected state.
  • resp.text can be null for a chunk with no text parts; the ?: return@collect guard skips it.
  • history is a List<Content> with user and model turns; in production also persist it to Room and trim it.

Run the idea in plain Kotlin

class ChunkAccumulator {
  var text: String = ""
      private set
  var cancelled: Boolean = false

  fun append(chunk: String) {
      if (!cancelled) {
          text = text + chunk
      }
  }

  fun cancel() {
      cancelled = true
  }
}

fun main() {
  val acc = ChunkAccumulator()
  val chunks = listOf("Hello", ", ", "world", "!")

  println("--- Streaming simulation ---")
  for (chunk in chunks) {
      acc.append(chunk)
      println("After chunk: " + acc.text)
  }
  println("Final text: " + acc.text)

  println("")
  println("--- Cancellation test ---")
  val acc2 = ChunkAccumulator()
  acc2.append("Start")
  println("Before cancel: " + acc2.text)
  acc2.cancel()
  acc2.append(" - ignored")
  acc2.append(" - also ignored")
  println("After cancel: " + acc2.text)

  println("")
  println("--- Step-limit guard ---")
  var step = 0
  val maxSteps = 3
  var loop = true
  while (loop) {
      step = step + 1
      println("Function-call step " + step)
      if (step >= maxSteps) {
          loop = false
          println("Hit step limit, stopping")
      }
  }
}

In production

403 storm after a release without App Check
  • After a Play Store update, a significant portion of users saw a blank chat screen. Crash logs showed no exception; the UI just stayed in a loading spinner.
  • App Check metrics in the Firebase console showed a spike of unverified requests. A dependency refactor had dropped the Play Integrity provider setup, so the new build sent no valid App Check token while enforcement was on.
  • The team had tested only on debug builds where the debug App Check provider was active, so the issue was invisible in QA.
The fix
  • Re-added the Play Integrity provider installation and shipped a hotfix.
  • Added a release smoke test on a Play-signed build that makes one real AI call.
  • Showed a visible error and logged a non-fatal when the AI call fails, so the next incident shows up in crash reports instead of a silent spinner.
Context window overflow on long chat sessions
  • Users who chatted for many turns saw every new message fail: the request was rejected because the history exceeded the model's context window.
  • The ViewModel stored every Content in a MutableStateFlow and passed the full list to startChat on every new message.
  • No trimming or summarisation was in place; the list grew unbounded.
The fix
  • Capped the in-memory history to the last 15 turns and persisted older turns to Room.
  • Added a summarisation step: when the list exceeds the cap, the oldest 5 turns are replaced by a single summary Content generated by a second generateContent call.
  • Added a unit test that feeds 50 turns and asserts the list length stays under the cap.

Common mistakes

  • No Firebase App Check. Without enforced App Check, anyone who copies your Firebase config can call the model and spend your quota. Add App Check, enforce it, and test on a Play-signed build, not just a debug APK.
  • Swallowing CancellationException. Catching Exception without re-throwing CancellationException breaks structured cancellation: the coroutine keeps running after it was told to stop. Always re-throw CancellationException.
  • Unbounded chat history. Passing the full List<Content> to startChat on every turn eventually exceeds the context window and the request fails. Trim to the last N turns or summarise old turns before each call.
  • Waiting for the full reply. generateContent is a suspend function, so it does not block the main thread, but the user stares at a spinner until the whole answer is ready. Use generateContentStream or sendMessageStream for long answers.
  • Trusting model output as a command. Model text can contain SQL, shell commands, or HTML. Rendering it with Html.fromHtml or passing it to a database query is an injection vector. Validate, sanitise, and render with a safe markdown renderer.
  • Hardcoding a versioned model id. Model names and supported devices change frequently. A hardcoded id that is later deprecated breaks the app silently. Read the model name from a remote config or check the current docs before each release.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“How does Firebase AI Logic keep the Gemini API key off the device?”

“How do you render a streaming AI response in Jetpack Compose?”

“Explain the function-calling loop in Firebase AI Logic.”

“What do you do when the chat history exceeds the context window?”

Quiz

What does generateContentStream return in Firebase AI Logic?

App Check is enforced for Firebase AI Logic. What happens to a request from an old app version that has no App Check?

In a function-calling loop, what should you do when the model returns a FunctionCall?

Where should a Claude or OpenAI API key live in an Android app that calls a non-Google LLM?

0 of 4 answered

Mini task

15-minute exercise: wire a streaming chat into a Compose screen

  1. Add the Firebase AI Logic and App Check dependencies to build.gradle.kts (check the current docs; use the Firebase BoM). Install the debug App Check provider for local builds and Play Integrity for release.

  2. Create a ChatViewModel that holds a MutableStateFlow<ChatUi> with fields reply, loading, error, and history: List<Content>. Add a send(text: String) function that calls model.startChat(history).sendMessageStream(text) and collects the flow inside viewModelScope.launch.

  3. In the collection block, append each resp.text chunk to reply via _ui.update { }. Re-throw CancellationException. Catch other exceptions and set error.

  4. Create a ChatScreen Composable that collects ui with collectAsStateWithLifecycle. Show reply in a LazyColumn of Text items. Show a progress indicator when loading is true. Show error in a red Text when non-null.

  5. Add a TextField and a send button that calls viewModel.send(text) and clears the input. Keep the Job from launch and add a "Stop" button that cancels it.

  6. Test: type a long prompt, watch tokens appear one by one. Navigate away mid-stream and confirm the flow stops (log a line in the finally block). Re-enter the screen and confirm no crash.

Done condition: the screen shows partial text as it streams, the Stop button cancels the flow without a crash, and a failed call (for example, airplane mode) shows the error text instead of a blank screen.