How ML models and LLMs work for app developers
Why it matters
- Every AI feature in an Android app (text generation, image tagging, speech) is a model file run by an inference runtime. Knowing the input/output shape (tensors) and the latency budget prevents main-thread ANRs and battery drain.
- LLMs predict the next token from a context window. Understanding tokens, temperature, and context limits lets you size prompts, set timeouts, and explain why output quality drops after a certain length.
- Interviewers for senior Android roles ask how you would choose on-device vs cloud inference, how you validate model output in Kotlin, and how you handle hallucination in the UI. This lesson covers all three.
- Structured output (asking a model for JSON) still requires validation in
kotlinx.serializationbecause models can return malformed or schema-violating JSON. Skipping that step causesSerializationExceptioncrashes in production.
The simple explanation
- A model is a recipe book: a fixed file of numbers (weights) that maps an input to an output. You do not change the recipe at runtime; you feed it different ingredients (input tensors).
- An LLM is a word-guessing machine: it reads the text so far (context) and picks the next word (token) from a probability list. It does not "think"; it scores and samples.
- Temperature is the dice sharpness: low temperature means the machine almost always picks the top guess; high temperature makes the dice fairer, so rarer words get picked more often.
- Context window is the short-term memory: the model can only see a fixed number of tokens at once. Anything that does not fit is not seen at all.
- Hallucination is like a confident wrong answer on an exam: the model has no fact-checker. It produces a plausible-sounding token even when the underlying fact is absent.
A trained model is a file of weights (a large matrix of floating-point numbers). At inference time, an inference runtime (LiteRT on Android, or a server for cloud LLMs) loads that file and runs a forward pass: input tensor in, output tensor out. No training happens in the app.
An LLM is a special case. It predicts the next token, one token at a time. First a tokenizer turns your text into token IDs (numbers). A token is a chunk of text (a word, a sub-word, or a punctuation mark). The model scores every token in its vocabulary, then a sampling step (controlled by temperature) picks one. The picked token is appended to the context, and the loop repeats until a stop condition.
Key parameters every Android developer must know:
| Parameter | What it controls | Where to find values |
|---|---|---|
context window | Max tokens the model can see at once | check current docs per model |
temperature | Randomness of sampling | allowed range differs per API; 0 is close to greedy |
top-p | Sample only from the smallest set of top tokens whose probabilities add up to p | check API docs |
latency | Time to first token, then time per token | measure on your own devices and network |
cost per token | Billing unit for cloud APIs | check provider pricing |
On-device vs cloud is a trade-off across privacy, offline use, latency, model quality, app size, battery, and device coverage. See On-device vs cloud AI: how to choose for the decision matrix.
Structured output: you can ask a model to return JSON matching a schema, but the model can still produce invalid JSON or wrong field types. Always parse and validate in Kotlin with kotlinx.serialization. See Prompts, context and structured output for prompt patterns.
Hallucination is normal model behaviour, not a bug you can fully remove. Design the UI to make clear the text is AI-generated, add a human-review step for important actions, and validate outputs against known data before acting on them.
Notes
- A model is a static file of weights (many tensors of numbers). The app loads it and runs a forward pass; it does not train or update the model at runtime.
- Inputs and outputs are tensors (multi-dimensional arrays). An image is often a tensor of shape [1, H, W, C] (batch, height, width, channels); text for an LLM is a list of token IDs. On Android, LiteRT runs these models.
- An LLM generates text one token at a time. Each step: score the full vocabulary, sample one token, append it, repeat. This is why generation is sequential and why latency grows with output length.
- Temperature divides the logits (raw scores) before softmax turns them into probabilities. Temperature near 0 is greedy (always pick the top token). Higher values flatten the distribution and increase randomness.
- Context window is the maximum number of tokens (prompt plus output) the model can handle in one request. Text outside it is invisible. Check the current docs for the limit of each model you use.
- Hallucination is the model producing plausible but false text. It comes from how next-token prediction works; it is not a rare bug. Mitigate with retrieval, validation, and UI cues, not by hoping the model stops.
- Structured output (JSON from a model) must be validated in Kotlin. Use
kotlinx.serializationwith a data class and add range or enum checks the model cannot guarantee. - Never put an API key in
BuildConfig, a resource file, or any code shipped in the APK. The key must live on a server that the app calls over HTTPS. - On-device inference runs on the device's CPU, GPU or NPU. Check the current docs for supported models and devices; the list changes frequently.
- Latency and cost per token are key numbers that decide whether a feature is viable. Measure both in a staging build before shipping.
Code example
This Kotlin snippet shows the pattern for structured LLM output: define a @Serializable data class as the schema, parse the model's JSON string, and add validation the model cannot guarantee. It is the pattern you use in any Android feature that calls a cloud or on-device LLM.
// Structured LLM output: define schema, parse, validate in Kotlin
import kotlinx.serialization.SerializationException
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
@Serializable
data class SentimentResult(
val label: String,
val confidence: Double,
val reasons: List<String>
)
private val json = Json { ignoreUnknownKeys = true }
// The model returns a raw JSON string. You must validate it.
fun parseSentiment(rawJson: String): SentimentResult? {
return try {
val result = json.decodeFromString<SentimentResult>(rawJson)
// Checks the model cannot guarantee on its own
if (result.confidence < 0.0 || result.confidence > 1.0) return null
if (result.label !in listOf("positive", "negative", "neutral")) return null
if (result.reasons.isEmpty()) return null
result
} catch (e: SerializationException) {
null // malformed JSON or missing fields; caller shows a fallback UI
}
}
// Usage: call the model, get a String, parse it
// val raw = callLlmApi(prompt) // returns String from your server
// val result = parseSentiment(raw)
// if (result == null) showFallback() else render(result)@Serializable+kotlinx.serializationgives you a typed schema. The model is asked to produce JSON matching this shape, but it can still violate it.- The three
ifchecks after deserialization catch values the model can produce that are syntactically valid JSON but semantically wrong (confidence outside 0-1, unknown label, empty list). - Returning
nullon any failure lets the caller show a fallback UI instead of crashing. Never let aSerializationExceptionreach the UI uncaught.
Run the idea in plain Kotlin
import kotlin.math.exp
import kotlin.math.roundToInt
data class Candidate(val token: String, val logit: Double)
// Softmax with temperature: divide each logit by T, then exp and normalise.
fun probabilities(candidates: List<Candidate>, temperature: Double): List<Double> {
val scaled = candidates.map { it.logit / temperature }
val maxScaled = scaled.maxOrNull() ?: 0.0
val exps = scaled.map { exp(it - maxScaled) }
val total = exps.sum()
return exps.map { it / total }
}
fun main() {
// A tiny pretend model: after "hello" it scores three next tokens.
val candidates = listOf(
Candidate("world", 3.0),
Candidate("there", 2.0),
Candidate("again", 1.0)
)
for (t in listOf(0.2, 1.0, 2.0)) {
println("Temperature " + t)
val probs = probabilities(candidates, t)
for (i in candidates.indices) {
val percent = (probs[i] * 1000).roundToInt() / 10.0
println(" " + candidates[i].token + ": " + percent + "%")
}
}
println("Greedy pick (temperature near 0): " + candidates.maxByOrNull { it.logit }!!.token)
}In production
- Users reported the chat screen crashing with a
SerializationExceptionafter the model returned a JSON string with a missingconfidencefield. - The team had asked the model to return JSON but only called
decodeFromStringwith notry/catchand no fallback. - Crashlytics showed a spike in fatal exceptions on the chat tab.
- Wrapped parsing in a
try/catchand returnednullon any failure, matching theparseSentimentpattern above. - Added range and enum checks after deserialization so a syntactically valid but semantically wrong payload (e.g.
confidence = 1.7) was rejected. - The UI now shows a "retry" button when parsing returns
nullinstead of crashing.
- Users on lower-end devices reported the image-tagging screen freezing.
- The team was calling the model's
run()method directly inside aLaunchedEffectin Compose, blocking the main thread. - ANR reports appeared in Play Console.
- Moved inference into
withContext(Dispatchers.Default)so the UI collects the result on the main thread. - Showed a loading state while inference runs and a fallback if it fails.
- Used Android Studio Profiler to confirm the inference call no longer ran on the main thread.
Common mistakes
- Trusting model JSON without validation. The model can return valid JSON that violates your schema (wrong types, missing fields, out-of-range numbers). Always parse with
kotlinx.serializationand add explicit checks. An uncaughtSerializationExceptioncrashes the app. - Putting the API key in BuildConfig or a resource file. Any value in the APK can be extracted with
apktool. The key must live on a server; the app calls a backend endpoint that injects the key server-side. A leaked key leads to quota abuse and billing spikes. - Running inference on the main thread. A forward pass can be slow, especially on low-end devices. Doing it on the main thread causes ANRs and jank. Run it on a background dispatcher such as
Dispatchers.Default, or use the library's async API. - Assuming the model will never hallucinate. Hallucination is a property of next-token prediction. The model has no fact-checker. Label AI output in the UI, add a human-review step for high-stakes actions, and validate outputs against a known dataset before acting.
- Hard-coding a cloud model name in app code. Providers retire and rename models. If the name lives in the APK, you need an app release to change it. Keep the model choice on your backend.
- Ignoring context-window limits. If the prompt plus history exceeds the context window, the API may reject the request or your code (or library) may cut old messages. Either way the user sees errors or the model "forgets" earlier instructions. Track token count and truncate or summarise before sending.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is a token in an LLM, and how does the model generate text?”
“What does temperature do, and when would you set it to zero?”
“How do you handle structured output from an LLM in an Android app?”
“How do you decide between on-device and cloud inference for an Android feature?”
Quiz
What is the basic unit an LLM predicts at each step?
What happens when temperature is set to zero in an LLM?
Why must you validate JSON returned by an LLM in Kotlin even if you asked for a specific schema?
Where should an LLM API key be stored for an Android app?
0 of 4 answered
Mini task
15-minute exercise: simulate next-token prediction in a Kotlin script
-
Open a new Kotlin file in Android Studio (or a Kotlin script in IntelliJ). Create a
data class Candidate(val token: String, val logit: Double)at the top level. -
Create a
listOfwith threeCandidateentries:("world", 3.0),("there", 2.0),("again", 1.0). This is your tiny "model" for the context"hello". -
Write a function
fun probabilities(candidates: List<Candidate>, temperature: Double): List<Double>that divides each logit by the temperature, applieskotlin.math.exp, and divides each value by the sum (this is softmax). -
In
fun main(), callprobabilitieswith temperatures0.2,1.0and2.0and print the token and its probability percentage using string concatenation with+(no string templates). -
Add a second list of candidates for the context
"I like":("coffee", 4.0),("tea", 2.0),("code", 3.0). Run the same three temperatures and compare the output. -
Observe: at low temperature the top token dominates; at high temperature the probabilities flatten. Note which token wins in each case.
Done condition: the script prints three temperatures for each of the two contexts, showing that the distribution changes with temperature, and the top token at 0.2 has a higher percentage than at 2.0.