Cloud AI in the app cheat sheet
Key ideas
- Firebase AI Logic entry point is
Firebase.ai(backend = GenerativeBackend.googleAI()); no Gemini API key string appears in your code. generateContentStreamreturns aFlow<GenerateContentResponse>; collect it insideviewModelScopeso cancellation is automatic.- For non-Google providers (Claude, OpenAI) the app calls your own backend; the backend holds the key, enforces auth and rate limits, and streams SSE.
- Function calling: pass
FunctionDeclarationobjects viatools, readfunctionCallsfrom the response, run the tool, send back aFunctionResponsePart, and cap iterations. - The model has no memory between calls;
startChat(history)wraps aList<Content>in memory only. Persist history in Room and trim before each call. - Treat all model output as untrusted text. Validate and sanitise before rendering in Compose; never execute it as a command or SQL string.
- Install and enforce Firebase App Check (Play Integrity for release, debug for development) so only your real app can call Firebase AI Logic.
- Set
responseMimeTypeandresponseSchemaingenerationConfigfor JSON output; parse with kotlinx.serialization, never regex. - A
FunctionResponsePartmust echo the original call'snameso the model can match the result to the request. - Put the system prompt in
systemInstructionon the model, not in the history, so trimming never drops it.
APIs at a glance
| API or term | Use it for |
|---|---|
Firebase.ai(backend = GenerativeBackend.googleAI()) | Create the Firebase AI Logic client; no API key string in app code |
generateContentStream | Stream a single-prompt reply as Flow<GenerateContentResponse> |
startChat(history) / sendMessageStream | Multi-turn chat with in-memory context; stream each turn |
FunctionDeclaration / Tool.functionDeclarations | Declare tools the model may call; pass via tools on the model |
FunctionCallPart / FunctionResponsePart | Read the model's tool call and send the result back with the same name |
generationConfig (responseMimeType, responseSchema) | Constrain model output to JSON; parse with kotlinx.serialization |
collectAsStateWithLifecycle() | Observe a StateFlow in Compose; stops when the screen is not visible |
viewModelScope.launch | Collect streams so they cancel when the ViewModel is cleared |
CancellationException | Always re-throw in catch blocks so the coroutine framework can clean up |
systemInstruction | Set the system prompt on the model so history trimming never removes it |
| Firebase App Check (Play Integrity / debug) | Enforce in the console so only your signed app can call Firebase AI Logic |
SSE (data: lines, an end marker such as [DONE]) | Read a backend-streamed LLM response with OkHttp on Dispatchers.IO; also stop when readLine() returns null |
Snippets
Stream a chat turn in the ViewModel (Firebase AI Logic)
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.CancellationException
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
data class ChatUi(
val history: List<Content> = emptyList(),
val reply: String = "",
val loading: Boolean = false,
val error: String? = null
)
class ChatViewModel(modelName: String) : ViewModel() { // name from Remote Config
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 // chunk with no text
_ui.update { s -> s.copy(reply = s.reply + chunk, loading = false) }
}
_ui.update { s ->
s.copy(history = s.history +
content(role = "user") { text(prompt) } +
content(role = "model") { text(s.reply) })
}
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
_ui.update { it.copy(loading = false, error = e.message) }
}
}
}
}Read SSE from your backend with OkHttp
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.IOException
// The app calls YOUR backend; the backend holds the provider key.
fun streamFromBackend(client: OkHttpClient, request: Request): Flow<String> = flow {
client.newCall(request).execute().use { resp ->
if (!resp.isSuccessful) throw IOException("HTTP ${resp.code}")
val reader = resp.body?.byteStream()?.bufferedReader()
?: throw IOException("empty body")
var line = reader.readLine()
while (line != null) { // null means the server closed the stream
currentCoroutineContext().ensureActive()
if (line.startsWith("data: ")) {
val chunk = line.removePrefix("data: ").trim()
if (chunk == "[DONE]") break // end marker agreed with your backend
emit(chunk)
}
line = reader.readLine()
}
}
}.flowOn(Dispatchers.IO) // readLine() blocksFunction-calling loop with a step cap
import android.util.Log
import com.google.firebase.ai.GenerativeModel
import com.google.firebase.ai.type.FunctionCallPart
import com.google.firebase.ai.type.FunctionResponsePart
import com.google.firebase.ai.type.content
import kotlinx.serialization.json.JsonObject
// model was created with tools = listOf(Tool.functionDeclarations(...))
suspend fun ask(
model: GenerativeModel,
question: String,
runTool: suspend (FunctionCallPart) -> JsonObject // validates args like user input
): String? {
val chat = model.startChat()
var response = chat.sendMessage(question)
val maxSteps = 5
var step = 0
while (response.functionCalls.isNotEmpty() && step < maxSteps) {
step++
val results = response.functionCalls.map { FunctionResponsePart(it.name, runTool(it)) }
response = chat.sendMessage(content { results.forEach { part(it) } })
}
if (response.functionCalls.isNotEmpty()) {
Log.w("AI", "Function-calling loop hit the step cap")
return null // show a fallback message
}
return response.text
}Observe the stream in Compose with lifecycle awareness
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.lifecycle.compose.collectAsStateWithLifecycle
@Composable
fun ChatScreen(vm: ChatViewModel) {
val state by vm.ui.collectAsStateWithLifecycle()
Column {
if (state.loading) CircularProgressIndicator()
Text(text = state.reply) // partial text, re-renders per chunk
state.error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
}
}Rules of thumb
- Prefer
generateContentStreamorsendMessageStreamovergenerateContentso the user sees text appear token by token. - Never put a provider API key in
BuildConfig,local.properties,res/raw, or any string resource; keep it on the backend server. - Always re-throw
CancellationExceptionin catch blocks; swallowing it stops the framework cleaning up and can leak the upstream HTTP connection. - Prefer a ViewModel-owned
List<ChatTurn>as the single source of truth; pass a freshstartChat(trimmed)each call instead of relying on theChatobject's internal history. - Never render raw model output with
Html.fromHtml; use a sanitised markdown renderer that escapes HTML. - Prefer reading the model name from Remote Config and checking the current docs for context-window sizes rather than hardcoding a versioned constant.
Gotchas
- Swallowing CancellationException. The framework cannot clean up, the flow is left half-collected, and the upstream HTTP connection can leak. Fix: add
catch (e: CancellationException) { throw e }before the genericcatch. - Unbounded chat history. Passing the full
List<Content>every turn eventually exceeds the context window and the request fails. Fix: trim to the last N turns or summarise old turns before each call. - No Firebase App Check enforced. Anyone who copies your Firebase config can call the model and burn your quota. Fix: install App Check, enforce it in the console, and test on a Play-signed build.
- No step cap on the function-calling loop. A model that keeps requesting a tool loops until the provider rate-limits or the user's quota is exhausted. Fix: wrap the loop in
while (step < maxSteps)and log when the cap is hit. - Writing streamed text to a plain var instead of StateFlow. Compose never recomposes because it cannot observe a plain variable. Fix: accumulate into a
MutableStateFlowand read it withcollectAsStateWithLifecycle(). - Hardcoding a versioned model id. Model names and supported devices change frequently, and an id baked into a release cannot be changed without shipping an update. Fix: read the model name from Remote Config and check the current docs before each release.
Quick interview answers
How do you stream a Gemini reply into a Compose UI without blocking the main thread?
Call generateContentStream (or sendMessageStream) which returns a Flow<GenerateContentResponse>, and collect it inside viewModelScope.launch. In the Composable, observe the resulting StateFlow with collectAsStateWithLifecycle() so the UI recomposes on every chunk and stops observing when the screen is not visible.
How do you call Claude or OpenAI from an Android app without exposing the API key?
The app calls your own backend server, which holds the secret key, enforces per-user auth and rate limits, and calls the provider. The backend streams the response back to the app as server-sent events or a chunked HTTP body, read with OkHttp on Dispatchers.IO.
What is the function-calling loop in Firebase AI Logic and how do you prevent it from running forever?
Send a message, check response.functionCalls, execute each tool, send the results back as FunctionResponsePart objects, and repeat. Cap the loop with a hard step limit (for example 5 iterations) and log a warning when the cap is hit so you can debug wrong-tool selection.
How do you manage chat history and context-window limits across process death?
Keep the authoritative history in a StateFlow<List<ChatTurn>> in the ViewModel and mirror every turn to Room. On ViewModel creation, reload from Room, trim to a token budget (roughly chars / 4), and pass the trimmed list to a fresh startChat call.
Why must you re-throw CancellationException when collecting a stream in a ViewModel?
Swallowing it prevents the coroutine framework from cleaning up, which leaves the flow half-collected and can leak the upstream HTTP connection. Always add catch (e: CancellationException) { throw e } before any generic catch (e: Exception) block.
How do you protect a Firebase AI Logic integration from quota abuse?
Install a Firebase App Check provider (Play Integrity for release, debug for development) and enforce App Check for Firebase AI Logic in the Firebase console. Once enforced, requests from builds without a valid App Check token are blocked; test with a real Play-signed build, not just a debug APK.