Summarize, classify, and rewrite on-device with ML Kit GenAI, and what actually breaks when you ship it.
A server-free summarizer sounds like a free lunch: no per-call cost, no network dependency, and user text that never leaves the phone. It is also a feature whose availability you do not control, whose model arrives as a separate download, and whose runtime budget is set by an OS service rather than your code. Most of the production pain comes from treating it like a library call instead of what it is: a capability negotiated with the platform at runtime.
This post walks through the shape I would use for a production feature built on Gemini Nano through ML Kit GenAI: how to decide whether the device can do it, which API to call for which job, how to model the download, when and how to fall back to a server, and how to measure the thing honestly. Code is Kotlin with coroutines and Flow. API names and artifact versions were checked against Google’s docs at the time of writing, and several of these APIs are beta, so confirm them against the current reference before you copy anything.
1. Device support and availability check
Start from an uncomfortable fact: there is no Build.VERSION.SDK_INT check that tells you whether Gemini Nano will run. The ML Kit GenAI APIs require Android API 26 or higher, they do not support devices with an unlocked bootloader, and they depend on the AICore system service and a Gemini Nano model that must be present on the device. Support also varies by chipset family and by which model generation a device ships. Google's docs say the Prompt API performs best on the Pixel 10 series, and that the list of devices behind the task-specific APIs (summarization, rewriting, and so on) differs from the Prompt API list.
So the only trustworthy signal is asking the feature itself. Every ML Kit GenAI client exposes a status check that returns one of four values: checkFeatureStatus() on the task clients (a ListenableFuture<Integer>), and a suspending checkStatus() on the Prompt API's GenerativeModel.
The diagram says checkFeatureStatus(). On the Prompt API, read that as checkStatus(); the four outcomes are identical.
Wrap the raw integer status and the exceptions into a type your UI can switch on exhaustively. I do this once, generically, and reuse it for every client:
sealed interface Availability { data object Ready : Availability data object NeedsDownload : Availability data object Downloading : Availability data class Unsupported(val cause: Throwable? = null) : Availability } suspend fun resolveAvailability(check: suspend () -> Int): Availability = try { when (check()) { FeatureStatus.AVAILABLE -> Availability.Ready FeatureStatus.DOWNLOADABLE -> Availability.NeedsDownload FeatureStatus.DOWNLOADING -> Availability.Downloading else -> Availability.Unsupported() // UNAVAILABLE and anything added later } } catch (e: CancellationException) { throw e // never swallow cancellation } catch (e: GenAiException) { Availability.Unsupported(e) } // Task clients return a ListenableFuture. await() comes from kotlinx-coroutines-guava. val availability = resolveAvailability { summarizer.checkFeatureStatus().await() } // The Prompt API's GenerativeModel exposes a suspending checkStatus() instead. val nanoAvailability = resolveAvailability { model.checkStatus() } Two details matter here. First, the else branch is deliberate: if a future library version adds a status, you degrade to "unsupported" rather than crash. Second, the status call itself can throw. Google documents setup failures such as a binding failure to AICore and a "feature not found" error when AICore has not yet fetched its configuration, which is common right after a device is set up or reset. Both surface as exceptions from the check, not as a clean UNAVAILABLE, so a bare checkFeatureStatus().await() on a fresh phone can crash your screen.
Failure modes at this layer
- Caching
AVAILABLEin SharedPreferences. Status can regress after a system update, an AICore change, or a storage cleanup. Re-derive it per session, and again at feature entry if the session is long. - Checking once at app start. On a just-unboxed phone the answer at minute one and minute thirty can differ. Check lazily, when the user reaches the feature.
- Hiding the feature permanently on the first
Unsupported. The "configuration not downloaded yet" case resolves itself, sometimes within hours. Treat it as "not yet" with a retry on next entry, not "never". - Gating on a device allow-list you maintain yourself. It rots within a release cycle. Use the runtime check, and use your own list only for analytics.
2. ML Kit GenAI APIs
ML Kit exposes Gemini Nano through task-specific clients, plus a free-form prompt client. Pick the narrowest tool that fits.
The task APIs are not just thin wrappers. Google describes each as the shared base model plus a task-specific LoRA adapter, tuned inference parameters, and an evaluation pipeline. That is why you should prefer them over a hand-rolled prompt when one exists. The Prompt API is the escape hatch for work that has no dedicated client, and for us that means classification.
Artifact coordinates at the time of writing, all marked beta (no SLA, breaking changes possible):
dependencies { implementation("com.google.mlkit:genai-summarization:1.0.0-beta1") implementation("com.google.mlkit:genai-rewriting:1.0.0-beta1") implementation("com.google.mlkit:genai-prompt:1.0.0-beta5") implementation("org.jetbrains.kotlinx:kotlinx-coroutines-guava:1.11.0") // await() on ListenableFuture implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.11.0") // see the known issue below } Check Google’s known-issues page before you pin these. genai-prompt 1.0.0-beta5 (released October 26, 2026) is newer than the beta4 this article was first written against, and the request DSL in the classifier below should be re-checked against it. The known-issues page lists two problems for earlier builds: in beta3 and beta4, download() throws NoSuchMethodError when the download completes or is cancelled if the app resolves kotlinx-coroutines to 1.10.x or earlier, and in beta3, checkStatus() threw an unhandled GenAiException on non-Pixel devices (fixed in beta4). Google's stated workaround for the first is to explicitly pin kotlinx-coroutines-android to 1.11.0 or newer, which is why it appears above. What matters is the version your app resolves, not the version of any single artifact, so confirm it with ./gradlew :app:dependencies. I did not find a statement that beta5 fixes the download() problem, so keep the pin until Google says otherwise.
Summarize
The summarizer takes an input type (article or conversation) and an output type of one, two, or three bullets. Documented limits are the part that bites: input must stay under roughly 4,000 tokens, article input must exceed 400 characters, and supported languages are English, Japanese, and Korean. A guard in front of the client keeps those limits out of your error handling:
class NanoSummarizer(context: Context) : AutoCloseable { private val client = Summarization.getClient( SummarizerOptions.builder(context) .setInputType(SummarizerOptions.InputType.ARTICLE) .setOutputType(SummarizerOptions.OutputType.THREE_BULLETS) .setLanguage(SummarizerOptions.Language.ENGLISH) .setLongInputAutoTruncationEnabled(true) .build() ) suspend fun availability() = resolveAvailability { client.checkFeatureStatus().await() } /** Emits streamed text; completes when inference finishes. */ fun summarize(text: String): Flow<String> = callbackFlow { val request = SummarizationRequest.builder(text).build() // trySend returns a ChannelResult we do not inspect. The UNLIMITED buffer // below means it can only fail once the channel is closed, so no chunk is // dropped while the collector is still attached. val future = client.runInference(request) { partial -> trySend(partial) } future.addListener( // The listener runs after completion, so get() returns immediately. { close(runCatching { future.get() }.exceptionOrNull()) }, Runnable::run ) awaitClose { future.cancel(true) } }.buffer(Channel.UNLIMITED) override fun close() = client.close() } object InputGuard { private const val MIN_ARTICLE_CHARS = 400 private const val MAX_APPROX_TOKENS = 4_000 fun approxTokens(s: String) = s.length / 4 // crude, English-biased fun verdict(text: String): Verdict = when { text.length <= MIN_ARTICLE_CHARS -> Verdict.TooShort // show the text itself approxTokens(text) > MAX_APPROX_TOKENS -> Verdict.TooLong // truncate or chunk else -> Verdict.Ok } enum class Verdict { Ok, TooShort, TooLong } } Verify one thing empirically in your version: whether the streaming callback delivers deltas or the cumulative text so far. The docs call the argument “new text,” which reads like a delta, but a UI that appends cumulative text produces a stuttering mess. Log the first three callbacks on a real device before wiring up the UI.
Rewrite
The rewriter takes an output type: elaborate, emojify, shorten, friendly, professional, or rephrase. It supports English, Japanese, French, German, Italian, Spanish, and Korean, and its input limit is tight: under 256 tokens. It may return several suggestions, sorted by descending confidence.
class NanoRewriter(context: Context, tone: RewriterOptions.OutputType) : AutoCloseable { private val client = Rewriting.getClient( RewriterOptions.builder(context) .setOutputType(tone) .setLanguage(RewriterOptions.Language.ENGLISH) .build() ) suspend fun rewrite(text: String): List<String> { val result = client.runInference(RewritingRequest.builder(text).build()).await() return result.results.map { it.text } // best suggestion first } override fun close() = client.close() } Note that a rewriter is bound to its tone at construction. A “pick a tone” chip row therefore means either one client per tone, created lazily and closed on screen exit, or rebuilding the client on selection. Do not hold six live clients because it was convenient in the ViewModel.
Classify
There is no dedicated classification API, so use the Prompt API with a hard constraint on the output. The goal is a closed label set, near-deterministic sampling, and a tiny output budget. As the benchmarks section shows, output length is what you pay for, so a three-token answer is also your cheapest feature.
class NanoClassifier(private val labels: List<String>) : AutoCloseable { private val model = Generation.getClient() suspend fun availability() = resolveAvailability { model.checkStatus() } suspend fun classify(text: String): String? { val prompt = """ Classify the message into exactly one label from: ${labels.joinToString(", ")}. Reply with the label only. If none fit, reply: other. Message: ${text.take(1_500)} """.trimIndent() val raw = model.generateContent( generateContentRequest(TextPart(prompt)) { temperature = 0.0f topK = 1 candidateCount = 1 maxOutputTokens = 8 } ).candidates.firstOrNull()?.text return parseLabel(raw) } // Never trust free text from a small model, even when you asked for one word. private fun parseLabel(raw: String?): String? { val cleaned = raw?.trim()?.lowercase()?.trim('.', '"', '\'', '`') ?: return null return labels.firstOrNull { it.equals(cleaned, ignoreCase = true) } ?: labels.firstOrNull { cleaned.startsWith(it.lowercase()) } } override fun close() = model.close() // releases the generation engine } The request-building DSL above mirrors the sample in Google’s Prompt API announcement, which used a low temperature, a small topK, a single candidate, and a very small output cap. Check the exact property names against the version you depend on, since this client is the newest and the most likely to move.
Failure modes at this layer
- Never closing clients. Each client holds a connection to an on-device service, and that includes the Prompt API’s
GenerativeModel. Release it withclose()inonCleared()or at the end of the feature scope. A leaked client is a slow leak, not a crash, which is the worst kind. - Rewriting past 256 tokens. Long messages need a policy: refuse, truncate, or chunk by sentence. Silent truncation changes meaning, so tell the user.
- Language drift. Ask for English on a Spanish message and you will not get an error, you will get something plausible. Detect the language first and route unsupported ones to fallback.
- Foreground-only inference and per-app quota. AICore enforces an inference quota per app. Google’s
GenAiException.ErrorCodereference documentsBUSY(9) as covering two cases: your app is out of quota (retry with exponential backoff), or the request comes from disallowed background use (call the API while your app is in the foreground). There are alsoBACKGROUND_USE_BLOCKED(30) andPER_APP_BATTERY_USE_QUOTA_EXCEEDED(27), the latter for long-duration quotas such as a daily one. Google does not publish the quota values. Community write-ups additionally report that a foreground service does not count as foreground; I did not find that in the official docs, so test it on a device. Design batch jobs (indexing a whole inbox, say) so they never depend on background Nano. - Output variance across devices. Google notes that output can differ across devices because they carry different Gemini Nano base versions, though the LoRA adapters reduce the gap. Never assert on exact strings in a test that runs on a device farm.
- Trusting the model with structure. Classification output must be parsed against your label set. Anything that fails the parse is
null, which routes to fallback, not to a guess.
3. Handling model download and states
If the status is DOWNLOADABLE, the model is not on the device yet. Google's docs describe two situations: if Gemini Nano is already present, only the feature's adapter downloads, which is quick; if not, the base model must come down first, which takes noticeably longer and is the case you must design for.
You can skip the explicit download. Per the docs, if you never call downloadFeature(), the first inference request triggers it. Do not rely on that for anything user-facing, because the user then stares at a spinner of unknown length with no progress and no way to say "not on mobile data".
Bridge the callback API into a Flow so the download becomes just another observable stream:
sealed interface DownloadEvent { data class Started(val totalBytes: Long) : DownloadEvent data class Progress(val bytesSoFar: Long) : DownloadEvent data object Completed : DownloadEvent } fun Summarizer.downloadEvents(): Flow<DownloadEvent> = callbackFlow { val future = downloadFeature(object : DownloadCallback { override fun onDownloadStarted(bytesToDownload: Long) { trySend(DownloadEvent.Started(bytesToDownload)) } override fun onDownloadProgress(totalBytesDownloaded: Long) { trySend(DownloadEvent.Progress(totalBytesDownloaded)) } override fun onDownloadCompleted() { trySend(DownloadEvent.Completed) close() } override fun onDownloadFailed(e: GenAiException) { close(e) // surfaces as an exception to the collector } }) // Stop tracking when the collector goes away. Whether cancelling the future // also stops the platform's fetch is not documented, so re-check status on // the next entry rather than assuming either way. awaitClose { future.cancel(true) } } The Prompt API takes a different shape for the same job: download() is collected as a flow of DownloadStatus events (started, progress, completed, failed), and it adds an optional warmup() that loads Gemini Nano into memory to cut first-call latency. The task APIs use the callback form shown above. Normalize both into your own DownloadEvent, so the UI layer does not care which client is behind it.
Then collapse everything into one UI state, owned by a ViewModel, and make the transitions explicit:
sealed interface NanoUiState { data object Checking : NanoUiState data object Unsupported : NanoUiState data class NeedsDownload(val sizeKnown: Long?) : NanoUiState data class Downloading(val fraction: Float?) : NanoUiState data object Ready : NanoUiState data class Failed(val retryable: Boolean) : NanoUiState } class NanoViewModel(private val summarizer: NanoSummarizer) : ViewModel() { private val _state = MutableStateFlow<NanoUiState>(NanoUiState.Checking) val state: StateFlow<NanoUiState> = _state.asStateFlow() fun refresh() = viewModelScope.launch { _state.value = when (val a = summarizer.availability()) { Availability.Ready -> NanoUiState.Ready Availability.NeedsDownload -> NanoUiState.NeedsDownload(sizeKnown = null) Availability.Downloading -> NanoUiState.Downloading(fraction = null) is Availability.Unsupported -> NanoUiState.Unsupported } } fun download() = viewModelScope.launch { var total = 0L summarizer.downloadEvents() .catch { _state.value = NanoUiState.Failed(retryable = true) } .collect { event -> _state.value = when (event) { is DownloadEvent.Started -> { total = event.totalBytes; NanoUiState.Downloading(0f) } is DownloadEvent.Progress -> NanoUiState.Downloading(if (total > 0) event.bytesSoFar.toFloat() / total else null) DownloadEvent.Completed -> NanoUiState.Ready } } } } Note that fraction is nullable. When the download is already in flight from an earlier session, you may never see a Started event with a byte count, so the honest UI is an indeterminate bar rather than a fake zero.
Failure modes at this layer
- Downloading on metered data without asking. The base model is not a small asset. Ask first, show the size if you have it, and offer “Wi-Fi only”.
- Restarting a download that is already running. If the status is
DOWNLOADING, attach to the in-flight work. The task-API samples note that an inference request issued in that state runs automatically once the download finishes; the Prompt API docs do not show the same note, so do not assume it there. CallingdownloadFeature()again just confuses your state machine. - Treating download failure as terminal. The documented download error is a network failure (an unresolved host, for instance) with advice to keep the connection and retry. Retry with exponential backoff and a cap, and keep the fallback path live while you wait.
- Assuming the download ends with the process. Your coroutine dies with your process, but the model fetch is not yours. After a cold start, always re-run the availability check rather than trusting in-memory state.
- Progress that lies. If you map “no progress events yet” to 0 percent, users watch a frozen bar and kill the app. Prefer indeterminate until you have real numbers.
- Surprise first-inference stalls. Skipping the explicit download means the first user action blocks on a multi-minute fetch. Make the download an explicit, consented step, or trigger it from a settings screen, and call
warmup()where the Prompt API offers it.
4. Cloud fallback strategy
On-device is a preference, not a guarantee. A real fraction of your users are on devices without Nano, on devices where the config has not landed, on devices whose quota is spent, or on a path where the model returned junk. A fallback strategy is not a bonus. It is the feature’s SLA.
The router has four design rules.
1. Fall back for reasons, and record them. Every result carries where it came from and why it left the...





