LocalMode

Local-first, privacy-first, offline-first AI for the browser.

Run ML models entirely in your browser. No servers. No API keys. Your data never leaves your device.

  • Docs website:
  • UI Components:
  • Blocks & Apps:

What is LocalMode?

LocalMode is a monorepo of packages for building AI-powered applications that run 100% in the browser. Everything from embeddings and vector search to LLM chat, vision, audio, agents, and structured output works offline after the initial model download.

15 packages. 36 demo blocks. Zero cloud dependencies.

Why LocalMode?

  • Privacy -- Your data never leaves your device. No telemetry, no tracking, no network requests from core.
  • Offline -- Works without internet after model download. Automatic fallbacks for every capability.
  • Fast -- No network latency. WebGPU acceleration where available. Instant inference.
  • Free -- No API costs, no rate limits, unlimited usage.
  • Universal -- Works in Chrome, Edge, Firefox, and Safari. Adapts to device capabilities.
  • Interoperable -- Vercel AI SDK patterns. LangChain.js adapters. Import from Pinecone/ChromaDB.

Packages

PackageVersionDescription
Zero-dependency core -- VectorDB (HNSW, typed metadata, WebGPU search, SQ8/PQ quantization), pipelines, inference queue, model cache, agent framework (ReAct + tools with opt-in human-in-the-loop tool approval + memory), evaluation SDK, vector import/export, multimodal content, knowledge base engine (createKnowledgeBaseEngine + frozen KnowledgeBaseEngine contract), all interfaces
64 React hooks, 10 pipeline step factories, batch/list processing, and browser helpers -- incl. useEncryptedVault passphrase-locked encrypted storage, useAgent tool-approval surface (pendingApproval/approve/deny), useRerank document reranking, useModelLoad unified model-download lifecycle, useChat usage tracking + regenerate() reply variants, useProviderFallback per-capability Chrome AI ⇄ Transformers.js resolution, usePhotoLibrary shared CLIP photo library, and useKnowledgeBase knowledge-base session orchestration
Vercel AI SDK provider for local models
HuggingFace Transformers.js provider -- 26 model factories covering embeddings, classification, vision, audio, OCR, multimodal (CLIP), and LLM inference via ONNX (Qwen3.5 vision support)
WebLLM provider for LLM inference via WebGPU -- 32 curated models including DeepSeek-R1, Qwen3, Llama 3.2, Phi 3.5 Vision
GGUF model provider via llama.cpp WASM -- 30 curated models (text, vision, embeddings, reranking), true streaming, structured output (JSON mode), reasoning mode, WebGPU acceleration, tool calling, grammar sampling (GBNF), LoRA adapters, model management, GGUF model discovery (searchGGUFModels/listGGUFFiles), 160K+ HuggingFace models, universal browser support
Google LiteRT-LM provider (.litertlm models, WebGPU + CPU WASM fallback). Text-only, early preview. Catalog ships Gemma 4 E2B/E4B and Qwen3 0.6B, all verified end-to-end. Gated Gemma 3n / Gemma 3 1B loadable via custom URL.
Google MediaPipe Tasks provider -- real-time hand/pose/face landmark tracking, gesture recognition, image & audio classification, language detection. WASM + WebGL, all browsers.
Chrome Built-in AI provider -- your app ships no model files; Chrome supplies Gemini Nano. Automatic fallback
LangChain.js adapters -- drop-in local embeddings, chat, vector store, and reranker for existing LangChain apps, plus createLangChainKnowledgeBaseEngine (the KnowledgeBaseEngine contract over LangChain adapters)
In-app AI observability -- 9 React hooks via the @localmode/devtools/react subpath for model cache, VectorDB stats, and inference queue data (the bundled DevTools widget UI was removed in v3.0.0 in favor of the hooks + the ui/devtools registry family and ui/blocks/devtools-drawer at localmode.ai)
PDF text extraction with PDF.js
Dexie.js storage adapter with schema versioning and transactions
Minimal IndexedDB storage adapter using the idb library
Cross-browser storage adapter with automatic fallback

@localmode/ui — UI registry (not an npm package)

is a shadcn-style registry of copy-owned AI UI components: 107 primitives across 10 families, plus 37 blocks that wire them to real on-device models. Like shadcn/ui, you install with the shadcn CLI and own the copied code, styled with shadcn/ui CSS variables so it inherits your theme. See the , , and .

