Shipping AI features cheat sheet

Revise shipping AI features: safetySettings, withTimeout, Flow streaming, Remote Config, eval sets, and fallbacks for Android.

Key ideas

  1. API keys must stay on the server; never put them in BuildConfig, local.properties, strings.xml, or any file shipped in the APK.
  2. Keep sensitive data (health, biometrics, precise location) on-device; check current docs for which models support on-device inference.
  3. Treat model output as untrusted data; gate every sensitive action (delete, transfer, post) behind an explicit user confirmation dialog.
  4. Use provider safetySettings AND your own local output filter; log blocked outputs so you can tune the filter over time.
  5. Stream tokens with Flow and wrap the call in withTimeout; always emit a cached or static fallback on failure or timeout.
  6. Store prompts and model names in Firebase Remote Config or server config, versioned and rolled out gradually; on-device models download and version separately from the APK.
  7. Build a fixed eval set of real inputs with expected properties; score prompt or model changes offline before release.
  8. Cap input tokens on the client (~4 chars per token) and rate-limit per user on the server to protect provider quotas.
  9. Add an in-app report button for offensive AI-generated content; Play's AI policy requires flagging without leaving the app.
  10. Monitor online metrics (thumbs up/down, retry rates, fallback rate, latency, token count) after every prompt or model update.

APIs at a glance

API or termUse it for
safetySettingsProvider-level safety filter in Firebase AI Logic; always pair with a local output check
withTimeoutHard limit on the whole AI call; on expiry the block is cancelled and you emit a fallback string
Flow<String>Stream AI tokens to the UI so the first character appears quickly instead of a blank screen
BuildConfigNever store API keys here; they ship in the APK and are extractable with jadx
Firebase Remote ConfigStore prompts, model IDs, and version numbers; percentage rollouts and rollback without a Play release (values are cached, so changes are not instant)
AiConfigExample data class holding version, modelId, systemPrompt, and temperature, with a local fallback
CancellationExceptionRe-throw in catch blocks so a cancelled collector does not emit a fallback string
TimeoutCancellationExceptionThrown by withTimeout; it subclasses CancellationException, so catch it first and emit a 'try again' message
Room / in-memory MapCache repeated prompts keyed by user id and a hash of the prompt; clear sensitive entries on sign-out
Per-user rate limitEnforce on the server with a budget alert; a client-side limit alone can be bypassed
EvalInput / EvalResultFixed test-set data classes for offline, reproducible evaluation of prompt or model changes
Play Data safety formMust reflect every data type collected or shared, including prompts and context sent to a third-party AI provider

Snippets

