Generated banner for ML Kit Genai Prompt API
Generated logo for ML Kit Genai Prompt API

ML Kit Genai Prompt API

Android (Google)OfficialCreated by Google LLCDistributed by Android (Google)

  • Skill
  • Tool integration
  • Software development
  • Apache-2.0
  • No issues found

From the author

Analyzes Android codebases to implement ML Kit GenAI Prompt API. Use this skill to send natural language requests on-device to Gemini Nano, use structured output with Prompt API, implement prefix caching, optimize the current prompt, or apply best practices."
— the description by Google LLC

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a comprehensive guide for developers to implement the ML Kit GenAI Prompt API within Android projects. It covers the end-to-end lifecycle of on-device generative AI, including model availability checks, dependency configuration, and resource management. The skill also details advanced optimization techniques such as prefix caching for reduced latency and structured output generation for type-safe data handling.

What it does

  • Configures Android projects with the necessary ML Kit GenAI dependencies.
  • Provides patterns for checking model availability and managing the download lifecycle.
  • Demonstrates how to implement implicit and explicit prefix caching to improve inference speed.
  • Guides the refactoring of string-based prompts into type-safe structured output using annotations.
  • Offers best practices for resource management, including proper model instance disposal.
  • Provides optimization strategies for prompt design to enhance model performance.

When to use it

  • When integrating on-device generative AI features using Gemini Nano in Android apps.
  • When you need to optimize inference latency for recurring prompt prefixes.
  • When you need to ensure your AI responses are returned in a structured, type-safe format.
  • When managing the lifecycle of generative model instances to prevent memory leaks.

Advantages

  • Reduces inference latency through efficient prefix caching mechanisms.
  • Enables type-safe AI interactions by mapping responses directly to data classes.
  • Provides clear lifecycle management patterns for stable app performance.
  • Offers granular control over model state and cache management.

Usage examples

“How do I check if Gemini Nano is ready to use on the device?”
The skill provides the logic to check the FeatureStatus of the generative model and handle the download process if the model is not yet available.
“How can I refactor my string-based prompt to return a structured data object?”
The skill demonstrates using the @Generable annotation and the generateTypedContentRequest method to map AI responses to a specific Kotlin data class.
“How do I speed up my app's AI response time for long prompts?”
The skill explains how to implement prefix caching by separating static prompt prefixes from dynamic suffixes.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/android/ml-kit-genai-prompt-api/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip ml-kit-genai-prompt-api.zip -d .agents/skills

Documentation by Google LLC

This skill provides step-by-step guidance for integrating and optimizing the ML Kit GenAI Prompt API in Android apps.

Prerequisites

  • Android API level must be 26 or higher. If minSdk is below 26, update it to 26.

  • Add the ML Kit GenAI Prompt API dependency (com.google.mlkit:genai-prompt) to the app-level build.gradle file, with version at least 1.0.0-beta4.

  • If com.google.mlkit:genai-schema-compiler dependency is used and KSP plugin version is below 2.3.6, update it to 2.3.6.

Detailed steps

1. Prompt optimization

To optimize prompts for use with the ML Kit Prompt API, follow the prompt optimization guide.

2. Prefix caching optimization

If the prompt is more than 200 words, implement the prefix caching API.

3. Lifecycle and best practices
  • The model must be fully downloaded and available before calling the first inference. Follow the guide on implementing a generative model to check that the FeatureStatus of a model is AVAILABLE before making an inference.

  • Release ML Kit instances by calling close() when an Activity, Fragment, or ViewModel is destroyed. Example:

    // Instantiating model in activity, fragment, or ViewModel
        val generativeModel = Generation.getClient()
    
    // When activity, fragment, or ViewModel is destroyed
        generativeModel.close()

    <br />

4. Structured output

When implementing or refactoring a prompt to use structured output, follow these rules:

  1. Check for API availability: Verify Structured Output feature is available on the device with isStructuredOutputFeatureAvailable() before using it. Refer to the Structured Output API guide for full instructions.

  2. Return type: Return the @Generable typed object from the function signature instead of a String or JSON string.

    For example:

    fun parseEmail(email: String): String {
        ... 
    }

    should be refactored to:

    fun parseEmail(email: String): ParsedEmail? {
        ...
    }
    
  3. Example:

    This is the example code before refactoring:

    suspend fun parseEmail(email: String): String {
        val parseEmailPrompt = "Parse this email and return the sender, title, and short summary of the email less than 10 words: "
    
        val parsedEmail = generativeModel.generateContent(parseEmailPrompt + email)
    
        return parsedEmail.candidates[0].text
    }

    <br />

    This is the example code after using Structured Output API:

    @Generable
    data class ParsedEmail(
        @Guide(description = "Sender of the email")
        var sender: String = "",
    
        @Guide(description = "Title of the email")
        var title: String = "",
    
        @Guide(description = "Summary of the email less than 10 words")
        var summary: String = ""
    )
    
    suspend fun parseEmail(email: String): ParsedEmail? {
        val parseEmailPrompt =
            "Parse this email: $email"
    
        val baseRequest = GenerateContentRequest.Builder(TextPart(parseEmailPrompt)).build()
        val typedRequest = generateTypedContentRequest(baseRequest, ParsedEmail::class)
        val typedResponse = generativeModel.generateContent(typedRequest)
        return typedResponse.candidates[0].response
    }

    <br />