The primitives are presentational and install with zero @localmode/* packages, so they work with any React AI app — the LocalMode hooks (on-device), the , or . Local-first by design, cloud-compatible by contract.

bash
# components.json → { "registries": { "@localmode": "https://localmode.ai/r/{name}.json" } }
npx shadcn@latest add @localmode/ui/conversation/message   # a single componentnpx shadcn@latest add @localmode/ui/conversation           # a whole familynpx shadcn@latest add @localmode/ui/all                    # the whole catalog
FamilyCountWhat it covers
24Chat shell, prompt input, reasoning, sources, tools, agent timelines, branches, citations
25Model download/selection, Hub search, capability gates, storage quota, cache status, VectorDB observability
12Confidence badges, scored result bars, similarity meters, evaluation dashboards, entity displays
11Char-limit rings, fill-mask inputs, mode pickers, parameter sliders, slash-command palettes
10Voice buttons/orbs, waveform bars, TTS voice pickers, streaming-speech panels, transcript viewers
7Image dropzones, bounding-box overlays, before/after viewers, webcam canvas, result galleries
5File dropzones, indexed-document cards, format badges, category facets, chunk visualizers
5Password-strength bar, differential-privacy controls, passphrase gate, vault item card, lock badge
4Docked canvas, sortable data tables, charts, code diffs — output rendered beside the chat
4Inference-queue monitor, event-log viewer, pipeline-run inspector, model-cache table

Blocks are complete experiences composed from the primitives — the wiring layer, and the only items that depend on @localmode/*. Each runs real models on-device and gates its download behind an explicit in-block action. Try them in the , then install with npx shadcn@latest add @localmode/ui/blocks/<category>/<block>.

CategoryBlocks
The flagship — streaming chat across 76 models and 4 providers, with vision, reasoning, agent mode, semantic caching, and custom GGUF URLs
semantic-search · document-qa · rag-chat · vector-data-manager — ingest text/PDF/OCR, rerank, ground answers with citations, import/export vectors
voice-notes · live-transcription · meeting-assistant · voice-explorer · audiobook-reader · audio-classifier
object-detector · live-tracker — DETR and BlazeFace detection, plus real-time hand / pose / face-mesh / gesture tracking
language-detector — 110-language detection and text-embedder similarity
device-report · model-advisor · gguf-explorer — capability report, ranked recommendations, and a 160K-model GGUF browser (zero download)
research-agent · data-extractor — a ReAct loop with human-in-the-loop tool approval, and schema-validated extraction rendered as artifacts
write · translate · summarize · complete — the Chrome Built-in AI ⇄ Transformers.js provider-fallback reference
sentiment-analyzer · text-classifier · model-evaluator · threshold-calibrator
smart-gallery · image-search · duplicate-finder · photo-categorizer — one CLIP model for both embeddings and zero-shot categorization
background-remover · image-enhancer · image-captioner
pii-redactor · encrypted-vault — on-device NER redaction with a differential-privacy demo, and a passphrase-locked AES-GCM vault

The 37th item, ui/blocks/devtools-drawer, is layout chrome rather than a gallery page: a six-tab observability drawer over @localmode/devtools, off by default and loaded only on first open. The 34 demo-app URLs from the previous localmode.ai site permanently redirect to the block that absorbed each one.


Quick Start

Semantic Search with Embeddings

bash
pnpm install @localmode/core @localmode/transformers
typescript
import { createVectorDB, embed, embedMany, chunk } from '@localmode/core';import { transformers } from '@localmode/transformers';
// Create embedding modelconst model = transformers.embedding('Xenova/bge-small-en-v1.5');
// Create vector database with typed metadataconst db = await createVectorDB<{ text: string }>({  name: 'docs',  dimensions: 384,});
// Chunk and embed documentsconst chunks = chunk(documentText, { size: 512, overlap: 50 });const { embeddings } = await embedMany({  model,  values: chunks.map((c) => c.text),});
// Store vectorsawait db.addMany(  chunks.map((c, i) => ({    id: `chunk-${i}`,    vector: embeddings[i],    metadata: { text: c.text },  })));
// Searchconst { embedding: query } = await embed({ model, value: 'What is AI?' });const results = await db.search(query, { k: 5 });

LLM Chat with Streaming

Four providers implement the same LanguageModel interface -- choose based on your needs:

bash
# WebGPU (fastest, 32 curated models)pnpm install @localmode/core @localmode/webllm
# WASM (universal browser support, 160K+ GGUF models)pnpm install @localmode/core @localmode/wllama
# ONNX (Transformers.js v4, same package as embeddings/vision/audio)pnpm install @localmode/core @localmode/transformers
# Google LiteRT-LM (.litertlm models, WebGPU — Gemma 4 E2B/E4B, Qwen3 0.6B)pnpm install @localmode/core @localmode/litert
typescript
import { streamText } from '@localmode/core';import { webllm } from '@localmode/webllm';import { wllama } from '@localmode/wllama';import { transformers } from '@localmode/transformers';import { litert } from '@localmode/litert';
// Pick any provider -- all implement the same LanguageModel interfaceconst model = webllm.languageModel('Llama-3.2-1B-Instruct-q4f16_1-MLC');       // WebGPU// const model = wllama.languageModel('Llama-3.2-1B-Instruct-Q4_K_M');          // WASM (GGUF)// const model = transformers.languageModel('onnx-community/Qwen3-0.6B-ONNX');  // ONNX// const model = litert.languageModel('gemma-4-E2B');                            // LiteRT (WebGPU)
const result = await streamText({  model,  prompt: 'Explain quantum computing simply',  maxTokens: 500,});
for await (const chunk of result.stream) {  process.stdout.write(chunk.text);}

Structured Output

typescript
import { generateObject, jsonSchema } from '@localmode/core';import { webllm } from '@localmode/webllm';import { z } from 'zod';
const { object } = await generateObject({  model: webllm.languageModel('Qwen3-1.7B-q4f16_1-MLC'),  schema: jsonSchema(    z.object({      name: z.string(),      age: z.number(),      interests: z.array(z.string()),    })  ),  prompt: 'Generate a profile for a software engineer named Alex',});

AI Agent with Tools

typescript
import { createAgent, defineTool, jsonSchema } from '@localmode/core';import { webllm } from '@localmode/webllm';import { z } from 'zod';
// defineTool() infers the parameter/result types so `execute`'s args are typedconst searchTool = defineTool({  name: 'search',  description: 'Search the knowledge base',  parameters: jsonSchema(z.object({ query: z.string() })),  execute: async ({ query }) => searchDB(query),});
const agent = createAgent({  model: webllm.languageModel('Qwen3-1.7B-q4f16_1-MLC'),  tools: [searchTool],  maxSteps: 5,});
const result = await agent.run({ prompt: 'Find documents about machine learning' });

React Hooks

typescript
import { useChat, useEmbed, useClassify } from '@localmode/react';import { transformers } from '@localmode/transformers';import { webllm } from '@localmode/webllm';
function ChatApp() {  const { messages, send, isStreaming } = useChat({    model: webllm.languageModel('Qwen3-1.7B-q4f16_1-MLC'),  });
  return <ChatUI messages={messages} onSend={send} loading={isStreaming} />;}

Real-Time Hand & Pose Tracking (MediaPipe)

typescript
import { detectHands } from '@localmode/core';import { mediapipe } from '@localmode/mediapipe';
// Single-frame: 21-point hand landmarksconst { hands } = await detectHands({  model: mediapipe.handLandmarker(),  image: imageBlob,});
// Real-time: 30-60fps tracking from a webcam video elementconst tracker = mediapipe.createHandTracker({  video: videoElement,  onResults: (hands) => drawLandmarks(hands),});await tracker.start();

Features

Core AI Functions

FeatureFunctionsDescription
Embeddingsembed(), embedMany(), streamEmbedMany()Text embeddings with streaming and batching
Multimodal EmbeddingsembedImage(), embedManyImages(), streamEmbedManyImages()CLIP-based text-image cross-modal search
Streaming LLMstreamText(), generateText()Streaming and complete text generation
Structured OutputgenerateObject(), streamObject()Typed JSON generation with Zod schema validation
Classificationclassify(), classifyZeroShot(), classifyMany()Sentiment, intent, topic classification
NERextractEntities()Named entity recognition
Rerankingrerank()Document reranking for improved RAG
Translationtranslate()Multi-language translation (20+ languages)
Summarizationsummarize()Text summarization
Question AnsweringanswerQuestion()Extractive QA with confidence scores
Fill-MaskfillMask()Masked token prediction (BERT-style)
OCRextractText()Optical character recognition
Document QAaskDocument(), askTable()Visual document and table understanding
Audiotranscribe(), synthesizeSpeech(), streamSynthesizeSpeech(), playStreamedSpeech(), classifyAudio()Speech-to-text, TTS (Kokoro -- 29 English voices, phonemizer-backed), streaming TTS with real-time playback, audio classification
Live TranscriptioncreateLiveTranscriber(), createTurnTaker()Real-time microphone transcription with VAD (Silero) and turn-based conversation
VisionclassifyImage(), captionImage(), detectObjects(), segmentImage(), imageToImage(), estimateDepth()Image processing and analysis
Landmarks & GesturesdetectHands(), detectPose(), detectFace(), detectFaceLandmarks(), recognizeGesture()Hand/pose/face landmark tracking and gesture recognition (MediaPipe)
Language DetectiondetectLanguage()Identify the language of text (110 languages)

Vector Database

FeatureFunctionsDescription
Vector DatabasecreateVectorDB()HNSW index, IndexedDB persistence, cross-tab sync, typed metadata
Semantic SearchsemanticSearch(), streamSemanticSearch()Query-time embed + search in one call
Vector QuantizationcreateVectorDB({ quantization })SQ8 (4x) and Product Quantization (8-32x compression)
Storage CompressioncreateVectorDB({ compression })SQ8 vector compression for 4x IndexedDB disk reduction
WebGPU Vector SearchcreateGPUDistanceComputer()WGSL compute shaders for batch distance computation
Hybrid SearchcreateHybridSearch(), reciprocalRankFusion()BM25 keyword + vector semantic search fusion

RAG & Pipelines

FeatureFunctionsDescription
Chunkingchunk(), semanticChunk(), codeChunk(), markdownChunk()Recursive, semantic, code-aware, and markdown chunking
Ingestioningest(), createIngestPipeline()End-to-end document ingestion with progress tracking
PipelinescreatePipeline()Composable multi-step workflows with 10 built-in step types
Inference QueuecreateInferenceQueue()Priority-based task scheduling with concurrency control
Semantic CachecreateSemanticCache()Cache LLM responses using embedding similarity
Import/ExportimportFrom(), exportToCSV(), exportToJSONL()Migrate vectors from Pinecone, ChromaDB, CSV, JSONL

Agents & Evaluation

FeatureFunctionsDescription
Agent FrameworkcreateAgent(), runAgent()ReAct loop with tool registry and VectorDB-backed memory
Evaluation SDKevaluateModel(), accuracy(), bleuScore(), ndcg()Classification, generation, and retrieval metrics with confusion matrix
Threshold CalibrationcalibrateThreshold(), getDefaultThreshold()Empirical similarity thresholds from corpus data
Model RegistryrecommendModels(), registerModel()Curated model catalog with device-aware recommendations
Adaptive BatchingcomputeOptimalBatchSize()Device-aware batch sizing for optimal throughput

Security & Privacy

FeatureFunctionsDescription
Encryptionencrypt(), decrypt(), deriveKey()Web Crypto API encryption, PBKDF2 key derivation
PII RedactionredactPII(), piiRedactionMiddleware()Named entity based PII detection and redaction
Differential PrivacydpEmbeddingMiddleware(), createPrivacyBudget()DP noise injection for embeddings and classification
Drift DetectioncheckModelCompatibility(), reindexCollection()Detect model changes, auto-reindex collections
Audit LogcreateAuditLog()Hash-chained, signed, append-only tamper-evident audit log (IndexedDB-backed)

Infrastructure

FeatureFunctionsDescription
Model CachecreateModelLoader()Chunked downloads, LRU eviction, cross-tab coordination, offline resume
StorageIndexedDBStorage, MemoryStorageBuilt-in persistent and in-memory storage
MiddlewarewrapEmbeddingModel(), wrapLanguageModel(), wrapVectorDB()Caching, logging, retry, validation, encryption, DP
CapabilitiesisWebGPUSupported(), detectCapabilities()Browser feature detection with automatic fallbacks
Cross-Tab SynccreateBroadcaster(), createLockManager()BroadcastChannel sync with Web Locks coordination
Network StatusgetNetworkStatus(), waitForOnline()Offline-first with network awareness

Demo Applications — the Blocks Gallery

See LocalMode running real models entirely in your browser at the (localmode.ai/blocks). The gallery ships 36 route-served blocks across 12 categories — full experiences assembled from the registry primitives ( plus the , , , , , , , , , , and category pages) plus the global-observability devtools-drawer chrome — each installable with npx shadcn@latest add @localmode/ui/blocks/<name>.

Full block descriptions, what each one covers, and install commands are in the @localmode/ui UI-registry section above (the authoritative block catalog).

Legacy localmode.ai/<slug> URLs permanently redirect to the corresponding block.


Architecture

┌──────────────────────────────────────────────────────────────────────────┐│                            Your Application                              │├──────────────────────────────────────────────────────────────────────────┤│                    @localmode/react  (64 React hooks)                    │├────────────────────────┬────────────────────────┬────────────────────────┤│  @localmode/langchain  │  @localmode/ai-sdk     │  @localmode/devtools   │├────────────────────────┴────────────────────────┴────────────────────────┤│                            @localmode/core                               ││                                                                          ││  VectorDB (HNSW + WebGPU)          Embeddings + Multimodal               ││  Agents & Pipelines                Evaluation + Metrics                  ││  Generation + Structured Output    Security (DP, PII, Crypto)            ││  Middleware System                 Import / Export                       │├──────────────────────────────────────────────────────────────────────────┤│                          Provider Packages                               ││                                                                          ││  @localmode/transformers         HuggingFace Transformers.js,            ││                                  26 model factories (ONNX)               ││  @localmode/webllm               WebGPU LLM inference, 32 models         ││  @localmode/wllama               GGUF via llama.cpp WASM, 30 curated     ││                                  + 160K+, streaming, JSON mode, rerank   ││  @localmode/litert               Google LiteRT-LM, .litertlm models      ││  @localmode/mediapipe            Google MediaPipe — landmarks, gestures  ││  @localmode/chrome-ai            Gemini Nano, browser-supplied           │├──────────────────────────────────────────────────────────────────────────┤│                            Browser APIs                                  ││                                                                          ││      WebGPU / WASM   ·  IndexedDB   ·  Web Workers   ·  Web Crypto       │└──────────────────────────────────────────────────────────────────────────┘

Design Principles

  1. Zero-Dependency Core -- @localmode/core has no external dependencies
  2. Provider Pattern -- ML frameworks are separate packages implementing core interfaces
  3. Function-First API -- Top-level async functions, not class methods
  4. Options Object Pattern -- Single options object for all functions
  5. Structured Results -- All functions return { result, usage, response }
  6. AbortSignal Everywhere -- Every async operation supports cancellation
  7. Middleware Composability -- Wrap embedding models, language models, and VectorDBs

LLM Provider Comparison

WebLLMWllamaTransformers.jsLiteRT
RuntimeWebGPUWASM (llama.cpp) + optional WebGPUONNX RuntimeLiteRT-LM (Google)
Models32 curated (MLC)30 curated + 160K+ GGUF from HuggingFace16 ONNX (TJS v4)3 verified (.litertlm)
SpeedFastest (GPU)Good (CPU), faster with WebGPUGood (CPU/GPU)Fast (WebGPU/CPU)
Embeddings--3 GGUF embedding modelsYes (many models)--
Reranking--2 reranker modelsYes (cross-encoder)--
Structured OutputYesYes (JSON mode / grammar)----
Reasoning--Yes (thinking mode)----
VisionPhi 3.5 VisionHolo2 4B/8B, Gemma 4 E2B/E4BQwen3.5, Gemma 4--
Tool CallingYesYes (via providerOptions)----
Browser SupportChrome/Edge 113+All modern browsersAll modern browsersChrome/Edge 113+
Best ForMaximum performanceUniversal compatibility, model variety, rerankingMulti-task (embeddings + LLM in one package)Google on-device models

Browser Compatibility

BrowserWebGPUWASMIndexedDBWorkersChrome AI
Chrome 80+113+YesYesYesYes
Edge 80+113+YesYesYesYes
Firefox 75+141+YesYesYesNo
Safari 14+26+YesYesPartialNo
  • Chrome AI: Gemini Nano supplied by the browser -- your app ships no model files (fallback to Transformers.js)
  • WebGPU: 3-5x faster inference (fallback to WASM)
  • IndexedDB: Persistent model/data storage (fallback to Memory)
  • Workers: Background processing for non-blocking UI

Documentation

Full documentation available at

TopicDocsREADME
Getting Started
Core Package
React Hooks
AI SDK Provider
Transformers Provider
WebLLM Provider
Wllama Provider
LiteRT Provider
MediaPipe Provider
Chrome AI Provider
LangChain Adapters
DevTools
PDF Extraction
Dexie Storage
IDB Storage
LocalForage Storage
UI Registry & Blocks (@localmode/ui)

Monorepo Structure

packages/  core/            # Zero-dependency core (functions, interfaces, VectorDB, agents, evaluation)  react/           # React hooks for all core functions (64 hooks + pipeline step factories)  ai-sdk/          # Vercel AI SDK provider  transformers/    # HuggingFace Transformers.js provider (26 model factories)  webllm/          # WebLLM provider (32 curated WebGPU models)  wllama/          # Wllama provider (GGUF via llama.cpp WASM, 30 curated + 160K+ models, streaming, JSON mode, reranking, reasoning, LoRA)  litert/          # LiteRT-LM provider (Google's WebGPU/WASM, .litertlm models)  mediapipe/       # MediaPipe Tasks provider (landmarks, gestures, vision/audio/text)  chrome-ai/       # Chrome Built-in AI provider (Gemini Nano)  langchain/       # LangChain.js adapters (embeddings, chat, vector store, reranker)  devtools/        # DevTools observability (/react hooks; widget UI deprecated)  pdfjs/           # PDF text extraction  dexie/           # Dexie.js storage adapter  idb/             # idb storage adapter  localforage/     # localForage storage adapterapps/  ui/              # @localmode/ui registry + blocks platform — the app-demo layer (localmode.ai; 36-block /blocks gallery across 12 categories + copy-owned UI primitives + Fumadocs)  docs/            # Documentation site (localmode.dev)

Privacy Guarantees

  • No telemetry -- We don't track anything
  • No network requests -- Core package makes zero network calls
  • Data stays local -- All processing happens in your browser
  • Differential privacy -- Optional DP noise injection for embeddings and classification
  • Encryption -- Built-in AES-GCM encryption via Web Crypto API
  • PII redaction -- Automatic detection and redaction of sensitive data
  • Open source -- Audit the code yourself

Acknowledgments

LocalMode is built on top of incredible open-source projects:

LibraryUsed byDescription
by HuggingFace@localmode/transformersState-of-the-art ML models in the browser via ONNX Runtime
by MLC AI@localmode/webllmHigh-performance LLM inference with WebGPU
by ngxson / by Georgi Gerganov@localmode/wllamaGGUF model inference via llama.cpp compiled to WASM
by Google AI Edge@localmode/litertGoogle's on-device LLM inference engine for browser (WebGPU/WASM, .litertlm models)
by Google AI Edge@localmode/mediapipeOn-device hand/pose/face landmark tracking, gesture recognition, and vision/audio/text tasks via WASM
by LangChain@localmode/langchainFramework for building LLM-powered applications
by Vercel@localmode/ai-sdkUniversal AI SDK for TypeScript
by Mozilla@localmode/pdfjsPDF rendering and text extraction
by David Fahlander@localmode/dexieIndexedDB wrapper with schema versioning and transactions
by Jake Archibald@localmode/idbTiny Promise-based IndexedDB wrapper
by Mozilla@localmode/localforageCross-browser storage with automatic fallback
by Google@localmode/chrome-aiOn-device AI APIs powered by Gemini Nano

Reporting Issues

Found a bug or unexpected behavior? and include:

  • A clear description of the problem
  • Steps to reproduce
  • Expected vs actual behavior
  • Browser name and version
  • Relevant error messages or console output
  • A minimal code snippet or reproduction if possible

Contributing

Contributions are welcome! See for setup, the architecture rules, our testing standards, and the pull-request checklist.

Changelog

See for a list of notable changes.

License

Built for Privacy. Designed for Developers. Powered by the Browser.