Output guard: flag content and gate sensitive actions (toy keyword list; pair it with the provider's safety settings)

data class AiRequest(
    val userPrompt: String,
    val triggersSensitiveAction: Boolean = false,
)
 
data class AiResponse(
    val text: String,
    val blocked: Boolean,
    val needsUserConfirm: Boolean, // UI must show a confirmation dialog
)
 
fun buildSafeResponse(raw: String, req: AiRequest): AiResponse {
    val lower = raw.lowercase()
    val flagged = lower.contains("harmful") || lower.contains("offensive")
    val needsConfirm = req.triggersSensitiveAction && !flagged
    return AiResponse(
        text = if (flagged) "I can't help with that." else raw,
        blocked = flagged,
        needsUserConfirm = needsConfirm,
    )
}

AI call with cache, rate limit, timeout, and fallback

import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.withTimeout
 
interface AiApi { fun stream(prompt: String, userId: String): Flow<String> } // your server proxy
interface AiCache { suspend fun get(userId: String, prompt: String): String? }
interface RateLimiter { fun allow(userId: String): Boolean }
 
private const val MAX_INPUT_CHARS = 2048 // rough cap, about 4 chars per token
private const val REQUEST_TIMEOUT_MS = 15_000L
 
class AiRepository(
    private val api: AiApi,
    private val cache: AiCache,
    private val rateLimiter: RateLimiter,
) {
    fun ask(userId: String, prompt: String): Flow<String> = flow {
        cache.get(userId, prompt)?.let { emit(it); return@flow }
        if (!rateLimiter.allow(userId)) { emit("Try again shortly."); return@flow }
        val capped = prompt.take(MAX_INPUT_CHARS)
        try {
            withTimeout(REQUEST_TIMEOUT_MS) {
                api.stream(capped, userId).collect { emit(it) }
            }
        } catch (e: TimeoutCancellationException) { // subclass: catch it first
            emit("Request timed out. Try again.")
        } catch (e: CancellationException) {
            throw e // the collector was cancelled: emit nothing
        } catch (e: Exception) {
            emit("AI unavailable. Try later.")
        }
    }
}

Offline eval runner with property-based checks

data class EvalInput(val prompt: String, val expectedProperty: String)
data class EvalResult(val input: EvalInput, val output: String, val passed: Boolean)
 
class MockAIService {
    fun generateResponse(input: String): String = "The weather is sunny"
}
 
class AIEvaluator(private val aiService: MockAIService) {
    fun runEvaluations(testSet: List<EvalInput>): List<EvalResult> =
        testSet.map {
            val output = aiService.generateResponse(it.prompt)
            val passed = output.contains(it.expectedProperty, ignoreCase = true)
            EvalResult(it, output, passed)
        }
}

Remote config with a local fallback

data class AiConfig(
    val version: Int, // log it so you know which prompt produced which result
    val modelId: String,
    val systemPrompt: String,
    val temperature: Double,
)
 
interface RemoteConfigProvider { suspend fun fetchConfig(): AiConfig? }
 
class AiConfigRepository(private val remoteConfig: RemoteConfigProvider) {
    private val fallbackConfig = AiConfig(
        version = 1,
        modelId = "default-model",
        systemPrompt = "You are a helpful assistant.",
        temperature = 0.7,
    )
 
    suspend fun getActiveConfig(): AiConfig =
        try {
            remoteConfig.fetchConfig() ?: fallbackConfig
        } catch (e: Exception) {
            fallbackConfig
        }
}

Rules of thumb

  • Prefer on-device inference for health, biometric, and precise-location data; check docs for supported models.
  • Never put API keys in BuildConfig, local.properties, or any file shipped in the APK; the app calls your backend.
  • Never let model output trigger a sensitive action without an explicit user confirmation dialog.
  • Prefer Flow streaming with withTimeout over a single blocking call so the UI never freezes.
  • Prefer property-based checks (contains, regex, LLM-as-judge) over exact string matching in evals.
  • Never hardcode model names or prompts in app code; use Remote Config or server config, versioned and rolled out gradually.

Gotchas

  • API key in BuildConfig or strings.xml. The key ships inside the APK and can be extracted with a decompiler like jadx, leading to unauthorized usage and cost spikes. Keep the key on the server; the app calls your backend, which proxies to the LLM provider.
  • No confirmation before a model-triggered action. Model output is untrusted text; a prompt injection can cause the app to delete data, send a message, or transfer money. Always gate sensitive actions behind a user tap.
  • No timeout on AI network calls. A slow server keeps the coroutine waiting and the user sees a frozen UI. Wrap the call in withTimeout and emit a fallback string on TimeoutCancellationException.
  • Relying only on the provider's safety filter. Provider filters miss edge cases and change between model versions. Add a local keyword or policy check and log blocked outputs so you can tune your own filter.
  • Hardcoding prompts or model IDs in app code. Every change requires a new Play Store release and users who update. Store prompts and model names in Firebase Remote Config or server config, version them, and roll out gradually.
  • No fallback when the AI call fails or the device lacks a model. The user sees a blank screen or a crash. Return a cached answer, a static message, or a 'try again' button; set a timeout on every call.

Quick interview answers

Where should API keys live in an Android AI app?

API keys must stay on the server, never in BuildConfig, local.properties, or any file shipped in the APK. The app calls your backend, which holds the key and proxies requests to the LLM provider.

How do you handle a slow or failed AI call on Android?

Stream tokens with Flow and wrap the coroutine in withTimeout so a slow server is cancelled. On timeout or any exception, emit a cached answer or a static fallback message so the user never sees a blank screen.

What is the right way to evaluate a prompt change before release?

Build a fixed eval set of real inputs with expected properties and run it offline, comparing the new prompt or model against a known baseline. Use property-based checks rather than exact string matches, and include latency and cost in the criteria; if you use LLM-as-a-judge, check its grades against human labels.

How do you protect against prompt injection in an Android AI feature?

Keyword checks like 'ignore previous' catch only lazy attacks, so treat them as a signal, not a defence. The real defence is limiting what model output can do and gating every sensitive action behind an explicit user confirmation dialog.

Why use Firebase Remote Config for prompts and model names instead of hardcoding them?

Hardcoding them in the APK means every change requires a new Play Store release. Remote Config lets you version configurations, roll out to a percentage of users first, and roll back without shipping a new build; changes apply when the app next fetches and activates the config.

What does Play's AI-generated content policy require from your app?

Users must be able to flag offensive AI-generated content without leaving the app, so add an in-app report button. The Data safety form must also list every data type collected or shared, including user prompts sent to a third-party AI provider.

Go deeper