@capgo/capacitor-llm

中文文档
8.2.0发布于 2026/11/04MPL-2.0TypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 4.9万

Adds support for LLM locally runned for Capacitor

原始使用文档
文档目录24 节
  1. ➡️ Get started for free
  2. Key features
  3. Documentation
  4. Compatibility
  5. Installation
  6. Model Setup
  7. iOS
  8. Android
  9. Web
  10. Usage
  11. Notes
  12. createChat()
  13. sendMessage(...)
  14. getReadiness()
  15. setModel(...)
  16. downloadModel(...)
  17. addListener('textFromAi', ...)
  18. addListener('aiFinished', ...)
  19. addListener('generationError', ...)
  20. addListener('downloadProgress', ...)
  21. addListener('readinessChange', ...)
  22. getPluginVersion()
  23. Interfaces
  24. Example App

@capgo/capacitor-llm

Run large language models on the device from your Capacitor app: Apple Intelligence on iOS, Gemini Nano or LiteRT-LM on Android, and Gemma web models in the browser. Private and free per request.

Capgo - Build Capacitor apps with AI, ship updates instantly

Capgo: push fixes to your Capacitor users in minutes, build signed iOS and Android apps without a Mac, and roll back in one click.

➡️ Get started for free

14-day unlimited free trial. No credit card required

🤖 Building with an AI coding agent? Install Capgo skills so Claude Code, Codex, Cursor, Copilot, or Gemini CLI know how to install and use @capgo/capacitor-llm in your Capacitor app: npx skills add Cap-go/capgo-skills. Then ask your agent: "Add @capgo/capacitor-llm to my Capacitor app and wire it up." Agent setup guides · Hosted MCP

@capgo/capacitor-llm for Capacitor apps

Key features

  • Chat sessions: createChat() and sendMessage(), with streamed textFromAi, aiFinished and generationError events.
  • Model choice: setModel() picks Apple Intelligence, Gemini Nano or a custom .litertlm model.
  • Model download: downloadModel() fetches a model to the device with downloadProgress events.
  • Readiness: getReadiness() and the readinessChange event tell you when the model can answer.
  • Platforms: iOS, Android and Web. Web uses Gemma models through @mediapipe/tasks-genai. It loads the runtime from a CDN and needs the model file, so it works offline only once both are available locally.

On-device LLM support for Capacitor.

Current platform strategy:

  • iOS: Apple Intelligence by default, plus LiteRT-LM .litertlm custom models in SwiftPM integrations when the path ends in .litertlm or modelType: 'litertlm' is passed
  • Android: Gemini Nano system model on supported devices where it is already available, LiteRT-LM for .litertlm bundles, and a compatibility fallback for legacy MediaPipe .task models
  • Web: Gemma 4 web models through @mediapipe/tasks-genai

Documentation

The most complete plugin docs are available at capgo.app/docs/plugins/llm.

Compatibility

Plugin versionCapacitor compatibilityMaintained
v8..v8..✅
v7..v7..On demand
v6..v6..❌
v5..v5..❌

Note: The plugin major version follows the Capacitor major version. Use the version that matches your Capacitor installation.

Installation

npm install @capgo/capacitor-llm
npx cap sync

If you use the web implementation, also install the MediaPipe peer dependency:

npm install @mediapipe/tasks-genai

Model Setup

iOS

Recommended path:

  • Use Apple Intelligence with path: 'Apple Intelligence'
  • Requires iOS 26.0+

Custom iOS LiteRT-LM path:

  • Available only when the plugin is integrated into the iOS app through Swift Package Manager
  • Uses the official LiteRT-LM Swift API and prebuilt iOS xcframework for .litertlm models
  • Selected only when the path ends in .litertlm or modelType: 'litertlm' is passed
  • CocoaPods builds keep Apple Intelligence and the legacy MediaPipe .task compatibility path
  • Other custom iOS model types keep the legacy MediaPipe compatibility path for backward compatibility

Example:

import { CapgoLLM } from '@capgo/capacitor-llm';

await CapgoLLM.setModel({ path: 'Apple Intelligence' });
const chat = await CapgoLLM.createChat();

Android

Recommended path:

  • Use Gemini Nano with path: 'Gemini Nano' when the Android device already has it available through AICore
  • Use LiteRT-LM .litertlm bundles
  • Gemma 4 E2B and E4B are good default examples
  • Models are available from the public litert-community Hugging Face repos

