On-device LLMs: Gemini Nano and LiteRT-LM
Why it matters
- On-device LLMs let you ship summarisation, proofreading and chat features without a network round-trip, which matters for offline UX and privacy-sensitive apps.
- Interviewers at product companies ask how you decide between a cloud LLM and an on-device one, and what happens when the device cannot run the model.
- The MediaPipe LLM Inference API (tasks-genai, .task files) is deprecated; knowing that LiteRT-LM with .litertlm files is the replacement shows you track the current stack.
- Getting the model-download, feature-check and accelerator-fallback order wrong is the most common cause of crashes and ANRs in on-device AI apps.
The simple explanation
- An on-device LLM is like a small expert sitting inside the phone, not in a data centre.
- The model file is the expert's brain; it must be downloaded before the expert can work.
- The feature check is asking the phone: "Do you have enough RAM and a compatible chip for this expert?"
- The accelerator fallback is like the expert trying a fast computer first, then a slower one, then a pencil.
- Quotas are a usage limit per app, so one app cannot hog the shared model.
Two paths run LLMs on Android today. ML Kit GenAI (dependency com.google.mlkit:genai-prompt plus feature modules) exposes Gemini Nano through Android AICore. You call a feature API (summarisation, proofreading, rewriting, image description) or the lower-level Prompt API. Before any call you must (1) check feature status, (2) trigger model download, (3) wait for the model to be ready. No background execution is allowed; usage quotas apply. LiteRT-LM (.litertlm model files) is the successor to the deprecated MediaPipe LLM Inference API (tasks-genai, .task files). It is built on LiteRT (the new name for TensorFlow Lite). In Kotlin you create an Engine from an EngineConfig (model path plus a backend: Backend.CPU(), Backend.GPU() or Backend.NPU(...)), call initialize(), then open a Conversation and send messages. You ship or download the model yourself, and there is no platform quota.
| Concern | ML Kit GenAI (Gemini Nano) | LiteRT-LM |
|---|---|---|
| Model file | Managed by AICore | .litertlm you ship or download |
| Entry point | Feature APIs / Generation.getClient() | Engine + Conversation |
| Background | Not allowed | You control the thread |
| Quotas | Enforced by AICore per app | None; you manage battery and heat |
| Hardware | AICore picks it | You pick a backend; retry on CPU if init fails |
LiteRT-LM model files are large, so download them after install (Play Asset Delivery, Play for On-device AI, or WorkManager) instead of bundling them in the base module. Engine initialization is slow: do it off the main thread, before the user needs it. For Gemini Nano, the Prompt API has an optional warmup(). Measure on real low-end devices. Check the current docs for supported models and devices; the list changes frequently.
Notes
- ML Kit GenAI runs Gemini Nano through Android AICore; call
checkStatus()(UNAVAILABLE,DOWNLOADABLE,DOWNLOADING,AVAILABLE) and calldownload()if needed before the first inference. Inference runs only while your app is in the foreground. - The lower-level entry point is the Prompt API in
com.google.mlkit:genai-prompt(Generation.getClient(), thengenerateContentorgenerateContentStream). The feature APIs (summarisation, proofreading, rewriting, image description) are higher-level and task-specific. - The Prompt API's input must fit the model's context window (the docs say under about 4000 tokens), and it does not run on devices with an unlocked bootloader.
- AICore enforces an inference quota per app. Hitting it makes calls fail with an error. Surface a user-facing message and back off.
- The MediaPipe LLM Inference API (
tasks-genai,.taskmodel files) is deprecated / maintenance-only. New on-device LLM work should use LiteRT-LM with.litertlmfiles. - LiteRT-LM's Kotlin API:
Engine(EngineConfig(modelPath = ..., backend = Backend.GPU())),engine.initialize(),engine.createConversation(), thensendMessageorsendMessageAsync(aFlowof chunks). Close the conversation and engine when done. - GPU and NPU backends depend on the device (GPU also needs native library entries in the manifest, per the LiteRT-LM docs). If
initialize()fails, recreate the engine withBackend.CPU(). - Large model files must be downloaded after install (Play Asset Delivery, Play for On-device AI, or
WorkManager). Bundling a multi-gigabyte model in the base APK will fail Play size limits. - Run LiteRT-LM initialization and inference off the main thread (
Dispatchers.Defaultor a dedicated dispatcher). Stream output so the first words appear quickly. - Never put an API key in app code or
BuildConfig. If a cloud fallback is needed, the key stays on your server and the app calls your backend. - Check the current docs for the list of supported models and devices; it changes every few months. Hard-coding a device list or a model version in your codebase will go stale.
Code example
This Kotlin snippet shows a repository that wraps the ML Kit GenAI Prompt API flow from the official docs: status check, model download, generation, and a graceful "unavailable" result the UI can turn into a cloud fallback.
// OnDeviceLlmRepository.kt
import com.google.mlkit.genai.common.DownloadStatus
import com.google.mlkit.genai.common.FeatureStatus
import com.google.mlkit.genai.prompt.Generation
data class LlmResult(val text: String, val source: String)
class OnDeviceLlmRepository {
private val model = Generation.getClient()
// 1. Is Gemini Nano usable on this device right now? Download if needed.
suspend fun ensureReady(): Boolean =
when (model.checkStatus()) {
FeatureStatus.AVAILABLE -> true
FeatureStatus.DOWNLOADABLE -> {
var ok = false
model.download().collect { status ->
if (status is DownloadStatus.DownloadCompleted) ok = true
if (status is DownloadStatus.DownloadFailed) ok = false
}
ok
}
else -> false // UNAVAILABLE or still DOWNLOADING
}
// 2. Generate on-device, or tell the UI to use the cloud path.
// Call only while the app is in the foreground.
suspend fun generate(prompt: String): LlmResult {
if (!ensureReady()) return LlmResult("", "unavailable")
val response = model.generateContent(prompt)
return LlmResult(response.candidates.first().text ?: "", "on-device")
}
// 3. Free resources when the feature is closed (e.g. ViewModel.onCleared).
fun close() = model.close()
}If you bring your own model instead, the LiteRT-LM Kotlin flow looks like this (from the LiteRT-LM docs):
import com.google.ai.edge.litertlm.Backend
import com.google.ai.edge.litertlm.Engine
import com.google.ai.edge.litertlm.EngineConfig
// Off the main thread; initialize() is slow
val engine = Engine(
EngineConfig(
modelPath = modelFile.path, // a downloaded .litertlm file
backend = Backend.GPU(), // retry with Backend.CPU() if this fails
cacheDir = context.cacheDir.path // speeds up later loads
)
)
engine.initialize()
engine.createConversation().use { conversation ->
conversation.sendMessageAsync("Summarise this note: ...")
.collect { chunk -> print(chunk) } // stream chunks to the UI
}
engine.close()ensureReady()maps the fourFeatureStatusvalues to a yes/no. In a real app you also exposeDownloadProgressevents so the UI can show progress.checkStatus(),download()andgenerateContent()are suspend orFlowAPIs, so the main thread does not block while you wait. UsegenerateContentStreamto show tokens as they arrive.- The Prompt API also has an optional
warmup()you can call when the screen opens, to make the first request faster. - The
"unavailable"result lets the UI layer decide whether to show a cloud fallback or a "not supported on this device" message. For LiteRT-LM, close the conversation and engine (both areAutoCloseable).
Run the idea in plain Kotlin
class Accelerator(val name: String, val available: Boolean)
class AcceleratorChain(private val accelerators: List<Accelerator>) {
fun pick(): String {
for (acc in accelerators) {
if (acc.available) return acc.name
}
return "none"
}
}
class ModelAvailability(val supported: Boolean, val downloaded: Boolean) {
fun canRun(): Boolean = supported && downloaded
}
fun main() {
val chain = AcceleratorChain(
listOf(
Accelerator("NPU", false),
Accelerator("GPU", true),
Accelerator("CPU", true)
)
)
val picked = chain.pick()
println("Chosen accelerator: " + picked)
val model = ModelAvailability(supported = true, downloaded = false)
println("Can run before download: " + model.canRun())
val model2 = ModelAvailability(supported = true, downloaded = true)
println("Can run after download: " + model2.canRun())
val model3 = ModelAvailability(supported = false, downloaded = true)
println("Can run on unsupported device: " + model3.canRun())
val cpuOnly = AcceleratorChain(
listOf(
Accelerator("NPU", false),
Accelerator("GPU", false),
Accelerator("CPU", true)
)
)
println("Low-end device picks: " + cpuOnly.pick())
val noAccel = AcceleratorChain(
listOf(
Accelerator("NPU", false),
Accelerator("GPU", false),
Accelerator("CPU", false)
)
)
println("No accelerator available: " + noAccel.pick())
}In production
- Users on mid-range devices reported a freeze the first time they opened the chat screen.
- ANR traces showed the main thread blocked inside LiteRT-LM
engine.initialize(). - The team created and initialized the engine lazily on the first send, on the main thread.
- Initialized the engine on
Dispatchers.Defaultwhen the chat screen opens, with a "preparing model" state. - Moved all inference into a
Repositorythat exposes aFlow, collected in the ViewModel. - Streamed the reply with
sendMessageAsyncso the first words appear quickly.
- A spike in crashes appeared after a release that added the summarisation feature.
- Stack traces showed the GenAI call failing on devices where Gemini Nano was not available.
- The team had not called the feature-status check before invoking the feature API.
- Wrapped every GenAI call behind an
ensureReady()check that callscheckStatus()first. - Triggered
download()when the user first opens the feature, with a progress UI fromDownloadStatusevents. - Added a UI fallback: when the model is unavailable, the screen shows a message and offers a cloud-based alternative.
Common mistakes
- Calling the GenAI feature API without a feature-status check. On devices without Gemini Nano, or before the model is downloaded, the call fails. Always call
checkStatus()and trigger the download before the first inference. - Bundling a multi-gigabyte .litertlm file in the base APK. Play size limits reject the upload, and users on metered connections cannot install the app. Use Play Asset Delivery, Play for On-device AI, or a
WorkManagerdownload after install. - Initializing or running LiteRT-LM on the main thread. Engine setup and generation can take seconds, causing an ANR. Use
Dispatchers.Defaultor a dedicated dispatcher and expose results through aFlow. - Assuming GPU or NPU always works. Backend support depends on the device. If you hard-code
Backend.NPU(...)orBackend.GPU()without a fallback, the feature dies on devices that lack it. Catch theinitialize()failure and retry withBackend.CPU(). - Putting a cloud API key in BuildConfig or a string resource. The key is extractable from the APK. If a cloud fallback is needed, the key must stay on your server and the app calls your own backend.
- Ignoring usage quotas. AICore enforces an inference quota per app. Hitting it returns an error. Surface a user-facing message and back off rather than retrying in a tight loop.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“How do you decide between a cloud LLM and an on-device LLM in an Android app?”
“What is the correct order of operations before calling the ML Kit GenAI Prompt API?”
“Why is the MediaPipe LLM Inference API deprecated and what replaces it?”
“How do you handle a device where the GPU or NPU backend does not work for LiteRT-LM?”
Quiz
What replaces the deprecated MediaPipe LLM Inference API (tasks-genai, .task files) for on-device LLMs on Android?
Where should on-device LLM inference run in an Android app?
How should a multi-gigabyte .litertlm model be distributed to users?
What is a sound backend strategy for LiteRT-LM on Android?
0 of 4 answered
Mini task
15-minute exercise: build a model-availability gate
-
Create a new Kotlin file
ModelGate.ktin your project. Define a sealed interfaceGateStatewith three states:Checking,Ready,Unavailable(reason: String). -
Add a suspend function
checkAndDownload(): GateStatethat simulates the real flow: first check a boolean flag (stand-in forcheckStatus()), then simulate a 2-second download delay withdelay(), then returnReady. If the flag is false, returnUnavailable("Device not supported"). -
In a
ViewModel, expose aStateFlow<GateState>that starts asChecking, callscheckAndDownload()inviewModelScope, and emits the result. -
In a Compose screen, collect the
StateFlowand render: a progress indicator forChecking, a "Start chat" button forReady, and a message with the reason forUnavailable. -
Add a second boolean flag
modelDownloadedthat starts asfalse. TheReadystate must require both the feature check and the download to be true. If the download fails (simulate with a random chance), emitUnavailable("Download failed").
Done condition: The screen shows the progress indicator, then either the chat button or the failure message. Toggling the two booleans in a debug overlay switches between the three UI states. No inference call is made until the state is Ready.