Small models in the browser, the chat model on your machine

9 min read
ollamahuggin-facetansformers.jsOpenAI Whisper

"Local LLM" gets used for two different setups. They solve different problems, and mixing them up is how people end up downloading a 4 GB chat model into a tab.

One setup runs inside the browser. The model files download once, the browser caches them, and the text or audio never goes to your server for that step. This is the part worth copying. The jobs are small: hide secrets before a message is sent, underline grammar mistakes while someone types, and turn speech into text when the app has words a normal speech engine will miss.

The other setup runs on a server you own. In this repo that server is Ollama, plus a small Node API and Postgres. It is a nice way to try the whole chat on one machine. Ollama is a local runner. It is a fun end-to-end experiment. For a real deployment with more than one user, you want a serving stack built for that, and this post does not pretend otherwise.

What the browser is doing

On first load the page starts four models in web workers. A worker is a background thread, so a download or a slow pass does not freeze the text box. The four are speech, a grammar checker, a title generator for the sidebar, and a safety classifier. The three that change how the product feels are masking, grammar, and voice.

Masking is not a model. It is a scanner that runs on the main thread before anything is sent. Grammar and speech are models, loaded with Transformers.js.

The repo uses @huggingface/transformers 3.5. The docs linked below are the v3 docs, which match that API. Transformers.js v4 is a newer line; the code here is the v3 pipeline() style.

Setup

You need Node 22 or newer, and a Chromium browser. Chrome 113 and later can use WebGPU for speech. If WebGPU fails, speech falls back to WASM.

The shortest path is Docker. From the repo root:

cp .env.example .env
docker compose up --build

Open http://localhost:8080. The first start pulls the Ollama chat model and the embedding model, so give it a few minutes.

Without Docker, start Postgres (with pgvector) and Ollama yourself, then:

cd core
cp .env.example .env
npm install
npm run db:migrate
npm run dev
cd frontend
npm install
npm run dev

The UI is at http://localhost:5173. The API is at http://localhost:3210.

Two server headers matter, and they are easy to forget. ONNX Runtime's WASM build uses threads, and threads need SharedArrayBuffer. Browsers only hand that out on a cross-origin isolated page:

headers: {
  "Cross-Origin-Opener-Policy": "same-origin",
  "Cross-Origin-Embedder-Policy": "require-corp",
}

Vite sets those in dev. nginx sets them when you run Docker. If you drop the frontend onto a host that does not send both headers, the WASM models load slowly or fail, and self.crossOriginIsolated is false. ONNX Runtime Web's notes on this are in the env flags guide.

Also tell Vite to leave Transformers.js alone. It ships as ESM, and pre-bundling it causes more pain than it saves:

optimizeDeps: {
  exclude: ["@huggingface/transformers"],
}

Transformers.js, in a worker

pipeline() is the whole idea. You name a task and a model id. The library downloads the ONNX weights from the Hugging Face Hub, caches them in the browser, and gives you a function to call. The pipeline docs list the tasks. Where the files come from is the env object: remote Hub by default, or a folder you host yourself. The custom models page shows env.localModelPath and env.allowRemoteModels.

Each model lives in its own worker. The UI thread only posts a message and waits for a reply. Hugging Face's React tutorial is the same shape. Vite has a requirement on top: the new Worker(new URL(...)) call has to be written out literally, or the worker is not bundled as its own file. That is covered in Vite's worker docs.

const workers = {
  asr: new Worker(new URL("../workers/asrWorker.ts", import.meta.url), { type: "module" }),
  grammar: new Worker(new URL("../workers/grammarWorker.ts", import.meta.url), { type: "module" }),
};

Inside the speech worker, the load looks like this. fp16 on WebGPU, q8 on WASM. If WebGPU throws, it tries WASM once.

import { pipeline, env } from "@huggingface/transformers";

env.allowLocalModels = false;

const transcriber = await pipeline(
  "automatic-speech-recognition",
  "onnx-community/whisper-base.en",
  {
    device: "webgpu",
    dtype: {
      encoder_model: "fp16",
      decoder_model_merged: "fp16",
    },
  },
);

const result = await transcriber(audio);

device: "webgpu" is the switch from the WebGPU guide. WASM is the path when that GPU init fails. The first download is about 160 MB on WebGPU and about 80 MB on WASM. After that, the Cache API keeps the files.

To point speech at your own ONNX export, set VITE_ASR_MODEL_ID. Set VITE_ASR_LOCAL_MODELS=true and put the files under frontend/public/models/<id>/ if you do not want the Hub. A local folder needs config.json, the encoder and decoder ONNX files, and the tokenizer. Vite inlines VITE_* at build time, so change them and rebuild.

