React hooks and TypeScript helpers for Chrome's browser-side LanguageModel API.
Use @yudin-s/react-chrome-ai when a React UI needs to check browser support, prepare a local model, stream prompt output, and clean up sessions without wiring the low-level API by hand.
The package keeps the browser API visible, but adds React state for feature detection, availability, download progress, session lifecycle, prompt calls, streaming, structured output, and the current task APIs such as Summarizer, Translator, Language Detector, Writer, Rewriter, and Proofreader.
Chrome Built-in AI is browser-owned and still evolving. This package does not bundle a model, does not call Google APIs, and does not polyfill unsupported browsers.
Live demo · Hook docs · Recipes · Comparison
npm install @yudin-s/react-chrome-aiReact is a peer dependency. The package ships its own conservative Prompt API types, so @types/dom-chromium-ai is optional.
import { useChromeAIPrompt } from "@yudin-s/react-chrome-ai";
export function LocalAssistant() {
const ai = useChromeAIPrompt({
createOptions: {
initialPrompts: [
{ role: "system", content: "You answer concisely and locally." },
],
expectedInputs: [{ type: "text", languages: ["en"] }],
expectedOutputs: [{ type: "text", languages: ["en"] }],
},
});
return (
<form
onSubmit={async (event) => {
event.preventDefault();
await ai.prompt("Summarize what Chrome Built-in AI is.");
}}
>
<button disabled={ai.status === "prompting"}>Ask local model</button>
{ai.progress?.percent != null && <progress value={ai.progress.progress} />}
<output>{ai.text}</output>
</form>
);
}More examples:
- Basic prompt
- Model download progress
- Summarizer task API
- Chrome AI Studio example site
- Local Review Workbench example site
- Local Translator example site
Chrome's native API is intentionally low-level:
LanguageModel.availability(options)must be called with the same language/modality options that will be used for the session.- the first
LanguageModel.create({ monitor })can trigger a large browser-managed download; - session resources must be destroyed;
promptStreaming()returns stream-like browser objects;- structured output and JSON constraints need careful state handling in UI.
@yudin-s/react-chrome-ai gives React apps a predictable hook layer without hiding the native API.
Full hook documentation lives in docs/hooks.md.
The package has two layers:
- Prompt / LLM layer:
LanguageModelsessions withavailability,params,create,monitor,prompt,promptStreaming,append,clone,destroy,contextUsage,contextWindow,contextoverflow,AbortSignal, andresponseConstraint. - Task API layer: generic and convenience hooks for
Summarizer,Translator,LanguageDetector,Writer,Rewriter, andProofreader, including readiness and download progress throughcreate({ monitor }).
Checks whether LanguageModel is exposed and whether the requested model/options are available, downloadable, downloading, or unavailable.
const { supported, availability, status, refresh, userActivation } =
useChromeAIAvailability();Creates and owns a LanguageModel session. Download progress is surfaced as React state. The hook destroys the session on unmount by default.
const { session, status, progress, createSession, destroySession } =
useChromeAISession({ autoCreate: false });Call createSession() from a click/tap handler when Chrome requires user activation to start model preparation.
High-level hook for request-style prompts.
const ai = useChromeAIPrompt();
await ai.prompt([{ role: "user", content: "Write a haiku." }]);Streams a long response from an existing session.
const { session } = useChromeAISession();
const stream = useChromeAIStream(session);
await stream.streamPrompt("Write a longer explanation.");Appends prepared context to a session before a later prompt. This maps to native session.append().
Forks an existing session with native session.clone() and owns the clone teardown.
Tracks contextUsage, contextWindow, and contextoverflow.
Reads LanguageModel.params() when the current Chrome context exposes sampling parameters.
For non-LLM task APIs, use the generic hooks or convenience wrappers:
const summarizer = useChromeAISummarizer({
createOptions: {
type: "key-points",
format: "markdown",
length: "medium",
expectedInputLanguages: ["en"],
outputLanguage: "en",
},
});
await summarizer.run(longArticleText);
console.log(summarizer.availability, summarizer.progress, summarizer.text);Available wrappers:
useChromeAISummarizeruseChromeAITranslatoruseChromeAILanguageDetectoruseChromeAIWriteruseChromeAIRewriteruseChromeAIProofreader
For experimental or newly changing methods, use useChromeAITaskSession or useChromeAITaskOperation directly.
The Prompt API supports responseConstraint for JSON Schema-based structured output. This package exposes that directly and can add a second reflection pass for validation/format repair:
const ai = useChromeAIPrompt<{ severity: "low" | "medium" | "high" }>({
reflection: {
format: "json",
reflect: true,
schema: {
type: "object",
properties: {
severity: { enum: ["low", "medium", "high"] },
},
required: ["severity"],
},
},
});
const result = await ai.promptStructured("Classify this PR risk: lockfile changed.");
console.log(result.data?.severity);Reflection is intentionally simple: draft, then ask the same session to correct instruction-following and formatting issues. Applications with strict correctness needs should still validate parsed data with their own schema validator.
Everything useful outside React is exported too:
getChromeLanguageModelAPI()readChromeAIAvailability(options)createChromeAISession(options, runtime, onProgress)prepareChromeAIModel(options, runtime, onProgress)normalizeDownloadProgress(event)promptWithReflection(session, input, options)safeParseJSON(text)
- Compared with direct
LanguageModelcalls, this package adds React state for readiness, download progress, streaming, context, errors, and teardown. - Compared with AI SDK providers, this package is dependency-light and Chrome UX focused.
- Compared with generic Chromium wrappers, this package is hook-first and includes full example sites.
Read the full comparison in docs/comparison.md.
Choose this package when a React app needs browser-native LanguageModel support and the UI has to show the real runtime state:
- React state for support, availability, download progress, session lifecycle, streaming, and errors;
- Prompt API coverage plus task API wrappers;
- no API keys, no backend, no bundled model;
- small dependency surface: React peer dependency only;
- TypeScript-first public API and copy-paste examples.
Chrome's current docs describe the Built-in AI API family as staged across Stable, origin trials, and developer trials. The Prompt API uses LanguageModel, supports availability(), create(), prompt(), promptStreaming(), append(), clone(), destroy(), context-window tracking, multimodal inputs, and structured output constraints.
Useful references:
npm install
npm run check
npm test
npm run build
npm run pack:dryPublication preparation notes live in docs/publishing.md.
@built-in-ai/core: Vercel AI SDK provider for browser-native AI, useful when your app already uses the AI SDK.simple-chromium-ai: small TypeScript wrapper around Chrome's Prompt API.@types/dom-chromium-ai: community TypeScript declarations.
This package focuses on React hooks and UI state rather than becoming a model-provider adapter.
Recent releases are tracked in CHANGELOG.md.