AI foundations for app developers cheat sheet

Revise AI foundations for Android: model inference, kotlinx.serialization validation, AiBackend abstraction, temperature, and context window limits.

Key ideas

  1. A model is a static file of weights; the app loads it and runs a forward pass, never training or updating at runtime.
  2. LLMs generate text one token at a time, so latency grows with output length.
  3. Temperature divides logits before softmax; near 0 is greedy, higher values flatten the distribution and add randomness.
  4. Context window is the hard token limit per request (prompt + output); exceeding it causes errors or dropped context.
  5. Hallucination is inherent to next-token prediction; mitigate with retrieval, validation, and UI cues, not by hoping the model stops.
  6. Structured output must be validated in Kotlin with kotlinx.serialization; models can return malformed JSON or wrong types.
  7. API keys must live on a server; never put them in BuildConfig, a resource file, or any code shipped in the APK.
  8. On-device inference runs on CPU, GPU, or NPU; cloud inference sends the prompt to your own server over HTTPS.
  9. An AiBackend interface lets you swap on-device and cloud at runtime without touching Compose or ViewModel code.
  10. Latency and per-token cost decide whether a feature is viable; measure both in a staging build before shipping.

APIs at a glance

API or termUse it for
kotlinx.serializationParse and validate raw model JSON into a typed data class in Kotlin
@SerializableAnnotate a data class so kotlinx.serialization can decode model output into it
Json { ignoreUnknownKeys = true }Tolerate extra fields the model adds; missing fields and wrong types still throw
AiBackend interfaceAbstract on-device vs cloud inference so callers and UI stay unchanged
AiResult sealed interfaceModel result as Ok / Err so error paths are explicit and testable
Dispatchers.DefaultRun a forward pass off the main thread to avoid ANRs and jank
LiteRTOn-device model runtime on Android for CPU, GPU, or NPU inference
temperatureControl sampling randomness; use a low value for structured or factual tasks
context windowHard token limit per request; track count and truncate or summarise before sending
SerializationExceptionCatch malformed JSON or missing fields from model output; show a fallback UI

Snippets

Validate structured LLM output in Kotlin

@Serializable
data class SentimentResult(val label: String, val confidence: Double, val reasons: List<String>)
 
private val json = Json { ignoreUnknownKeys = true }
 
fun parseSentiment(raw: String): SentimentResult? = try {
    val r = json.decodeFromString<SentimentResult>(raw)
    if (r.confidence !in 0.0..1.0) return null
    if (r.label !in listOf("positive", "negative", "neutral")) return null
    if (r.reasons.isEmpty()) return null
    r
} catch (e: SerializationException) { null }

AiBackend interface for on-device vs cloud

sealed interface AiResult {
    data class Ok(val text: String) : AiResult
    data class Err(val msg: String) : AiResult
}
 
interface AiBackend { suspend fun complete(prompt: String): AiResult }
 
class CloudBackend(private val serverUrl: String) : AiBackend {
    override suspend fun complete(prompt: String): AiResult =
        try { AiResult.Ok("cloud result") } // call your backend here, never the provider directly
        catch (e: Exception) { AiResult.Err("Network error: " + e.message) }
}

Build a prompt with embedded JSON schema

fun buildPrompt(userQuery: String, context: List<String>): String {
    val ctx = context.joinToString("\n") { "- " + it }
    return "You are a product assistant. " +
        "Context:\n$ctx\n\n" +
        "User question: $userQuery\n\n" +
        "Respond ONLY with JSON: " +
        "{\"name\": string, \"reason\": string, \"confidence\": number}"
}

Rules of thumb

  • Never ship an API key in the APK: not in BuildConfig (even when read from local.properties), a string resource, or code.
  • Always validate model JSON with kotlinx.serialization and add range or enum checks the model cannot guarantee.
  • Prefer a low temperature for structured output and factual tasks; a high value makes broken JSON more likely.
  • Never run inference on the main thread; use Dispatchers.Default or the library's async API.
  • Prefer an AiBackend interface injected via Hilt so you can swap on-device and cloud without rewriting callers.
  • Never hard-code a cloud model name in app code; keep the choice on your backend so you avoid an app release to rename it.

Gotchas

  • Trusting model JSON without validation. The model can return valid JSON that violates your schema (wrong types, missing fields, out-of-range numbers). An uncaught SerializationException crashes the app. Fix: parse with kotlinx.serialization inside runCatching and show a fallback UI on failure.
  • Storing the API key in BuildConfig or a resource file. Any value in the APK can be extracted with tools like apktool, leading to quota abuse and billing spikes. Fix: the key lives only on your server; the app calls a backend endpoint that injects the key server-side.
  • Running inference on the main thread. A forward pass can be slow, especially on low-end devices, causing ANRs and jank. Fix: dispatch to Dispatchers.Default or use the library's async API.
  • Assuming hallucination can be eliminated. Hallucination is a property of next-token prediction; the model has no fact-checker. Fix: label AI output in the UI, add a human-review step for high-stakes actions, and validate against a known dataset.
  • Sending the full conversation history every cloud call. Context window size drives per-token cost and latency; exceeding it causes the API to reject the request or silently drop old messages. Fix: trim to the most recent turns or summarise older context on your server before forwarding.
  • Hard-coding a cloud model name in the APK. Providers retire and rename models; a name baked into the APK requires a full app release to change. Fix: keep the model choice on your backend and fetch it at runtime.

Quick interview answers

How do you guarantee structured output from an LLM?

You cannot guarantee it; the model can return malformed JSON, extra prose, or wrong types. Validate the response with kotlinx.serialization in Kotlin, add range and enum checks, retry once with a stricter prompt, and show a fallback UI on failure.

Where should the LLM API key live in an Android app?

The key must live only on your server, never in BuildConfig, a resource file, or any code shipped in the APK. The app calls your backend over HTTPS, and the backend injects the key when it talks to the model provider.

What is the context window and what happens when you exceed it?

The context window is the maximum number of tokens (prompt plus output) the model can handle in one request. Exceeding it causes the API to reject the request or your code to silently truncate old messages, so the user sees errors or the model forgets earlier instructions.

How do you choose between on-device and cloud inference?

On-device wins for low-latency, offline features like typing assist; cloud wins for long-form generation. Check the current docs for supported models and devices, verify free RAM and NPU availability, and plan a fallback (cloud or a simpler feature) for devices that cannot load the model.

What is temperature and when do you use a low versus high value?

Temperature divides the logits before softmax turns them into probabilities; near 0 is greedy (always pick the top token), higher values flatten the distribution and increase randomness. Use a low value for structured output and factual tasks, and a higher value is acceptable for creative tasks.

Why can't you eliminate hallucination from an LLM?

Hallucination is inherent to next-token prediction; the model scores and samples tokens without any fact-checking mechanism. Mitigate it with retrieval, output validation, confidence indicators in the UI, and a human-review step for high-stakes actions.

Go deeper