Gemini Nano system model example:

await CapgoLLM.setModel({ path: 'Gemini Nano' });
const chat = await CapgoLLM.createChat();

Optional: ML Kit GenAI Agent API (Gemini Nano agentic workflows)

Google's ML Kit GenAI Agent API (com.google.mlkit:genai-agent:1.0.0-alpha1) adds AgentRunner managed multi-turn sessions on top of Gemini Nano (including Gemini Nano v4 on supported devices). It is opt-in so apps that do not use it do not pull the dependency.

Docs:

Enable the native dependency (pick one):

  1. capacitor.config.ts (runs capacitor:sync:before hook):
plugins: {
  CapgoLLM: {
    android: {
      genaiAgent: {
        include: true,
        dependencyType: 'implementation',
      },
    },
  },
},
  1. App android/gradle.properties or variables.gradle:
capacitorLLM.genaiAgent.include=true

Use the agent backend (default remains direct genai-prompt access):

await CapgoLLM.setModel({
  path: 'Gemini Nano',
  androidGeminiBackend: 'agent',
});

Requirements: Android API 26+, Android 14 (API 34)+ with AICore for agent previews, Kotlin 2.3+ in the plugin when enabled. See Google's device support list for Gemini Nano model versions.

Fallback: If genai-agent is not included, androidGeminiBackend: 'agent' fails model load with a clear error. Use androidGeminiBackend: 'prompt' (default) or omit the field for the existing Prompt API path.

compileOnly: Set dependencyType: 'compileOnly' in config when your app adds implementation 'com.google.mlkit:genai-agent:1.0.0-alpha1' itself.

Quickstart with a downloaded Gemma 4 model:

import { CapgoLLM } from '@capgo/capacitor-llm';

const result = await CapgoLLM.downloadModel({
  url: 'https://huggingface.co/litert-community/gemma-4-E2B-it-litert-lm/resolve/main/gemma-4-E2B-it.litertlm?download=true',
  filename: 'gemma-4-E2B-it.litertlm',
});

await CapgoLLM.setModel({
  path: result.path,
  modelType: 'litertlm',
  maxTokens: 4096,
  topk: 40,
  temperature: 0.8,
});

const chat = await CapgoLLM.createChat();

Bundled asset example:

await CapgoLLM.setModel({
  path: '/android_asset/gemma-4-E2B-it.litertlm',
  modelType: 'litertlm',
  maxTokens: 4096,
});

Legacy compatibility:

  • Existing Android .task models still load through the compatibility path
  • New integrations should prefer .litertlm

Web

The web implementation uses @mediapipe/tasks-genai with web-ready model artifacts.

Gemma 4 web models are published next to the mobile LiteRT-LM bundles and use *-web.task.

Example:

await CapgoLLM.setModel({
  path: 'https://huggingface.co/litert-community/gemma-4-E2B-it-litert-lm/resolve/main/gemma-4-E2B-it-web.task?download=true',
  modelType: 'task',
  maxTokens: 4096,
});

Usage

import { CapgoLLM } from '@capgo/capacitor-llm';

const { readiness } = await CapgoLLM.getReadiness();
console.log('LLM readiness:', readiness);

const { id } = await CapgoLLM.createChat();

await CapgoLLM.addListener('textFromAi', (event) => {
  console.log('chunk', event.text);
});

await CapgoLLM.addListener('aiFinished', ({ chatId }) => {
  console.log('finished', chatId);
});

await CapgoLLM.sendMessage({
  chatId: id,
  message: 'Explain why local inference is useful on mobile.',
});

Notes

  • Android now prefers LiteRT-LM and Gemma 4 style .litertlm bundles.
  • iOS LiteRT-LM custom-model support now uses the official LiteRT-LM Swift API and prebuilt iOS binaries, is available only in SwiftPM integrations of this plugin, and is selected only for explicit .litertlm models.
  • CocoaPods builds on iOS should use Apple Intelligence or the legacy MediaPipe .task compatibility path.
  • Web uses Gemma 4 *-web.task artifacts through @mediapipe/tasks-genai.
  • Apple Intelligence remains the preferred default on iOS where available.

LLM Plugin interface for interacting with on-device language models

createChat()

createChat() => Promise<{ id: string; instructions?: string; }>

Creates a new chat session

Returns: Promise<{ id: string; instructions?: string; }>


sendMessage(...)

