Skip to content

AI9 min read

How I Run a Local LLM in the Browser with WebGPU

How I built on-device AI with WebLLM and WebGPU: Qwen3 in a Web Worker, shader-f16 checks, streaming, cached weights and a quality gate. No server or API key.

I run a real language model inside the browser with WebLLM and WebGPU. The model (Qwen3, 1.7B or 4B) downloads once, runs on the visitor's own GPU in a Web Worker, and streams text back like a chat API, with no server and no API key. It powers the on-device writing in my TikTok and Facebook post generator, and this post walks through exactly how I built it.

Key takeaways

  • WebLLM gives you an OpenAI-style chat.completions.create() that runs on WebGPU. My whole "backend" is static files.
  • Run the engine in a Web Worker. Downloading, compiling and generating would otherwise freeze the page.
  • Check navigator.gpu.requestAdapter() and the shader-f16 feature, then pick the model build the GPU can run.
  • The weights are big (about 1 GB to 2.3 GB here). Ask before downloading, download once, and let the browser cache them.
  • Small models need guard rails: clean the output, check it in code, and keep the first draft if the AI version is worse.

Why I wanted the AI on the device

My site is a static site on Vercel with no backend, and I wanted to keep it that way. A hosted LLM API would have meant a server route, an API key to protect, a bill that grows with every visitor, and sending people's post ideas to a third party.

Running the model in the browser removes all of that. The visitor's GPU does the work, so there is no per-request cost for me. Nothing they type leaves their device. And the tool keeps working the same way whether ten people use it or ten thousand. The trade-off is a large one-time download and a dependency on WebGPU, so I designed around both.

How the pieces fit together

There are four parts:

  1. The page (social.js) owns the UI: the chat, the post panel and a progress bar.
  2. A module Web Worker (social-ai-worker.js) loads WebLLM and the model, and does all the generating.
  3. A prompt builder (aiMessages()) turns the user's brief into chat messages.
  4. A cleaner and a quality gate (cleanAi() and aiQuality()) decide whether the model's text is good enough to show.

The page and the worker only talk through postMessage. That keeps the main thread free to paint progress and streamed text, even while the GPU is busy.

Step 1: check for WebGPU and pick the right model build

WebGPU is not everywhere yet, so the first thing I do is ask for an adapter. If there is none, the AI option stays hidden and the normal template writer does the job.

JavaScript
const webgpu = async () => {
  if (!('gpu' in navigator)) return null;
  try { return await navigator.gpu.requestAdapter(); } catch { return null; }
};

const adapter = await webgpu();
if (!adapter) throw new Error(NO_GPU);
// q4f16 builds need the shader-f16 feature; q4f32 builds run on any WebGPU adapter.
const model = `${base}-${adapter.features.has('shader-f16') ? 'q4f16_1' : 'q4f32_1'}-MLC`;

base is Qwen3-4B or Qwen3-1.7B, so the final id is something like Qwen3-4B-q4f16_1-MLC. Those ids come from WebLLM's prebuilt model list. Asking for an f16 build on a GPU without shader-f16 fails at load time, so checking first saves the user a confusing error after a long download.

Step 2: load WebLLM in a Web Worker

The worker imports WebLLM from a pinned version on jsDelivr and creates the engine. I pin the exact version because the model list and APIs change between releases.

JavaScript
// social-ai-worker.js (module worker)
const VERSION = '0.2.86';
const LIB = `https://cdn.jsdelivr.net/npm/@mlc-ai/web-llm@${VERSION}/+esm`;

let engine;
let loadedModel = '';

const load = async (model) => {
  if (engine && loadedModel === model) return;
  const { CreateMLCEngine } = await import(LIB);
  if (engine) await engine.reload(model); // switch models on the same engine
  else engine = await CreateMLCEngine(model, { initProgressCallback: onProgress });
  loadedModel = model;
};

The page creates the worker with new Worker(url, { type: 'module' }). Two details mattered in practice:

  • Loads are serialized. If the user picks one model and then another, I chain the second load after the first instead of running two downloads side by side. Two parallel multi-gigabyte loads can easily run a laptop GPU out of memory.
  • Progress is throttled. WebLLM reports progress many times a second. I forward at most one update every 120 ms, because every message costs the page a render.
JavaScript
let lastProgress = 0;
const onProgress = (p) => {
  const now = performance.now();
  if (p.progress < 1 && now - lastProgress < 120) return;
  lastProgress = now;
  self.postMessage({ type: 'progress', progress: p.progress, text: p.text });
};

Step 3: stream tokens back to the page

Generating text uses the same shape as the OpenAI chat API, which made it feel familiar straight away. With stream: true you get an async iterator of chunks.

JavaScript
const stream = await engine.chat.completions.create({
  messages,
  stream: true,
  temperature: 0.7,
  top_p: 0.8,
  frequency_penalty: 0.3,
  presence_penalty: 0.5,
  max_tokens: platform === 'tiktok' ? 220 : 420,
  extra_body: { enable_thinking: false }, // Qwen3: answer directly, no reasoning block
});

let text = '';
let last = 0;
for await (const chunk of stream) {
  text += chunk.choices[0]?.delta?.content || '';
  const now = performance.now();
  if (now - last > 90) { last = now; self.postMessage({ type: 'token', id, text }); }
}
self.postMessage({ type: 'done', id, text });

Qwen3 can "think" before it answers. For a short social post that only adds delay, so I turn it off with extra_body: { enable_thinking: false }. I send the whole text so far (not single tokens) about every 90 ms. The page simply replaces the textarea content, so the post appears to type itself without flooding the main thread.

Step 4: write a prompt a small model can follow

