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
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
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/android/ml-kit-genai-prompt-api/downloadUnzip 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
minSdkis below 26, update it to 26.Add the ML Kit GenAI Prompt API dependency (
com.google.mlkit:genai-prompt) to the app-levelbuild.gradlefile, with version at least1.0.0-beta4.If
com.google.mlkit:genai-schema-compilerdependency 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
FeatureStatusof a model isAVAILABLEbefore making an inference.Release ML Kit instances by calling
close()when anActivity,Fragment, orViewModelis 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:
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.Return type: Return the
@Generabletyped object from the function signature instead of aStringor JSON string.For example:
fun parseEmail(email: String): String { ... }should be refactored to:
fun parseEmail(email: String): ParsedEmail? { ... }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
- ATTRIBUTION.mdAdded by AutoGineer986 B
- LICENSELicence file added by AutoGineer11.1 KiB
- SKILL.md4.1 KiB
- references/get-started.md10.6 KiB
- references/prefix-caching.md5.7 KiB
- references/prompt-design.md3.5 KiB
- references/prompt-optimization.md4.5 KiB
- references/structured-output.md10.2 KiB
- references/system-instructions.md3.3 KiB
references/prompt-design.md
When using Prompt API, there are specific strategies you can use to tailor your prompts and receive optimal results. This page describes best practices for formatting prompts for Gemini Nano.
For more general prompt engineering guidance, see Prompt Engineering whitepaper, Prompt Engineering for Generative AI, and Prompt design strategies.
Alternatively, to automatically refine and improve prompts, you can use the
zero-shot optimizer, which can target on-device models such as
gemma-3n-e4b-it.
Prompt design best practices
When designing prompts for Prompt API, use the following techniques:
Provide examples for in-context learning. Add well-distributed examples to your prompt to show Gemini Nano the kind of result you expect.
Consider using the prefix caching feature when you use in-context learning, as providing examples makes the prompt longer and increases inference time.
Be concise . Verbose preambles with repeated instructions can produce suboptimal results. Keep your prompt focused and to-the-point. If you need to repeat a short directive that guides the model's behavior, consider using system instructions.
Structure prompts to generate more effective responses, such as this sample prompt template that clearly defines instructions, constraints, and examples.
Keep output short . LLM inference speeds are heavily dependent on the output length. Carefully consider how you can generate the shortest possible output for your use case and do manual post-processing to structure the output in the chosen format. To help ensure that the response output is in your preferred format, use the Structured Output API.
Add delimiters . Use delimiters like
<background_information>,<instruction>, and##to create separation between different parts of your prompt. Using##between components is particularly critical for Gemini Nano, as it significantly reduces the chances of the model failing to correctly interpret each component.Prefer simple logic and a more focused task . If you find it challenging to achieve good results with a prompt requiring multi-step reasoning (for example, do X first, if the result of X is A, do M; otherwise do N; then do Y... ), consider breaking the task up and let each Gemini Nano call handle a more focused task, while using code to chain multiple calls together. If you do need to tackle a complex, reasoning-intensive task all at once, consider using thinking mode.
Use lower temperature values for deterministic tasks . For tasks such as entity extraction or translation that don't rely on creativity, consider starting with a
temperaturevalue of0.2, and tune this value based on your testing.
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