Mask secrets before the message leaves

People paste keys into chat boxes. A regex pass is the right tool for that. AWS keys, GitHub tokens, Slack tokens, JWTs, KEY=value secrets, emails, US social security numbers, phone numbers, and card numbers (checked with the Luhn test) are patterns. A classifier will miss a well-formed token and will also flag harmless text.

The scan runs in the browser, on the text that is about to be sent. The model and the server see the masked string. The UI names what it hid.

export function maskCredentials(text: string) {
  let masked = text;
  const found: string[] = [];

  masked = masked.replace(/\bAKIA[0-9A-Z]{16}\b/g, () => {
    found.push("AWS Access Key");
    return "[REDACTED:AWS Access Key]";
  });

  // same loop for the other patterns, then phone numbers and Luhn-checked cards
  return { masked, found };
}

The real scanner covers more shapes than that snippet, including password=, Bearer tokens, and private-key blocks. It does not try to find names or street addresses. Those are not reliable as patterns, and a wrong redaction in the middle of a sentence is worse than leaving a name in a message the user chose to send.

There is a second check after the mask: a small ONNX build of Llama Prompt Guard (gravitee-io/Llama-Prompt-Guard-2-86M-onnx) scores the text for prompt injection. A score of 0.6 or higher, with the label MALICIOUS, blocks the send. If that model errors, the send still goes out, because the secrets are already masked. Blocking a normal sentence is more annoying than missing one odd prompt.

Grammar, in the box, as you type

The checker is Xenova/t5-base-grammar-correction, a text-to-text model. It runs on WASM at q8. The composer waits 600 ms after the last keystroke, and it skips anything shorter than 8 characters.

The worker sends the draft in, gets a corrected string back, and diffs the two by word. The spans become underlines. Clicking one replaces that span. "Fix all" applies them from the end of the string backward, so earlier indexes stay valid.

import { pipeline } from "@huggingface/transformers";

const generator = await pipeline(
  "text2text-generation",
  "Xenova/t5-base-grammar-correction",
  { device: "wasm", dtype: "q8" },
);

const result = await generator(text, { max_new_tokens: 128 });
const corrected = result[0].generated_text;

T5 has a short context. The worker splits long drafts on sentence boundaries and only runs a few batches per pass, so one huge paste does not blow the WASM heap. Corrections are suggestions. The original text stays until the user accepts a fix.

Voice, and when your own model is worth it

For most apps, use the browser's speech engine. The Web Speech API is a few lines, it knows general English, and you do not ship an 80 MB model. Chrome's default still sends audio to a recognition service, which MDN states plainly. On-device recognition (processLocally) exists and is still marked experimental. Read that page before you promise "audio never leaves the device" via this API.

Whisper in the page is the other choice, and it is the one this repo ships. Reach for it when the product has its own vocabulary: product names, abbreviations, ticket ids, words the stock engine will rewrite into something common. You can fine-tune Whisper on your audio, export ONNX, and load that export through VITE_ASR_MODEL_ID. The fine-tune pipeline for whisper-base-en-ewc-v1 lives in a separate repo. This one only runs the exported model.

The mic uses getUserMedia and MediaRecorder. On stop, the blob is decoded to a Float32Array and transferred into the worker (the buffer is moved, not copied). Whisper returns text. That text lands in the composer. Nothing is sent until the user sends it, so they can fix a bad word first.

const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const recorder = new MediaRecorder(stream);

recorder.addEventListener("stop", async () => {
  const blob = new Blob(chunks, { type: chunks[0].type });
  const audio = await blobToFloat32(blob);
  worker.postMessage({ type: "transcribe", audio }, [audio.buffer]);
});

Default model: onnx-community/whisper-base.en. English only, base size. It is a reasonable trade for a chat box. It will still mangle rare words until you swap in a model trained on them.

The server on your own machine

The chat reply itself comes from core/, an Express API. With Docker, nginx serves the UI and proxies /api/ to that process, so the browser talks to one origin.

Ollama serves the chat model (erwan2/DeepSeek-R1-Distill-Qwen-1.5B unless you change it) and the embedding model (nomic-embed-text). Postgres stores conversations. pgvector stores short memories the agent can search. An Exa key lets a researcher sub-agent look things up on the web. You can point the chat model at Anthropic instead, with MODEL_PROVIDER=anthropic. Embeddings still go through Ollama.

That stack is how you click around and see a full chat without a hosted model. Keep it in that role. Ollama on a laptop is one process, one GPU, no story for many users, upgrades, or abuse. When this leaves your machine, replace that piece. The browser models can stay. They were the point.

Docs used here

All posts