Перейти к содержанию
Skillpedia
Агенты10k · #11914

mlkit-agent-api

Что он делает

Этот скилл направляет создание Android-агента, который работает на Gemini Nano и может самостоятельно вызывать функции приложения. Он нужен Android-разработчикам, которые создают чат-помощников или разовые задачи агента на телефоне. Скилл рассчитан на AICore Developer Preview.

Когда использовать

  • ✓Когда вы хотите многоходовой чат-помощник в Android-приложении, который работает на устройстве.
  • ✓Когда вы хотите, чтобы агент на устройстве вызывал функции вашего приложения через AppFunctions.
  • ✓Когда нужно обработать один разовый запрос агентом без сохранения истории чата.

Ссылка на скилл

https://github.com/android/skills/blob/main/device-ai/mlkit-agent-api/SKILL.md

Скопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.

Как использовать

Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.

Готовое сообщение для вставки

Используй этот скилл, чтобы помочь мне: https://github.com/android/skills/blob/main/device-ai/mlkit-agent-api/SKILL.md Прочитай файл SKILL.md по этой ссылке и следуй его инструкциям в моей задаче.
Хотите, чтобы ваш ИИ сам находил такие скиллы?Установите бесплатный MCP Skillpedia: одна строка, и перед каждой задачей он ищет среди 15 000+ скиллов.Установить за 1 минуту →

Пример запроса к вашему ИИ

“Создай в моем Android-приложении чат-помощника на устройстве, который может вызывать функции моего приложения.”

5 новых скиллов в неделю. 1 минута чтения.

Как это работает

Скилл настраивает агента с его инструкциями и runner, затем ведет сессию чата во ViewModel или выполняет разовые запросы. Функции приложения он объявляет как инструменты, которые агент может вызывать.

Технический текст (оригинальный SKILL.md)

Оригинальный текст автора на английском, прямо с GitHub.

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 
Частые вопросы

Готово ли это к продакшену?

Скилл рассчитан на AICore Developer Preview, поэтому ожидайте, что API будут предварительными версиями.

Как он предотвращает бесконечные циклы вызовов инструментов?

По умолчанию агент ограничен 10 ходами, чтобы не допустить бесконечных циклов инструментов.

Какие библиотеки нужны?

Используются библиотека ML Kit genai-agent и библиотека AppFunctions.

Подробности

Оригинальное описание автора

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 a

repo: android/skills

Популярность

Звёзды на GitHub
10k
Место в рейтинге
#11914
Лицензия
Apache-2.0
Обновлён
29.10.2026

Полезен ли этот скилл?

0

Войдите , чтобы голосовать.

Комментарии

  • …

Другие скиллы из этого репозитория

Похожие скиллы