Mlkit Agent Api logo

Mlkit Agent Api

OrganizationPopular
android
mlkit-agent-api

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.

Overview

Publisherandroid
Repositoryskills
Skill namemlkit-agent-api
Stars
10K
Forks
654
Bundled files
2
LicenseApache-2.0
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • 2 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

    Published by android on GitHub. Read the source before you install it.

Installation

Install the Mlkit Agent Api AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/android/skills/tree/main/device-ai/mlkit-agent-api
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/android/skills.git /tmp/skills
mkdir -p .claude/skills
cp -r /tmp/skills/device-ai/mlkit-agent-api .claude/skills/mlkit-agent-api
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Mlkit Agent Api in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Mlkit Agent Api on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Mlkit Agent Api is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

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.*, and com.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.builder defaults to maxTurns = 10 automatically to prevent infinite tool loops.
  • AgentRunner defaults to greedy decoding (temperature = 0.0f) for deterministic tool selection and schema compliance.
  • AgentRunner(agent) automatically resolves application context using MlKitContext for AppFunction execution in Android apps. An explicit AgentRunner(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

  1. Content object : session.runAsync and runner.runSingleTurnAsync require a Content object. Always build it using Content.builder().text(userPrompt).build().

  2. textTokens extension : textTokens is a Kotlin extension function on Flow<AgentEvent>. Always include import com.google.mlkit.genai.agent.textTokens.

  3. Session cleanup : Always invoke session.close in ViewModel.onCleared to evict conversational RAM and cancel pending tasks.

  4. AgentEvent stream : When collecting Flow<AgentEvent> directly instead of textTokens, always include import com.google.mlkit.genai.agent.AgentEvent. Match against AgentEvent.TextMessage(text, isPartial), AgentEvent.FunctionCall(name, args), and AgentEvent.FunctionResponse(name, response), and always include an else -> {} branch in when (event) expressions (AgentEvent is 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 @AppFunctionSerializable data 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) on Agent.Builder) or the advanced path (AppFunctionAgentTools.discover passed to addTools), 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.genai.schema.annotations.*, along with AgentTool.fromAnnotatedObject, Agent.Builder.addTools(annotatedObject: Any), and standalone FunctionTool, have been deprecated or removed. All tools added to Agent must originate from @androidx.appfunctions.AppFunctionDeclaration using Agent.Builder.enableAppFunctions(true) or AppFunctionAgentTools.discover.


5. Ephemeral single-turn execution

For one-off tasks where conversation history isn't needed (such as summarizing text, formatting data, or answering standalone questions), invoke runner.runSingleTurnAsync(content) directly:

import com.google.mlkit.genai.agent.AgentRunner
import com.google.mlkit.genai.agent.textTokens
import com.google.mlkit.genai.prompt.Content
import kotlinx.coroutines.flow.Flow

// Executes a single-turn query ephemerally without session persistence:
fun askQuickQuestion(runner: AgentRunner, question: String): Flow<String> {
    val content = Content.builder().text(question).build()
    return runner.runSingleTurnAsync(content).textTokens()
}
  • runner.runSingleTurnAsync(content) automatically creates and evicts an ephemeral session upon Flow completion.
  • Cleanup reference :
    • session.close: Releases session resources and cancels coroutines (call in ViewModel.onCleared).
    • session.delete or runner.deleteSession(sessionId): Permanently deletes the session from the runner.

6. Error handling and GenAiException reference

Runtime failures during on-device execution (such as model unavailability or exceeding maximum turn limits) are emitted or thrown as GenAiException:

import com.google.mlkit.genai.common.GenAiException

Key error codes

  • GenAiException.ErrorCode.MAX_TURNS_EXCEEDED (-112): The agent exceeded maxTurns (default 10) without completing the reasoning loop.
  • GenAiException.ErrorCode.NOT_AVAILABLE (8): The Gemini Nano model or AICore service isn't available on this device.
  • GenAiException.ErrorCode.BUSY (9): System or AICore is busy, or battery or thermal quota has been reached.

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the Mlkit Agent Api AI skill do?

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 latenc...

Why use Mlkit Agent Api on TypingMind?

Because you install it once and use it with any model. Mlkit Agent Api is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Mlkit Agent Api in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/android/skills/tree/main/device-ai/mlkit-agent-api. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use Mlkit Agent Api?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Mlkit Agent Api?

As many as you like. As long as a model supports skills, you can use Mlkit Agent Api with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Mlkit Agent Api AI skill free?

Yes. It is published on GitHub by android under the Apache-2.0 license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