ai newsDi., 1. Dez.
EilmeldungThe Model Proposes, Your Code Disposes: A Tool-Calling Agent Loop for Android with Gemini Nano

Offline by Default: Shipping Gemini Nano Features Without a Server

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,

dev.toDienstag 08:29 · 01.12.17 Min. Lesezeit
Bild: dev.to

Posted on Dec 1 • Originally published at Medium

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.

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 ( ) } Enter fullscreen mode Exit fullscreen mode 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.

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 } Enter fullscreen mode Exit fullscreen mode 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.

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 } } Enter fullscreen mode Exit fullscreen mode 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.

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 ( ) } Enter fullscreen mode Exit fullscreen mode 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.

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 } Enter fullscreen mode Exit fullscreen mode 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.

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 ) } } Enter fullscreen mode Exit fullscreen mode 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 } } } } Enter fullscreen mode Exit fullscreen mode 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.

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.

1. Fall back for reasons, and record them. Every result carries where it came from and why it left the device. Without that, you cannot answer “what percentage of our users actually get the offline path?”, which is the number that decides whether the project paid off.

3. Validate output before trusting it. A small on-device model can return empty text, the wrong language, or a response that is longer than the input. A cheap validator is the difference between a fallback and a bug report.

4. Always have a last resort that is not a model. If the device cannot do it and cloud is not allowed, degrade: show the first sentences for a summary, hide the rewrite button, or show “uncategorized”. The user sees a slightly worse feature rather than an error.

Two questions, and they need different tools: how long does it take and is the answer any good.

Google’s announcement reports a Pixel 9 Pro text-to-text rate of about 510 tokens per second for prefill (reading the prompt) and about 11 tokens per second for decode (writing the answer). Those two numbers explain nearly everything about how these features feel. Reading is fast, writing is slow, and the asymmetry is about 46 to 1.

As a first-order approximation, latency is roughly inputTokens / 510 + outputTokens / 11, plus cold-start overhead. It ignores tokenization, safety checks and thermal throttling, so use it for planning, not prediction. I applied it to four representative jobs. These are derived estimates from Google's published figures on one device, not measurements of mine, and they exclude the first-call cost of loading the model.

Look at what the chart implies for design:

What the estimates leave out is exactly where the field data will differ: the first call after the process starts (model load), thermal throttling after sustained use, other apps competing for the NPU, and device generation. A mid-range phone with an older Nano version will not match a Pixel 9 Pro.

Do not ship a latency claim you did not measure on your own hardware. A small harness that records time-to-first-chunk and total time per run, labeled by device state, is enough. Run it on physical devices only, since emulators do not have the model.

data class RunSample ( val task: String, val firstChunkMs: Long, val totalMs: Long, val outputChars: Int, val warm: Boolean, val thermalStatus: Int, // -1 when unavailable (below API 29, or no PowerManager) ) class NanoBench ( private val context: Context ) { private val power: PowerManager? = context. getSystemService ( PowerManager:: class. java ) // currentThermalStatus needs API 29; the GenAI APIs themselves start at 26. private fun thermalStatus ( ): Int = if ( Build. VERSION. SDK_INT >= Build.

VERSION_CODES. Q ) power?. currentThermalStatus?: - 1 else - 1 suspend fun measure ( task: String, warm: Boolean, output: Flow < String > ): RunSample { val clock = TimeSource. Monotonic val start = clock. markNow ( ) var first = - 1L var chars = 0 output. collect { chunk -> if ( first < 0 ) first = start. elapsedNow ( ). inWholeMilliseconds chars += chunk. length } return RunSample ( task, first, start. elapsedNow ( ). inWholeMilliseconds, chars, warm, thermalStatus ( ), ) } } fun percentile ( sortedMs: List < Long >, p: Double ): Long? { require ( p in 0.0..

1.0 ) { "p must be in [0, 1]" } if ( sortedMs. isEmpty ( ) ) return null return sortedMs [ ( ( sortedMs. size - 1 ) * p ). roundToInt ( ) ] } Enter fullscreen mode Exit fullscreen mode A protocol that has held up for me:

Google reports benchmark scores for each task comparing the bare base model against the ML Kit GenAI API, and the gap is the argument for using the task clients instead of prompting the base model yourself.

Treat these as a vendor-reported signal about adapter value, not as a measure of your feature. They tell you the adapters help, most for summarization and least for rewriting. They do not tell you whether summaries of your support tickets, in your users’ dialects, are acceptable.

Start with the classifier, because three output tokens make it fast, cheap to fallback, and easy to grade. Add summarization next, with streaming and an explicit one-bullet mode for short surfaces. Add rewriting last, because its 256-token input ceiling and decode-heavy latency make it the hardest to make feel good.

Sources: Google’s announcement of the on-device GenAI APIs in ML Kit (tasks, adapters, benchmark scores, Pixel 9 Pro rates); the Prompt API alpha announcement; and the ML Kit developer docs for summarization, rewriting, and the Prompt API. Quota and foreground-restriction behavior comes from the ML Kit GenAI overview and the GenAiException.ErrorCode reference; the Prompt API surface ( checkStatus(), download(), warmup(), close() ) from the GenerativeModel reference; version caveats from the ML Kit known issues page. The claim that foreground services do not count as foreground is community-reported only. The latency chart is derived arithmetic from Google's published rates, not a measurement.

If “just add launch and hope” describes how your team handles concurrency, I’d recommend “Kotlin Coroutines Under the Hood” — a 25-chapter deep dive that goes past the syntax and down to the bytecode: the Continuation-Passing Style transform, the compiler-generated state machine, and exactly why a suspended coroutine costs a few dozen bytes while a blocked thread costs a megabyte.

It walks through structured concurrency and Job hierarchies, dispatcher internals (Default vs IO vs Unconfined), cooperative cancellation and exception aggregation, Flow’s cold-stream semantics and the full operator vocabulary, StateFlow/SharedFlow’s hot-broadcast model, Channels and fan-in/fan-out patterns, Mutex/Semaphore/actors for shared state, and a complete Android case study retrofitting a legacy callback-driven app onto coroutines and Flow — including a 100,000-coroutines-vs-100,000-threads benchmark lab you can run yourself.

Quelle: dev.to (dev.to). Original öffnen