Flutter 设备内置 AI 调用
flutter-edge-ai-builtin-ai
当使用 flutter_edge_ai_builtin_ai 运行设备自带模型时使用本技能——Android 或桌面 Chrome 上的 Gemini Nano、Microsoft Edge 中的 Phi-4-mini、iPhone、iPad 和 Mac 上的 Apple Foundation Models、Windows 上的 Phi Silica——无需下载或捆绑任何内容;或在模型缺失时回退到已下载的模型时使用。当抛出 BuiltInAiUnavailableException 或 TimeoutException、可用性报告为 "downloadable"、Web 端在用户手势之外抛出 LocalAiUserActivationRequiredException、Android 构建因 minSdk 导致清单合并失败,或 Chrome 中模型缺失时,也使用本技能。对于应用自行下载的模型,请使用 flutter-edge-ai-inference。
- License 许可
- MIT
- 最近更新
- 2026-11-14
- Stars
- ★ 662
- Forks
- 180
01 前言 Front Matter
- name
- flutter-edge-ai-builtin-ai
- description
- Use when running the device's own model with flutter_edge_ai_builtin_ai — Gemini Nano on Android or in desktop Chrome, Phi-4-mini in Microsoft Edge, Apple Foundation Models on iPhone, iPad and Mac, Phi Silica on Windows — with nothing to download or bundle, or when falling back to a downloaded model where it is missing. Also use when BuiltInAiUnavailableException or a TimeoutException is thrown, availability reports "downloadable", web throws LocalAiUserActivationRequiredException outside a user gesture, the Android build fails the manifest merge on minSdk, or the model is missing in Chrome. For models the app downloads itself, use flutter-edge-ai-inference.
03 SKILL.md 正文
The built-in OS model
Rules
- The OS owns the weights, but the model is still installed — as an identity:
fileType: ModelFileType.builtInwith.fromBundled(...). The app downloads nothing. - Call
BuiltInAi.ensureReady()beforegetActiveModel(), from a user action: the first call downloads the model and can take minutes, and on web the browser refuses to start that download without a user gesture. Call it straight from the tap handler, with no slowawaitin front of it. It throwsTimeoutExceptionaftertimeout— 10 minutes by default. - On web,
ensureReadycalled outside a user gesture throws aBuiltInAiUnavailableExceptionwhosestatusisBuiltInAiAvailability.downloadable— in the log,LocalAiUserActivationRequiredException: Chrome only starts the Gemini Nano download inside a user gesture…, a subclass. The browser can run the model; it is waiting for a tap. Checke.status == BuiltInAiAvailability.downloadablefirst, ask the user to tap, and callensureReadyagain from that tap handler. Do not fall back to a download here — the fallback below would fetch gigabytes the browser was about to provide. - Catch
BuiltInAiUnavailableExceptionwith any otherstatusand fall back to a downloadable model. - Android apps need
minSdk 26, or the manifest merge fails, and Kotlin 2.3.21. The native layer, flutter_local_ai, no longer applies the Kotlin Gradle Plugin itself (since 0.2.0), so it does not block built-in Kotlin on AGP 9; other plugins in the app still may. - Linux has no built-in model:
BuiltInAiModels.forCurrentPlatformis null there andBuiltInAi.availability()reportsBuiltInAiAvailability.unavailableDeviceUnsupported. Windows runs Phi Silica through Windows AI Foundry on Copilot+ hardware, in a packaged app; a Windows build that could not resolve the Windows App SDK reports the same unavailable state, so the fallback below covers it.
Setup with a fallback
flutter pub add flutter_edge_ai flutter_edge_ai_builtin_ai flutter_edge_ai_litertlm
import 'dart:async';
import 'package:flutter_edge_ai/flutter_edge_ai.dart';
import 'package:flutter_edge_ai_builtin_ai/flutter_edge_ai_builtin_ai.dart';
import 'package:flutter_edge_ai_litertlm/flutter_edge_ai_litertlm.dart';
await FlutterEdgeAi.initialize(
inferenceEngines: [BuiltInAiEngine(), LiteRtLmEngine()],
);
final spec = BuiltInAiModels.forCurrentPlatform; // null on Linux
Future<InferenceModel> downloadGemma() async {
await FlutterEdgeAi.installModel(
modelType: ModelType.gemma4,
fileType: ModelFileType.litertlm,
).fromNetwork(
// 2.6 GB — ask first. On web: gemma-4-E2B-it-web.litertlm
'https://huggingface.co/litert-community/gemma-4-E2B-it-litert-lm/resolve/main/gemma-4-E2B-it.litertlm',
).install();
return FlutterEdgeAi.getActiveModel(maxTokens: 1024);
}
InferenceModel model;
if (spec == null) {
model = await downloadGemma();
} else {
try {
// The first await in the tap handler: on web the browser starts the
// download only inside a user gesture, so nothing slow may run before it.
// onProgress reports real percentages on Android and the web; Apple
// downloads nothing and reports none — ensureReady just waits.
await BuiltInAi.ensureReady(onProgress: (int percent) => print('$percent%'));
await FlutterEdgeAi.installModel(
modelType: ModelType.general,
fileType: ModelFileType.builtIn,
).fromBundled(spec.name).install();
model = await FlutterEdgeAi.getActiveModel(maxTokens: 4096);
} on BuiltInAiUnavailableException catch (e) {
if (e.status == BuiltInAiAvailability.downloadable) {
// Web, called outside a user gesture. The browser can run the model:
// show an "Enable AI" button and call ensureReady from its handler.
return;
}
model = await downloadGemma();
} on TimeoutException {
model = await downloadGemma();
}
}
The latest install is the one getActiveModel loads, so the fallback replaces the built-in model. Sessions and chats then work as in the flutter-edge-ai-inference skill.
Checking before offering the feature
final availability = await BuiltInAi.availability();
final usable = availability == BuiltInAiAvailability.available ||
availability == BuiltInAiAvailability.downloadable ||
availability == BuiltInAiAvailability.downloading;
downloadable and downloading mean "not yet" — ensureReady finishes the job. The unavailable* states describe the device now, not forever:
| State | Meaning |
|---|---|
BuiltInAiAvailability.unavailableDeviceUnsupported |
the hardware cannot run it — and on web, that the browser exposes no Prompt API at all, including desktop Chrome before 148 with neither the flag nor an origin-trial token |
BuiltInAiAvailability.unavailableOsTooOld |
an OS update would enable it; on Apple the floor is OS 26 |
BuiltInAiAvailability.unavailableDisabled |
the user can turn it on in system settings (Apple Intelligence on Apple devices) |
BuiltInAiAvailability.unavailableOther |
anything else: a probe that timed out after 20 seconds, or Chrome's reasonless "unavailable", which in practice is its disk and VRAM floor — worth asking again later |
Platforms
| Platform | Model | Needs |
|---|---|---|
| Android | Gemini Nano (AICore) | a device on Google's Prompt API device list; minSdk 26 |
| iOS, macOS | Apple Foundation Models | iOS 26+ / macOS 26+ on an iPhone 15 Pro or newer, or an Apple Silicon Mac, with Apple Intelligence on; below OS 26 it reports unavailableOsTooOld. flutter_local_ai builds from iOS 13 / macOS 12; with core the app needs iOS 15.0 and a macOS 12.0 deployment target |
| Windows | Phi Silica (Windows AI Foundry) | Windows 11 25H2+ on a Copilot+ PC or a supported GPU, in a packaged app. Streams one final chunk and ignores maxOutputTokens |
| Web | Gemini Nano (Chrome Prompt API) | desktop Chrome 148+ — not mobile browsers, Firefox or Safari |
| Web | Phi-4-mini (Edge Prompt API) | Microsoft Edge with the Prompt API flag on; Edge Dev 154–155 exposes the API but cannot run the model |
Images work on Android, one per message, and only when asked for: pass supportImage: true to getActiveModel (getActiveModel(maxTokens: 4096, supportImage: true)); chats from openChat and sessions inherit it. An image sent to a model loaded without it throws UnsupportedError. Windows and web are text-only, and Apple is text-only on OS 26: supportImage: true there fails when getActiveModel creates the model, not mid-conversation — so do not build an image path there.
Web
There is no script to add: the Prompt API is part of the browser.
- Chrome — since Chrome 148 the Prompt API is available to ordinary web pages: no origin-trial token and no
chrome://flagsentry. - Microsoft Edge — enable
edge://flags→ "Prompt API for on-device language model" and restart. Both browsers useBuiltInAiModels.chromePromptApi, which is whatforCurrentPlatformreturns on web: the spec names the API, and the browser picks the model. - Sampling — on web,
topPandmaxOutputTokensare ignored (warned once); on web pages Chrome ignorestemperatureandtopKtoo (they work in Chrome Extensions only) and logs a deprecation warning, so atopK: 1there is not greedy.
Trade-offs
No choice of weights, no LoRA, and capabilities that vary by OS version. The right pick when zero download and zero disk matter more than choosing the model.
Tool calls go through the prompt on every platform. The flutter_edge_ai
responseFormat path is implemented but no built-in platform is qualified in
this release: model.structuredOutputSupport.isSupported is false and
openSession / openChat(responseFormat: ...) throw
ResponseFormatUnsupportedException on Apple, Chrome, Windows and Android.
Android has no bridged runtime-schema API; Apple, Chrome and Windows remain
gated until their own runs pass. Platform-native tool and structured APIs that
flutter_local_ai exposes remain reachable through
BuiltInAiModel.localAiModel / BuiltInAiSession.localAiSession
(@experimental).
When a built-in platform is eventually enabled, its flutter_edge_ai structured
reply is buffered as one final chunk and supports only the keywords reported by
structuredOutputSupport; model.refusalFor(format) can still reject a
particular schema. On Apple, responseFormat together with maxOutputTokens is
also refused at openSession / openChat even if refusalFor(format) returns
null, because the platform cannot report that the cap cut the value.
04 同仓库更多 Skills
电子邮件发送
send-email
发送电子邮件。
维基百科摘要查询
query-wikipedia
查询维基百科中给定主题的摘要。
二维码生成
qr-code
为给定的 URL 生成二维码。
厨房冒险文字游戏
kitchen-adventure
扮演一款文字冒险游戏的地下城主,故事设定在一个所有人都是有感知能力的厨房电器的世界里。当用户说"start kitchen adventure"时触发。
交互式地图展示
interactive-map
为给定位置显示交互式地图视图。
当前日期时间查询
get-current-time
获取用户当前的本地日期、时间和星期几。