Files

references/prefix-caching.md

[!NOTE] Note: Prefix caching is experimental and may change in the future. This feature is only available on a subset of the supported devices for Prompt API, with support for more devices coming soon. We encourage you to experiment with this API on a Pixel device to understand how it can improve inference latency speeds for your specific use case.

Prefix caching is a feature that reduces inference time by storing and reusing the intermediate LLM state of processing a shared and recurring prompt prefix part. To enable prefix caching, you only have to separate the static prefix from the dynamic suffix in your API request.

Prefix caching currently only supports text-only input, so you shouldn't use this feature if you're providing an image in your prompt.

There are two approaches to implement prefix caching: implicit or explicit:

Use prefix caching implicitly

To enable prefix caching, add the shared portion of the prompt to the promptPrefix field, as shown in the following code snippets:

Kotlin
val promptPrefix = "Reverse the given sentence: "
val dynamicSuffix = "Hello World"

val result = generativeModel.generateContent(
  generateContentRequest(TextPart(dynamicSuffix)) {
    promptPrefix = PromptPrefix(promptPrefix)
  }
)
Java
String promptPrefix = "Reverse the given sentence: ";
String dynamicSuffix = "Hello World";

GenerateContentResponse response = generativeModelFutures.generateContent(
    new GenerateContentRequest.Builder(new TextPart(dynamicSuffix))
    .setPromptPrefix(new PromptPrefix(promptPrefix))
    .build())
    .get();

In the preceding snippet, the dynamicSuffix is passed as the main content, and the promptPrefix is provided separately.

Estimated performance gains

|---|---|---| | | Without prefix caching | With prefix cache-hit (Prefix cache-miss may occur when prefix is used for the first time) | | Pixel 9 with 300-token fixed prefix and a 50-token dynamic suffix prompt | 0.82 seconds | 0.45 seconds | | Pixel 9 with a 1,000-token fixed prefix and a 100-token dynamic suffix prompt | 2.11 seconds | 0.5 seconds |

Storage considerations

With implicit prefix caching, cache files are saved on the client application's private storage, which increases your app's storage usage. Encrypted cache files and their associated metadata, including original prefix text, are stored. Keep the following storage considerations in mind:

  • The number of caches is managed by an LRU (Least Recently Used) mechanism. Least used caches are deleted automatically when exceeding the max total cache amount.

  • Prompt cache sizes are dependent on the length of the prefix.

  • To clear all caches created from prefix caching, use the generativeMode.clearImplicitCaches() method.

    [!NOTE] Note: The clearImplicitCaches() method is experimental and may change in the future.

Use explicit cache management

The Prompt API includes explicit cache management methods to give developers more precise control over how caches are created, searched, used, and removed. These manual operations run independently of the system's automated cache handling.

This example illustrates how to initialize explicit cache management and perform inference:

Kotlin
val cacheName = "my_cache"
val promptPrefix = "Reverse the given sentence: "
val dynamicSuffix = "Hello World"

// Create a cache
val cacheRequest = createCachedContextRequest(cacheName, PromptPrefix(promptPrefix))
val cache = generativeModel.caches.create(cacheRequest)

// Run inference with the cache
val response = generativeModel.generateContent(
  generateContentRequest(TextPart(dynamicSuffix)) {
    cachedContextName = cache.name
  }
)
Java
String cacheName = "my_cache";
String promptPrefix = "Reverse the given sentence: ";
String dynamicSuffix = "Hello World";

// Create a cache
CachedContext cache = cachesFutures.create(
  new CreateCachedContextRequest.Builder(cacheName, new PromptPrefix(promptPrefix))
  .build())
  .get();

// Run inference with the cache
GenerateContentResponse response = generativeModelFutures.generateContent(
  new GenerateContentRequest.Builder(new TextPart(dynamicSuffix))
  .setCachedContextName(cache.getName())
  .build())
  .get();

This example demonstrates how to query, retrieve, and delete explicitly managed caches using generativeModel.caches:

Kotlin
val cacheName = "my_cache"

// Query pre-created caches
for (cache in generativeModel.caches.list()) {
  // Do something with cache
}

// Get specific cache
val cache = generativeModel.caches.get(cacheName)

// Delete a pre-created cache
generativeModel.caches.delete(cacheName)
Java
String cacheName = "my_cache";

// Query pre-created caches
for (PrefixCache cache : cachesFutures.list().get()) {
  // Do something with cache
}

// Get specific cache
PrefixCache cache = cachesFutures.get(cacheName).get();

// Delete a pre-created cache
cachesFutures.delete(cacheName);

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
Google LLC
Publisher
Android (Google) (Official)
Distributed by
Android (Google)
Source
android/skills · device-ai/ml-kit-genai-prompt-api · commit bf68e2d
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE.txt)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Google LLC or Android (Google).

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download ml-kit-genai-prompt-api.zip