A 1.7B or 4B model is far more literal than a large hosted model. What worked for me:

  • A short, numbered shape. First line a hook under the platform's fold, then a few specific lines, then exactly one call to action.
  • Hard rules about facts. Use every fact the user gave. Never invent prices, discounts, dates, addresses, phone numbers, names or reviews.
  • One worked example. I include a single example brief and its finished post before the real request. One example taught the format better than another paragraph of rules.
  • A starter draft. My template engine writes a plain first draft, and the prompt asks the model to improve it. Giving the model something concrete to rewrite keeps it on topic.

Step 5: clean the output and refuse bad rewrites

This is the part that made the feature trustworthy. Small models sometimes repeat the instructions, add labels like "Caption:", leave a stray <think> block, or invent a discount. So the text goes through two functions before the user sees it as final.

cleanAi() strips reasoning blocks, hashtags (my own tool adds checked ones), labels, markdown, echoed instructions, repeated lines and extra emoji.

aiQuality() then decides whether the rewrite may replace the draft. It rejects output that:

  • is too short or rambles on too long for the platform,
  • is full of stray symbols,
  • never mentions the topic,
  • contains a price, percentage or phone number that was not in the user's brief,
  • copies the worked example,
  • scores clearly lower (by more than 15 points) than the first draft on my post checker.
JavaScript
const q = aiQuality(text, platform, { topic, draft, extra: [points, location, cta, audience] });
area.value = q.ok ? withHashtags(text, tags) : draft; // never leave a junk rewrite in place

If a rewrite fails, the user keeps the first draft and sees why in plain words, such as "it made up a price, discount or number". When a rewrite succeeds, an Undo AI rewrite button brings the draft back. The model is allowed to add general knowledge about the topic, which is what makes the AI version better. It is not allowed to make claims about the user's business.

Step 6: handle the big download politely

A 1 GB to 2.3 GB download is fine on home Wi-Fi and terrible on mobile data, so I treat it as the user's decision:

  • Ask first. The first time, the assistant asks which model to use, "Best writing" (Qwen3 4B, about 2.3 GB) or "Faster" (Qwen3 1.7B, about 1 GB), or "Not now". The choice is remembered.
  • Respect Save-Data. If the browser reports navigator.connection.saveData, automatic AI is off.
  • Start early once allowed. After someone has picked a model, I start loading it as soon as they type a topic, so it is often ready by the time they finish answering the questions.
  • Download once. WebLLM stores the weights in the browser's Cache Storage by default, so a returning visitor skips the download and only waits for the model to load onto the GPU.

Errors get the same treatment. Raw WebGPU errors mean nothing to most people, so I map them to plain messages: no WebGPU in this browser, the download was interrupted, or the GPU ran out of memory and the smaller model might fit. In every case the posts written without AI are still there and ready to copy.

WebGPU vs WebAssembly: when I use which

Not every on-device model on my site uses WebGPU. My free background remover runs an ISNet segmentation model with ONNX Runtime on WebAssembly instead, because a single image segmentation runs fine on the CPU and WebAssembly works in more browsers. To make it fast I run it in a Web Worker and serve that one page with cross-origin isolation headers, which lets ONNX Runtime use every CPU core. In my test on a 12-thread machine, the first cutout dropped from about 13 seconds to about 6.

My rule of thumb: a language model that generates hundreds of tokens needs a GPU, so it gets WebGPU. A one-shot vision model can often stay on WebAssembly, where it reaches more people. I wrote more about how the background remover works in how to remove a background from an image for free.

What I would tell you before you try it

  • Start with the smallest model that does the job. The size of the download decides whether people wait for it.
  • Keep a non-AI path. Plenty of visitors will not have WebGPU. My tool writes a good post without AI, and the model only improves it.
  • Test on a weak GPU. Out-of-memory errors show up on laptops long before they show up on a desktop graphics card.
  • Check the output in code, not just in the prompt. Prompt rules reduce mistakes. Code checks catch the rest.

If you would rather call a hosted model from a server, I covered that approach in building an AI chatbot in Next.js with streaming. For my free tools, keeping the AI on the device was the better trade, and it fits how I build tools that never upload your files.

FAQ

Can you run an LLM in the browser without a server?

Yes. With WebLLM, the model weights download to the browser and run on the visitor's own GPU through WebGPU. There is no inference server and no API key. The page only needs to be served as static files.

Which browsers support WebGPU for local AI?

Recent Chrome and Edge on desktop support WebGPU, and support on other browsers and on phones keeps changing. I never assume it is there: I call navigator.gpu.requestAdapter() and fall back to a normal, non-AI path when it returns nothing.

How big is a local LLM download?

It depends on the model. In my post generator, Qwen3 4B is about 2.3 GB and Qwen3 1.7B is about 1 GB, both 4-bit quantized. The download happens once, then WebLLM keeps the weights in the browser's Cache Storage.

What is shader-f16 and why does it matter?

shader-f16 is a WebGPU feature that lets shaders use 16-bit floats. WebLLM ships q4f16 builds that need it and q4f32 builds that do not. I check adapter.features.has('shader-f16') and load the build the GPU can actually run.

How do you stop a small local model from making things up?

I tell it not to invent prices, dates or contact details, then I check the output in code. A rewrite that adds a price or number the user never gave, drifts off topic or scores worse than the first draft is thrown away, and the user keeps the draft.

Wrapping up

Running an LLM in the browser is practical today. WebLLM handles the hard parts: compiling the model for WebGPU, caching the weights and exposing a familiar chat API. My job was everything around it: a worker so the page stays smooth, a check for the right GPU features, a polite download, and code that refuses bad output. You can try the result in my TikTok and Facebook post generator. Pick a model in the chat and watch the post write itself on your own GPU.

  • #AI
  • #WebGPU
  • #JavaScript
  • #Performance
  • #Tools