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/system-instructions.md

System instructions let you give the model a persona, set the tone of its responses, or provide specific rules it must follow. These instructions are separate from the user's prompt and are treated with higher priority by the model to ensure it behaves as expected.

Common use cases include:

  • Setting a persona: For example, "You are a helpful math tutor."

  • Enforcing output format: For example, "Always respond in bullet points."

  • Setting constraints: For example, "Do not answer questions about politics."

Prerequisites

System instructions work on devices running Gemini Nano V3 and higher. For a list of supported devices, see Prompt API device support.

Limitations

We don't recommend using system instructions with prefix caching. In general, use system instructions for short instructions that define how the model should behave; use prefix caching if you need to repeat a large part of your prompt across queries and need to optimize performance.

How to use system instructions

To provide system instructions, create a SystemInstruction object and pass it to the GenerateContentRequest builder:

import com.google.mlkit.genai.prompt.SystemInstruction
import com.google.mlkit.genai.prompt.TextPart
import com.google.mlkit.genai.prompt.generateContentRequest

// 1. Define the system instruction
val systemInstruction =
    SystemInstruction("You are a concise assistant. Answer in 2 sentences or less.")

// 2. Create the request
val request = generateContentRequest(TextPart("How does photosynthesis work?")) {
    this.systemInstruction = systemInstruction
}

// 3. Run inference
try {
    val response = generativeModel.generateContent(request)
    println(response.candidates.firstOrNull()?.text)
} catch (e: GenAiException) {
    // Handle SDK-specific exceptions
}

You can further simplify the code by passing the system instructions directly into the generateContentRequest request builder:

val request = generateContentRequest(
    SystemInstruction("You are a pirate. Speak like one."),
    TextPart("What is the weather like today?")
) {
    // Optional configurations like temperature
    temperature = 0.7f
}

Best practices

Here are some best practices when using system instructions:

  • Be clear and direct: The model follows clear, direct instructions better than ambiguous ones. Here are some examples:

    • Vague (avoid): "Don't write too much. Try to be helpful and friendly, and format the output nicely."

    • Clear (preferred): "You are a friendly customer support assistant. Limit your responses to a maximum of 3 sentences. Format any lists using bullet points."

  • Be concise: While system instructions are powerful, very long instructions can consume the model's limited context window.

  • Factor in token counts: Make sure that your token counting logic includes the system instructions to avoid underestimating request size. We recommend keeping your system instructions to under 150 words (100-200 tokens).

  • Test and iterate: Model behavior can vary based on phrasing. Test with various user inputs to ensure the model maintains its persona consistently.

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