sendMessage(options: { chatId: string; message: string; }) => Promise<void>

Sends a message to the AI in a specific chat session

ParamTypeDescription
options{ chatId: string; message: string; }- The chat id and message to send

getReadiness()

getReadiness() => Promise<{ readiness: string; }>

Gets the readiness status of the LLM

Returns: Promise<{ readiness: string; }>


setModel(...)

setModel(options: ModelOptions) => Promise<void>

Sets the model configuration

  • iOS: Use "Apple Intelligence" as path for the system model. Custom LiteRT-LM .litertlm models are supported on iOS only when this plugin is integrated through Swift Package Manager, and are selected only when modelType: 'litertlm' is passed or the path ends in .litertlm.
  • Android: Use "Gemini Nano" for the AICore system model on supported devices where it is already available. Set androidGeminiBackend: 'agent' to use the ML Kit GenAI Agent API (com.google.mlkit:genai-agent) for managed multi-turn Gemini Nano sessions (opt-in native dependency). Prefer LiteRT-LM .litertlm bundles for custom models; legacy MediaPipe .task models are still supported
  • Web: Provide a web-ready model asset for @mediapipe/tasks-genai such as Gemma 4 *-web.task
ParamTypeDescription
optionsModelOptions- The model configuration

downloadModel(...)

downloadModel(options: DownloadModelOptions) => Promise<DownloadModelResult>

Downloads a model from a URL and saves it to the appropriate location

  • iOS: Downloads to the app's documents directory
  • Android: Downloads to the app's files directory
ParamTypeDescription
optionsDownloadModelOptions- The download configuration

Returns: Promise<DownloadModelResult>


addListener('textFromAi', ...)

addListener(eventName: 'textFromAi', listenerFunc: (event: TextFromAiEvent) => void) => Promise<{ remove: () => Promise<void>; }>

Adds a listener for text received from AI

ParamTypeDescription
eventName'textFromAi'- Event name 'textFromAi'
listenerFunc(event: TextFromAiEvent) => void- Callback function for text events

Returns: Promise<{ remove: () => Promise<void>; }>


addListener('aiFinished', ...)

addListener(eventName: 'aiFinished', listenerFunc: (event: AiFinishedEvent) => void) => Promise<{ remove: () => Promise<void>; }>

Adds a listener for AI completion events

ParamTypeDescription
eventName'aiFinished'- Event name 'aiFinished'
listenerFunc(event: AiFinishedEvent) => void- Callback function for finish events

Returns: Promise<{ remove: () => Promise<void>; }>


addListener('generationError', ...)

addListener(eventName: 'generationError', listenerFunc: (event: GenerationErrorEvent) => void) => Promise<{ remove: () => Promise<void>; }>

Adds a listener for generation failures that happen after streaming starts

ParamTypeDescription
eventName'generationError'- Event name 'generationError'
listenerFunc(event: GenerationErrorEvent) => void- Callback function for generation errors

Returns: Promise<{ remove: () => Promise<void>; }>


addListener('downloadProgress', ...)

addListener(eventName: 'downloadProgress', listenerFunc: (event: DownloadProgressEvent) => void) => Promise<{ remove: () => Promise<void>; }>

Adds a listener for model download progress events

ParamTypeDescription
eventName'downloadProgress'- Event name 'downloadProgress'
listenerFunc(event: DownloadProgressEvent) => void- Callback function for progress events

Returns: Promise<{ remove: () => Promise<void>; }>


addListener('readinessChange', ...)

addListener(eventName: 'readinessChange', listenerFunc: (event: ReadinessChangeEvent) => void) => Promise<{ remove: () => Promise<void>; }>

Adds a listener for readiness status changes

ParamTypeDescription
eventName'readinessChange'- Event name 'readinessChange'
listenerFunc(event: ReadinessChangeEvent) => void- Callback function for readiness events

Returns: Promise<{ remove: () => Promise<void>; }>


getPluginVersion()

getPluginVersion() => Promise<{ version: string; }>

Get the native Capacitor plugin version.

Returns: Promise<{ version: string; }>

Since: 1.0.0


Interfaces

ModelOptions

Model configuration options Only path is required. All other properties are optional overrides.

