AIOnDeviceModel

class AIOnDeviceModel(context: Context, val maximumResponseTokens: Int = DEFAULT_RESPONSE_TOKENS) : AILocalModel, AutoCloseable

Gemini Nano, the model in Android's AICore, through ML Kit's GenAI Prompt API. It answers without a network connection, and the conversation never leaves the device.

It runs on devices whose AICore offers Gemini Nano (recent Pixel, Samsung and other flagship phones), not on emulators. The model may need downloading first: status says whether it is Status.Downloadable or Status.Downloading, and download starts it.

It is a small model, good for short answers and for working with what is in the conversation. Its context holds a few thousand tokens, so the oldest turns of a long conversation are left out.

val model = AIOnDeviceModel(context)
if (model.isAvailable()) {
model.reply(instructions, turns).collect { answer -> show(answer) }
}

Parameters

context

Any context; the application context is kept.

maximumResponseTokens

The longest answer, in tokens. The model writes at most MODEL_MAXIMUM_RESPONSE_TOKENS, so larger values are capped.

Constructors

Link copied to clipboard
constructor(context: Context, maximumResponseTokens: Int = DEFAULT_RESPONSE_TOKENS)

Types

Link copied to clipboard
object Companion
Link copied to clipboard
abstract class Download

How a download of the model is going. More states may be added.

Link copied to clipboard
class Failure(cause: Throwable) : Exception

Thrown by reply when the model fails while answering.

Link copied to clipboard

Where the model is on this device.

Link copied to clipboard
class Unavailable(cause: Throwable? = null) : Exception

Thrown by reply when the model can't answer on this device.

Properties

Link copied to clipboard

Functions

Link copied to clipboard
open override fun close()

Releases the model's resources.

Link copied to clipboard

Downloads the model, when status is Status.Downloadable. The download continues while the flow is collected.

Link copied to clipboard
open suspend override fun isAvailable(): Boolean

Whether the model can answer now.

Link copied to clipboard
open override fun reply(instructions: String, turns: List<AIConversationTurn>): Flow<String>

Streams the answer to the last of turns. Each emission is the whole answer so far, and cancelling the collection stops the model.

Link copied to clipboard

Where the model is on this device. A device without AICore, or an error, reads as unavailable.