Sebastian Gomez
Local AI in Production Starts Before the First Token: availability(), User Gestures, and Downloads in Chrome
Chrome Built-in AI's "Hello World" takes three lines of JavaScript: check availability(), call create(), and run prompt(). With Summarizer, Translator, and LanguageDetector stable since Chrome 138, LanguageModel stable on the web since Chrome 148, and five desktop languages supported from Chrome 149 (en, es, ja, de, and fr), it is tempting to drop those three lines in place of a remote fetch().
In production, that snippet rarely survives the first visitor outside your development laptop.
The architectural shift is real. Unlike cloud LLM calls that add network round trips, token bills, and off-device data transfer, Chrome Built-in AI runs Gemini Nano inside the browser. Your site ships only a few kilobytes of JavaScript while Chrome handles downloading and caching the model once across origins, with zero per-token cost and offline execution once cached.
Calling prompt() is the easy part. Real engineering happens before the first token arrives: checking device eligibility without downloading a byte, gating multi-gigabyte transfers behind a user click, surfacing Chromium's real download phases, and keeping your page working when the browser says no.
Why Calling create() on Page Load Breaks Production
The fastest way to break a Built-in AI feature in production is dropping await LanguageModel.create() into DOMContentLoaded, a React useEffect(..., []), or ngOnInit. On your laptop where Gemini Nano already sits on disk, nothing complains. On a real user's browser, two failures hit right away.
First comes user activation. When the model is not yet cached ('downloadable'), Chrome blocks background multi-gigabyte downloads without explicit intent. Calling create() while navigator.userActivation.isActive is false rejects immediately with NotAllowedError.
Second come the hardware and platform requirements. Per Chrome's Built-in AI getting started guide, foundation-model APIs run on desktop only today (Windows 10/11, macOS 13+, Linux, and Chromebook Plus on Platform 16389.0.0+; not Chrome for Android or iOS) with clear cutoffs:
- Storage: at least 22 GB of free disk space on the Chrome profile volume to download. Chrome also evicts the model automatically if free space later drops below 10 GB, re-downloading it once space returns.
- Compute: a GPU with strictly more than 4 GB of VRAM, or a CPU with at least 16 GB of RAM and 4 cores (audio input in the Prompt API strictly requires a GPU).
- Network and secure context: an unmetered connection (Wi-Fi or Ethernet) for the initial download only, inside a Secure Context (
https:orlocalhost/127.0.0.1). Once cached, inference runs 100% offline with zero data leaving the device.
A production page cannot assume every visitor clears those gates. Check availability first and keep a non-AI workflow or server fallback intact for mobile devices, other browsers, and ineligible hardware.
availability() Is a 4-State Machine, Not a Boolean
Checking if ('LanguageModel' in self) is not enough. Modern APIs live directly on self (2024 shapes like window.ai and capabilities() are gone), yet seeing the constructor does not guarantee the model is downloaded, permitted by policy, or valid for your requested languages.
availability(options) returns one of four explicit states:
'unavailable': the hardware, OS, requested languages, orPermissions-Policyblock local AI. Fall back cleanly and never callcreate().'downloadable': the device qualifies, but Chrome must download the base model, LoRA adapter, or language pack first. Render an explicit user-click CTA before callingcreate().'downloading': a transfer is already active. Show progress and attach a monitor via a user-activatedcreate()if needed.'available': the model is cached on disk and ready to instantiate.
Calling availability(options) never transfers bytes or allocates VRAM. Two rules prevent silent mismatches:
- Identical options across both calls: declare your core options object once and pass the exact same object to
availability(opts)andcreate(opts). For example,Proofreaderin Chrome 150+ is English-only and requires{ expectedInputLanguages: ['en'] }on both calls; passing Spanish resolves to'unavailable'. - Translator anti-fingerprinting privacy: calling
Translator.availability({ sourceLanguage: 'es', targetLanguage: 'en' })on an origin that has not created that translator yet deliberately returns'downloadable', even if another site already installed the language pack. Chrome hides installed packs to prevent cross-site fingerprinting.
Here is a safe Chrome 148+ probe that prepares your UI with zero bytes downloaded:
const coreOpts = {
expectedInputs: [{ type: 'text', languages: ['en', 'es'] }],
expectedOutputs: [{ type: 'text', languages: ['es'] }],
};
async function probeLocalAi() {
if (!('LanguageModel' in self) || typeof LanguageModel.availability !== 'function') {
return showFallback('API not exposed in this browser');
}
const state = await LanguageModel.availability(coreOpts);
if (state === 'unavailable') {
return showFallback('Unsupported hardware, languages, or Permissions-Policy');
}
if (state === 'downloadable') {
return renderEnableButton(coreOpts);
}
// 'downloading' or 'available': ready the workspace without instantiating yet
return prepareAiWorkspace(state, coreOpts);
}User Activation (userActivation) and Chromium's 3-Phase downloadprogress
Once the user clicks your button to enable local AI, check navigator.userActivation.isActive before starting a download.
Watch out when chaining APIs behind a single click: transient user activation expires if asynchronous work runs too long before create() fires. In this repository's sample audit (sample-audit-report.md), that exact race surfaced in recipe-arena when awaiting Summarizer before invoking LanguageModel.create(). If the first step takes several seconds, transient activation expires and LanguageModel.create() throws NotAllowedError. When your page already probed availability, call create() synchronously inside the click handler; if a second downloadable model still needs activation, ask for a second explicit click.
Pass three options together into create(): the exact same coreOpts, an AbortSignal to cancel a slow transfer, and a monitor(m) callback for downloadprogress:
async function enableLocalAi(coreOpts, cachedState, onProgress) {
if (cachedState === 'unavailable') return showFallback();
if (cachedState !== 'available' && !navigator.userActivation?.isActive) {
return showGesturePrompt('Click the button to authorize the model download.');
}
const controller = new AbortController();
cancelDownloadBtn.onclick = () => controller.abort();
try {
// Calling create() without extra awaits preserves transient userActivation
const session = await LanguageModel.create({
...coreOpts,
initialPrompts: [{ role: 'system', content: 'Answer concisely.' }],
signal: controller.signal,
monitor(m) {
m.addEventListener('downloadprogress', (e) => {
// W3C spec invariant: e.loaded in [0, 1] and e.total === 1 (no exact bytes exposed)
const pct = Math.max(0, Math.min(100, Math.round(e.loaded * 100)));
onProgress(pct);
});
},
});
return session;
} catch (err) {
if (err.name === 'AbortError') return showStatus('Download cancelled.');
if (err.name === 'NotAllowedError') return showStatus('Requires a user click or Permissions-Policy grant.');
if (err.name === 'NetworkError') return showStatus('Download interrupted; retry on an unmetered network.');
if (err.name === 'NotSupportedError') return showStatus('Requested options or languages are not supported.');
throw err;
}
}Four Chromium downloadprogress behaviors shape how your progress UI should behave:
- No byte counts for privacy: Chrome never exposes exact download sizes.
e.loadedarrives normalized to[0, 1]withe.total === 1, so compute percentages viaMath.round(e.loaded * 100). - Three real phases (
0% → 90% → 100%): Chromium holds briefly at0%while checking the component (show an animated shimmer instead of a dead 0% bar), transfers the CRX artifact from0%to90%, pauses at90%(e.loaded === 0.9) while unpacking and loading weights into memory/VRAM, and fires100%right beforecreate()resolves. Even when already cached, the spec guarantees at least0and1. - Progressive telemetry, never a blocking gate: in test suites using contract doubles (like
scripts/native-contracts.mjs),monitormay never run. Drive your progress bar frommonitor, but neverawaitadownloadprogressevent before unblocking the UI. - When pre-warming makes sense: per Chrome's Built-in AI do's and don'ts, skip cold
create()on page load. Once the user explicitly opens an AI workspace and yourinitialPromptsare ready (sinceinitialPromptsare accepted only increate()), pre-warming eliminates cold-start latency on the first prompt.
Live Walkthrough: Model Concierge (6 APIs, 0 Bytes on Load)
You can inspect this entire lifecycle in the talk's first interactive demo (Demo 01 · Model Concierge).
On initial load, zero sessions exist and zero bytes download. Clicking Check Browser APIs runs static availability() across all six interfaces (LanguageModel, Summarizer, LanguageDetector, Translator with { sourceLanguage: 'es', targetLanguage: 'en' }, Proofreader with { expectedInputLanguages: ['en'] }, and SemanticEmbedder). Only after clicking Create Session on LanguageModel does the row progress from 0% → 42% → 90% → 100% and release the session inside finally, ending at created: 1 · destroyed: 1 · 0 leaks.
The static capture below highlights the details worth inspecting at rest: the expanded Chrome Flags drawer with 1-click copy pills, the inline Proofreader remediation callout showing { expectedInputLanguages: ["en"] } and chrome://flags/#proofreader-api, and the green release receipt confirming 0 (No leaks).
Verified Chrome 148+ Flags, Diagnostics, and TypeScript Contracts
Developers often ask which flags are still needed today. All four Stable desktop APIs (LanguageModel in Chrome 148+, plus Summarizer, Translator, and LanguageDetector since Chrome 138) work with 0 flags on eligible desktop Chrome over HTTPS or localhost. Older pre-148 flags have been retired.
Only Developer Trials still require flags:
chrome://flags/#proofreader-api: enablesProofreaderin Chrome 150+ (English-only; requires{ expectedInputLanguages: ['en'] }).chrome://flags/#semantic-embedder-api: enablesSemanticEmbedderin Canary 153+.chrome://flags/#summarizer-api-performance-preference: optional trial for theSummarizerspeed specialist.
When availability() returns 'unavailable' on your own machine without an obvious cause, inspect Chrome directly before debugging your app code:
chrome://on-device-internals: open the Broker State tab for the exact eligibility reason (hardware, free disk space, download state) and Gemini Nano's disk footprint.chrome://components: verify Optimization Guide On Device Model is downloaded and not stalled.- Web AI Studio DevTools extension: recommended in Chrome's official getting-started guide to inspect model state and active sessions inside DevTools.
For TypeScript, install @types/dom-chromium-ai to match Chrome 148+ types (bearing in mind that types do not add runtime support). To adjust sampling randomness in LanguageModel.create(), use the seven web samplingMode presets ('most-predictable', 'predictable', 'slightly-predictable', 'balanced', 'slightly-creative', 'creative', and 'most-creative'): combining samplingMode with topK or temperature throws a TypeError, because raw topK and temperature are restricted to Chrome Extensions.
If you want to inspect an existing codebase before modifying anything, the Built-in AI Lifecycle Auditor Prompt checks your repository in read-only mode against all seven production lifecycle traps.
Part 2 picks up right after create() resolves: canceling live streams with AbortController, releasing VRAM via finally { session.destroy() } and BFCache-safe pagehide, isolating tasks with baseSession.clone(), and rendering streamed output without XSS risks.
Live Lab and References
- Interactive Demo 01 (6-API Board &
availability()): model-concierge.html - Interactive talk deck (20 slides, ES/EN): slides-lifecycle/index.html
- Built-in AI Lifecycle Auditor Prompt (talk giveaway): GIST-READY-built-in-ai-lifecycle-auditor.md
- Official Chrome documentation: Get started with built-in AI · Built-in AI: Do's and Don'ts · The Prompt API · Proofreader API · Translator API
- TypeScript definitions: @types/dom-chromium-ai
Sebastian Gomez
Creador de contenido principalmente acerca de tecnología.