PropTypeDescriptionSince
pathstringModel path, "Apple Intelligence" for the Apple system model on iOS, or "Gemini Nano" for the Android AICore system model when already available on the device. On iOS, custom .litertlm models require the plugin to be integrated through Swift Package Manager. Gemma 4 examples use .litertlm on mobile and *-web.task on web.
modelTypestringOptional. Model file type/extension (for example task, bin, litertlm, gemini-nano, or gemini-nano-agent). If not provided, it is extracted from the path. On iOS, LiteRT-LM is selected only when this resolves to litertlm; all other custom types keep the legacy MediaPipe compatibility path.
maxTokensnumberMaximum number of tokens the model handles
topknumberNumber of tokens the model considers at each step
temperaturenumberAmount of randomness in generation (0.0-1.0)
randomSeednumberOptional. Random seed for generation.
backend'gpu' | 'cpu'Optional. LiteRT-LM engine backend for iOS (SwiftPM) and Android. Use cpu for stable long generations. When omitted, iOS prefers CPU then falls back to GPU; Android uses CPU.8.2.0
androidGeminiBackend'prompt' | 'agent'Optional. Android-only Gemini Nano integration. Defaults to prompt (ML Kit genai-prompt direct model access). Use agent for ML Kit GenAI Agent API (com.google.mlkit:genai-agent) with AgentRunner managed sessions. Requires opting in to the native dependency in Gradle (see README). Ignored on iOS and web.8.2.0

DownloadModelResult

Result of model download

PropTypeDescription
pathstringPath where the model was saved
companionPathstringPath where the companion file was saved (if applicable)

DownloadModelOptions

Options for downloading a model Only url is required. companionUrl and filename are optional.

PropTypeDescription
urlstringURL of the model file to download
companionUrlstringOptional: URL of a companion file for legacy model formats
filenamestringOptional: Custom filename (defaults to filename from URL)

TextFromAiEvent

Event data for text received from AI

PropTypeDescription
textstringThe text content from AI - this is an incremental chunk, not the full text
chatIdstringThe chat session ID
isChunkbooleanWhether this is a complete chunk (true) or partial streaming data (false)

AiFinishedEvent

Event data for AI completion

PropTypeDescription
chatIdstringThe chat session ID that finished

GenerationErrorEvent

Event data for generation failures chatId is optional and may be omitted when the failure is not tied to a specific chat.

PropTypeDescription
chatIdstringOptional. The chat session ID that failed, when available.
errorstringError message describing the failure

DownloadProgressEvent

Event data for download progress

PropTypeDescription
progressnumberPercentage of download completed (0-100)
totalBytesnumberTotal bytes to download
downloadedBytesnumberBytes downloaded so far

ReadinessChangeEvent

Event data for readiness status changes

PropTypeDescription
readinessstringThe readiness status

Example App

The repo includes an example-app/ that demonstrates:

  • Apple Intelligence on iOS
  • Gemma 4 LiteRT-LM model downloads on Android

See example-app/README.md for local setup instructions.

版本与发布记录

@capgo/capacitor-llm 共发布 48 个版本,首次发布于 2025/08/16;过去 12 个月发布了 37 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
8.2.0latest2026/11/044 天前
8.1.112026/10/1525 天前
8.1.102026/10/1327 天前
8.1.92026/10/091 个月前
8.1.82026/10/081 个月前
8.1.72026/10/081 个月前

关于 @capgo/capacitor-llm 的常见问题

@capgo/capacitor-llm 是什么?

Adds support for LLM locally runned for Capacitor

如何安装 @capgo/capacitor-llm?

在项目目录运行 npm install @capgo/capacitor-llm,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@capacitor/core(>=8.0.0)、@mediapipe/tasks-genai(^0.10.24)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@capgo/capacitor-llm 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@capgo/capacitor-llm 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@capgo/capacitor-llm 可以商用吗?

@capgo/capacitor-llm 使用 MPL-2.0 许可。弱 Copyleft:可以商用,也可以和闭源代码一起使用;但如果分发时修改了 MPL 授权的文件,这些文件的修改需以 MPL 开源。以上为概括,不构成法律意见,请以许可原文为准。

@capgo/capacitor-llm 的下载量有多少?

根据 npm 官方下载统计,@capgo/capacitor-llm 在 2026/10/09 – 2026/11/07 这 30 天内被下载 49,029 次,日均约 1,634 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@capgo/capacitor-llm 还在维护吗?

最新版本 8.2.0 发布于 2026/11/04(4 天前);至今共发布 48 个版本,其中过去 12 个月发布了 37 个;首次发布于 2025/08/16。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。