Chuyển đến nội dung
Skillpedia
Agent10k · #11914

mlkit-agent-api

Skill này làm gì

Skill này hướng dẫn xây dựng một agent Android chạy trên Gemini Nano và tự gọi được các hàm của ứng dụng. Nó dành cho lập trình viên Android xây dựng trợ lý trò chuyện hoặc tác vụ agent một lần trên điện thoại. Nó nhắm tới AICore Developer Preview.

Khi nào nên dùng

  • ✓Khi bạn muốn một trợ lý trò chuyện nhiều lượt trong ứng dụng Android chạy trên thiết bị.
  • ✓Khi bạn muốn agent trên thiết bị gọi các hàm của ứng dụng thông qua AppFunctions.
  • ✓Khi bạn cần một yêu cầu đơn lẻ được agent xử lý mà không giữ lịch sử trò chuyện.

Liên kết skill

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

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/android/skills/blob/main/device-ai/mlkit-agent-api/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Xây dựng trợ lý trò chuyện trên thiết bị trong ứng dụng Android của tôi, có thể gọi các hàm của ứng dụng.”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Skill thiết lập một agent với hướng dẫn và runner của nó, rồi giữ phiên trò chuyện trong ViewModel hoặc chạy các yêu cầu một lần. Nó khai báo các hàm của ứng dụng như công cụ để agent có thể gọi.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

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 
Câu hỏi thường gặp

Cái này đã sẵn sàng cho môi trường thật chưa?

Skill nhắm tới AICore Developer Preview, nên hãy kỳ vọng các API là phiên bản xem trước.

Nó ngăn vòng lặp gọi công cụ vô tận bằng cách nào?

Cài đặt mặc định của agent giới hạn nó ở 10 lượt để tránh vòng lặp công cụ vô tận.

Nó cần những thư viện nào?

Nó dùng thư viện genai-agent của ML Kit và thư viện AppFunctions.

Chi tiết

Mô tả gốc của tác giả

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

Độ phổ biến

Sao GitHub
10k
Vị trí xếp hạng
#11914
Giấy phép
Apache-2.0
Cập nhật
29/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự