mlkit-agent-api
Builds autonomous on-device agentic workflows in Android apps using the
Install / Use
npx skills add android/skills --skill mlkit-agent-apiInstalls into whichever agent you are using.
SKILL.md
Installable skill definition
Quality Score
Category
AutomationSupported Platforms
Our assessment of mlkit-agent-api
mlkit-agent-api scores 86/100 on our quality scale, 1832nd of 2,860 Automation skills we index.
Its SKILL.md is 14 KB long, well organised into 12 sections and no code examples: a thorough specification that gives an agent plenty to work with.
With 7,514 GitHub stars, it is one of the more widely adopted skills in the catalogue.
Maintenance, license and trust
- The repository was last updated 40 days ago, so mlkit-agent-api is actively maintained.
- It is released under the Apache-2.0 license, a permissive license that allows use, modification and commercial use with attribution.
- Its trust signals score 100/100, with no cautions. These come from repository metadata, not a code audit — read the skill file before letting an agent act on it.
mlkit-agent-api compared with similar skills
All 4 of these similar skills score higher than mlkit-agent-api; compare them before choosing.
| Skill | Score | Stars | Updated | Format |
|---|---|---|---|---|
| mlkit-agent-api (this skill)by android | 86 | 7.5k | 40d ago | SKILL.md |
| Agent-Reachby Panniantong | 100 | 107.8k | 1d ago | CLAUDE.md |
| headroomby headroomlabs-ai | 100 | 78.6k | today | CLAUDE.md |
| Scraplingby D4Vinci | 100 | 92.4k | today | MCP Server |
| crawl4aiby unclecode | 100 | 86.8k | today | MCP Server |
Frequently asked questions
- How do I install mlkit-agent-api?
- Run
npx skills add android/skills --skill mlkit-agent-api. The install tabs above show the steps for each supported agent. - Which AI agents does mlkit-agent-api work with?
- It is written for Gemini CLI, as a SKILL.md file. Other agents that read the same format can often use it too.
- Is mlkit-agent-api safe to use?
- It is Apache-2.0-licensed and scores 100/100 on trust signals. Skills are instructions an agent will follow, so read the file before installing it and do not approve commands you do not understand.
- Is mlkit-agent-api still maintained?
- The repository was last updated 40 days ago, so mlkit-agent-api is actively maintained.
Skill content
View source on GitHubname: mlkit-agent-api description: Builds autonomous on-device agentic workflows in Android apps using the ML Kit GenAI Agent API powered by Gemini Nano and AICore. Use this skill when implementing conversational agents, multi-turn chat with AgentSession in a ViewModel, autonomous tool calling using Android AppFunctions (@AppFunctionDeclaration and AppFunctionAgentTools.discover), ephemeral single-turn execution with runner.runSingleTurnAsync, or handling GenAiException error resilience. It solves the problem of orchestrating local reasoning loops, typed tool dispatch, and session persistence on-device with zero cloud latency and privacy preservation. Don't use for cloud-based Gemini models or Vertex AI, single-turn text generation without agent loops (suggest Prompt API), or non-Android platforms. license: Complete terms in LICENSE.txt metadata: author: Google LLC last-updated: '2026-10-24' keywords:
- Android
- ML Kit
- GenAI
- Agent API
- Gemini Nano
- AICore
- AppFunctions
- Tool Calling
- Function Calling
- Session Persistence
- AgentSession
Targeting AICore Developer Preview. This skill provides authoritative execution patterns and failure-prevention rules for on-device agentic workflows in Android apps.
1. Prerequisites and setup
Gradle dependencies
// app/build.gradle.kts
dependencies {
// Core ML Kit GenAI Agent API
implementation("com.google.mlkit:genai-agent:1.0.0-alpha1")
// Android AppFunctions dependency for on-device tool declarations
implementation("androidx.appfunctions:appfunctions:1.0.0-alpha13")
}
[!IMPORTANT] Always use official SDK interfaces from
com.google.mlkit.genai.agent.*,androidx.appfunctions.*,com.google.mlkit.genai.prompt.*, andcom.google.mlkit.genai.common.*. Never declare local placeholder interfaces or fallback mocks.
2. Minimal agent and runner initialization
Configure an Agent with Agent.builder and wrap execution in AgentRunner:
import com.google.mlkit.genai.agent.Agent
import com.google.mlkit.genai.agent.AgentRunner
val agent = Agent.builder()
.setName("OnDeviceAssistant")
.setInstructions("You are a helpful on-device assistant.")
.build()
val runner = AgentRunner(agent)
Agent.builderdefaults tomaxTurns = 10automatically to prevent infinite tool loops.AgentRunnerdefaults to greedy decoding (temperature = 0.0f) for deterministic tool selection and schema compliance.AgentRunner(agent)automatically resolves application context usingMlKitContextfor AppFunction execution in Android apps. An explicitAgentRunner(context, agent)overload is available for headless tests or custom context scopes.
3. Multi-turn chat and lifecycle (ViewModel)
AgentSession preserves conversational history in memory and is not
Parcelable . To preserve dialogue history across Android configuration
changes (such as screen rotation), retain session inside an AndroidX
ViewModel.
When executing single-turn ephemeral queries, managing concurrent multi-sessions, or requiring explicit RAM cleanup, you must follow the guidelines in Session lifecycle.
package com.example.app
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.mlkit.genai.agent.Agent
import com.google.mlkit.genai.agent.AgentRunner
import com.google.mlkit.genai.agent.AgentSession
import com.google.mlkit.genai.agent.textTokens
import com.google.mlkit.genai.common.GenAiException
import com.google.mlkit.genai.prompt.Content
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
class ChatViewModel : ViewModel() {
private val agent = Agent.builder()
.setInstructions("You are a helpful on-device assistant.")
.build()
private val runner = AgentRunner(agent)
private val session: AgentSession =
runner.getOrCreateSession("chat_session")
private val _uiState = MutableStateFlow<ChatUiState>(ChatUiState.Idle)
val uiState: StateFlow<ChatUiState> = _uiState.asStateFlow()
fun sendMessage(prompt: String) {
viewModelScope.launch {
_uiState.value = ChatUiState.Loading("")
try {
// Content.builder() required; runAsync takes Content
val content = Content.builder().text(prompt).build()
var fullResponse = ""
session.runAsync(content)
// Extension function requiring textTokens import
.textTokens()
.collect { token ->
fullResponse += token
_uiState.value = ChatUiState.Loading(fullResponse)
}
_uiState.value = ChatUiState.Success(fullResponse)
} catch (e: GenAiException) {
// Catch GenAiException to prevent app crashes on AI errors
val err = e.localizedMessage ?: "AI error (${e.errorCode})"
_uiState.value = ChatUiState.Error(err)
}
}
}
override fun onCleared() {
super.onCleared()
// Evict conversation session from RAM when ViewModel is destroyed
session.close()
}
}
Essential lifecycle and coroutine rules
-
Contentobject :session.runAsyncandrunner.runSingleTurnAsyncrequire aContentobject. Always build it usingContent.builder().text(userPrompt).build(). -
textTokensextension :textTokensis a Kotlin extension function onFlow<AgentEvent>. Always includeimport com.google.mlkit.genai.agent.textTokens. -
Session cleanup : Always invoke
session.closeinViewModel.onClearedto evict conversational RAM and cancel pending tasks. -
AgentEventstream : When collectingFlow<AgentEvent>directly instead oftextTokens, always includeimport com.google.mlkit.genai.agent.AgentEvent. Match againstAgentEvent.TextMessage(text, isPartial),AgentEvent.FunctionCall(name, args), andAgentEvent.FunctionResponse(name, response), and always include anelse -> {}branch inwhen (event)expressions (AgentEventis non-exhaustive for forward compatibility):import com.google.mlkit.genai.agent.AgentEvent
session.runAsync(content).collect { event -> when (event) { is AgentEvent.FunctionCall -> { _uiState.update { it.copy(activeToolStatus = "Tool started: ${event.name}") } } is AgentEvent.FunctionResponse -> { _uiState.update { it.copy(activeToolStatus = "Tool completed: ${event.name}") } } is AgentEvent.TextMessage -> { _uiState.update { it.copy(responseText = it.responseText + event.text) } } else -> {} // Required: AgentEvent is non-exhaustive for forward compat } }
4. Tool calling recipe
All tools used with Agent originate from Android AppFunctions
(@AppFunctionDeclaration), registered using the declarative path
(enableAppFunctions(true) or addAppFunctionIds(...)) or advanced discovery
(AppFunctionAgentTools.discover(...)).
When you need to restrict caller access levels for private in-app tools or wrap discovered AppFunctions with human-in-the-loop (HITL) confirmation decorators, you must consult Tools and functions.
Option A: Declarative AppFunctions path
Define tools declaratively in your app using AndroidX AppFunctions:
package com.example.app.tools
import androidx.appfunctions.AppFunctionDeclaration
import androidx.appfunctions.AppFunctionSerializable
@AppFunctionSerializable
data class CalendarEvents(val date: String, val events: List<String>)
class CalendarTools {
/**
* Fetches scheduled calendar appointments for a specific date in
* YYYY-MM-DD format.
*
* @param date Date string in YYYY-MM-DD format
*/
@AppFunctionDeclaration(isDescribedByKDoc = true)
fun fetch_calendar(
date: String
): CalendarEvents {
return CalendarEvents(
date = date,
events = listOf(
"Team Standup at 10:00 AM",
"Product Review at 2:00 PM"
)
)
}
}
Enable AppFunctions on Agent.Builder and initialize AgentRunner:
import com.google.mlkit.genai.agent.Agent
import com.google.mlkit.genai.agent.AgentRunner
val agent = Agent.builder()
.setName("CalendarAssistant")
.setInstructions("You assist with calendar queries.")
// Automatically discovers AppFunctions in your app package
.enableAppFunctions(true)
// Optional: scope to specific function IDs or method names
.addAppFunctionIds("fetch_calendar")
.build()
val runner = AgentRunner(agent)
- AppFunction Contract : Tool methods take domain parameters directly (no framework context parameter required). Returns must be primitives or
@AppFunctionSerializabledata classes (Map<String, Any?>isn't supported for AppFunctions). - Restricting Callers with
ACCESS_LEVEL_SELF: AppFunctions don't have to be public to external callers. To restrict execution strictly to your app's internal agent (blocking external system assistants and IPC callers), annotate with@OptIn(ExperimentalAppFunctionsApi::class)and@AppFunctionAccessLevel(level = AppFunctionMetadata.ACCESS_LEVEL_SELF, isCompatEnforcementEnabled = true).
Option B: Advanced discovery and decorator pattern
For inspecting, filtering, or decorating discovered AppFunctions (such as
Human-in-the-Loop confirmation wrappers using AgentTool(delegate)) before
registering with the agent:
import com.google.mlkit.genai.agent.Agent
import com.google.mlkit.genai.agent.AgentRunner
import com.google.mlkit.genai.agent.AgentTool
import com.google.mlkit.genai.agent.AppFunctionAgentTools
// Discover tools (optionally scoped to function IDs)
val discoveredTools = AppFunctionAgentTools.discover(
enabledAppFunctionIds = listOf("fetch_calendar")
)
// Optional: Wrap sensitive tools using AgentTool(delegate) decorator
class HitlConfirmationTool(
delegate: AgentTool,
private val onConfirm: suspend (
toolName: String,
args: Map<String, Any>
) -> Boolean
) : AgentTool(delegate) {
override suspend fun execute(args: Map<String, Any>): Map<String, Any?> {
if (!onConfirm(name, args)) {
return mapOf("status" to "CANCELLED_BY_USER")
}
return checkNotNull(delegate).execute(args)
}
}
val agent = Agent.builder()
.setName("CalendarAssistant")
.setInstructions("You assist with calendar queries.")
.addTools(discoveredTools)
.build()
val runner = AgentRunner(agent)
[!WARNING] Mutual exclusivity : Configure AppFunctions using either the declarative path (
enableAppFunctions(true)onAgent.Builder) or the advanced path (AppFunctionAgentTools.discoverpassed toaddTools), but not both. Using both simultaneously triggers a warning and registers duplicate tool schemas.
Deprecated annotations (@Tool and @Param)
The legacy @Tool and @Param annotations in
`com.google.mlkit.
Truncated for display — read the full file on GitHub.
Related Skills
Agent-Reach
107.8kGive your AI agent eyes to see the entire internet. Read & search Twitter, Reddit, YouTube, GitHub, Bilibili, XiaoHongShu — one CLI, zero API fees.
headroom
78.6kCompress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Scrapling
92.4k🕷️ The BEST Web Scraping framework that handles everything from a single request to a full-scale crawl! Don't be shy, join here: https://discord.gg/EMgGbDceNQ and follow here for daily tips and tricks: https://x.com/Scrapling_dev
crawl4ai
86.8kOpen-source web crawler and scraper for LLMs and AI agents: any website into clean, LLM-ready Markdown. Run it yourself, or use Crawl4AI Cloud with one key. Join our Discord https://discord.gg/VuxzM8mtf
Languages
Trust signals
From repository metadata: license, adoption, age and documentation. Not a code audit — see the Safety scan above for what the skill file itself contains.
