DEV Community

Diogo Soares
Diogo Soares

Posted on Edited on

I Ran AI Offline Inside Chrome: No Ollama, No API Key

I turned off the Wi-Fi on a Windows laptop, typed a question into a page in Chrome, and the first words of the answer came back in 0.6 seconds.

No Ollama. No Python. No API key. No inference server. The model was running inside the browser itself, on the laptop's own hardware.

There are two ways to run AI offline in Chrome today, and they answer different needs. One uses Gemini Nano, the model Chrome manages and downloads on demand, through a few lines of JavaScript. The other lets you pick an open model (Llama, Qwen, Gemma, Phi) and run it on the GPU through WebGPU, with a library called WebLLM.

This post covers:

  1. The numbers I got on a Windows laptop with both approaches.
  2. A step-by-step guide to Gemini Nano, from the DevTools console.
  3. A step-by-step guide to running your own model with WebLLM, in a page you build in five minutes.
  4. A bug in my own test page that taught me not to trust navigator.onLine.
  5. Where this fits in a real product, and when it's the wrong tool.

The results first

I built a small test page that runs both engines and measures them the same way: wall-clock time seen by the page, with one fixed prompt ("Explain dependency injection in about 150 words and finish with a short TypeScript example").

Engine and model Ready First visible text Answer time Output speed
Gemini Nano (built into Chrome) 4.2 s (already on disk) 0.63 to 0.66 s 16 to 18 s 17 to 19 tokens/s
Gemma 4 E2B (WebLLM), first answer 92 s (download + load) 17.7 s 52.5 s 9.4 tokens/s
Gemma 4 E2B (WebLLM), next answers already loaded 0.29 to 0.30 s 27 to 32 s 10.6 to 11.1 tokens/s

The machine: a Windows laptop with 32 GB of RAM, AMD Radeon graphics (RDNA 3, reported by WebGPU), Windows and Chrome 158. I ran three benchmark runs per engine while switching the Wi-Fi on, off and on again. The page didn't record which run was which (more on that below), but all of them landed in the ranges above. Full method further down.

Two things stood out. On this laptop, Chrome's own model was about 1.7 times as fast as the open model I picked (in characters per second, which doesn't depend on the tokenizer). And the slow first answer from Gemma happened only once: the first answer right after the download waited 17.7 seconds for its first word, and the two answers after it started in 0.3 seconds. I didn't isolate the cause, so I'll only call it a one-time warm-up cost.

The two numbers also pull in different directions. Once warmed up, Gemma started answering more than twice as fast as Nano (0.3 s against 0.65 s), but Nano finished the full answer sooner because it generated text faster. For a chat, time to first text is what feels fast; for a long summary, generation speed is what you wait for.


Two ways to run AI offline in Chrome

The difference is who owns the model.

Gemini Nano (Prompt API) WebLLM
Who downloads the model Chrome, which manages it (not each site) Your page, once per origin
Can you choose the model No Yes, from the models compiled for WebLLM: Llama, Qwen, Gemma, Phi, SmolLM and more
Library needed None @mlc-ai/web-llm
Runs on GPU, or CPU on machines with enough RAM GPU, through WebGPU
API style LanguageModel.create(), session.prompt() OpenAI-style chat.completions.create()
Mobile Not supported Depends on the device's WebGPU support

If you only need a capable small model and your users are on desktop Chrome, Gemini Nano is the shortest path. If you need a specific model, support beyond Chrome, or control over which model version your users run, WebLLM is the one.

Neither is "installing a model in Chrome" in the sense of replacing Nano. Chrome's built-in slot only takes Gemini Nano. Every other model lives in the storage of the page that downloaded it.


Step by step: Gemini Nano from the DevTools console

The Prompt API is available to regular web pages from Chrome 148, and to extensions from Chrome 138 (the docs' feature table, last updated October 2026).

1. Check your machine. The hardware requirements are stricter than most people expect:

  • Windows 10 or 11, macOS 13 or newer, Linux, or a Chromebook Plus. No Android or iOS.
  • At least 22 GB of free space on the drive that holds your Chrome profile. The model itself is much smaller, but Chrome checks for that space before downloading, and removes the model if free space drops below 10 GB.
  • A GPU with strictly more than 4 GB of VRAM, or, for the CPU path, 16 GB of RAM and at least 4 CPU cores.
  • An unmetered connection for the first download.

2. Check your Chrome version. Open chrome://settings/help and update to 148 or newer. I had Chrome flags turned on when I first tested it; on Chrome 148 and later, the docs mention no flag for web pages.

3. Open DevTools on any HTTPS page (F12, then the Console tab) and ask whether the model is there:

await LanguageModel.availability();
// "available" | "downloadable" | "downloading" | "unavailable"
Enter fullscreen mode Exit fullscreen mode

In real code, pass the same options you'll use in create() (for example expectedInputs: [{ type: "text", languages: ["en"] }]), because the answer can depend on them.

4. If it says "downloadable", trigger the download with a click. Chrome only starts the download from a real user interaction. In the console, attach the call to the next click on the page, then click anywhere on it:

document.addEventListener("click", async () => {
  const session = await LanguageModel.create({
    monitor(monitor) {
      monitor.addEventListener("downloadprogress", (event) => {
        console.log(`Downloaded ${Math.round(event.loaded * 100)}%`);
      });
    },
  });
  console.log(await session.prompt("Say hello in five words."));
}, { once: true });
Enter fullscreen mode Exit fullscreen mode

If it stays at "unavailable", open chrome://on-device-internals: it shows the model state and any error, usually a hardware or disk requirement.

5. Prompt it. Once availability() says available:

const session = await LanguageModel.create();
console.log(await session.prompt("Explain dependency injection in two sentences."));
Enter fullscreen mode Exit fullscreen mode

For a chat interface you want the streaming version, which hands you the text as it is generated:

for await (const chunk of session.promptStreaming("Write a haiku about caching.")) {
  console.log(chunk);
}
Enter fullscreen mode Exit fullscreen mode

6. Turn off the Wi-Fi and prompt again. The same session keeps answering. The session keeps the conversation context, so a second prompt() call can refer to the first answer. Call session.destroy() when you're done to free memory.

Languages are limited: the Prompt API docs list English, Japanese, Spanish, German and French.


Step by step: run your own model with WebLLM

WebLLM describes itself as an in-browser LLM inference engine, accelerated with WebGPU, with "no server support" needed and an API that follows OpenAI's chat completions format. You give it a model ID, it downloads the weights from Hugging Face and keeps them in the browser's Cache API.

It runs the models that were compiled for it, not any file from Hugging Face. These are some of the prebuilt ones in WebLLM 0.2.88, with the GPU memory WebLLM's own config estimates for each 4-bit build:

Model Model ID (q4f16 build) Estimated GPU memory
Llama 3.2 1B Llama-3.2-1B-Instruct-q4f16_1-MLC 0.9 GB
Qwen3.5 0.8B Qwen3.5-0.8B-q4f16_1-MLC 1.6 GB
Qwen3.5 2B Qwen3.5-2B-q4f16_1-MLC 2.2 GB
Gemma 4 E2B gemma-4-E2B-it-q4f16_1-MLC 3.4 GB
Phi 3.5 mini Phi-3.5-mini-instruct-q4f16_1-MLC 3.7 GB
Qwen3.5 4B Qwen3.5-4B-q4f16_1-MLC 3.9 GB

The q4f16 builds need a GPU that supports 16-bit floats in shaders (shader-f16 in WebGPU). Without it, use the q4f32 build of the same model (every model in the table has one: swap q4f16_1 for q4f32_1 in the ID), which needs more GPU memory: Phi 3.5 mini goes from 3.7 to 5.5 GB. The full list lives in prebuiltAppConfig.model_list inside the package.

You need Node.js 20.19 or newer (for Vite 8) and Chrome with WebGPU. The commands are the same on Windows, macOS and Linux.

1. Create the project and install two packages:

mkdir offline-ai && cd offline-ai
npm init -y
npm install --save-exact vite@8.3.8 @mlc-ai/web-llm@0.2.88
Enter fullscreen mode Exit fullscreen mode

Vite is only there to serve the page on localhost and resolve the import. WebLLM is the inference engine.

2. Create index.html:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Offline AI in Chrome</title>
    <link rel="stylesheet" href="/style.css" />
  </head>
  <body>
    <main class="app">
      <header>
        <h1>Offline AI <span>in Chrome</span></h1>
        <p class="chip">● Runs on your GPU · no API key · works offline</p>
      </header>
      <section class="loader">
        <button id="load">Load model</button>
        <div class="bar"><div id="bar-fill"></div></div>
        <p id="status">The first load downloads the model. After that, it works offline.</p>
      </section>
      <section id="messages" class="messages"></section>
      <form id="chat">
        <input id="prompt" placeholder="Ask something..." autocomplete="off" disabled />
        <button disabled>Send</button>
      </form>
    </main>
    <script type="module" src="/main.js"></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

3. Create style.css. It's optional (the page works without it), but it turns a bare form into a small chat app with a progress bar, the same one you see in the screenshots:

style.css (25 lines)
:root { --bg: #0a0a0a; --panel: #141414; --line: #262626; --text: #f0f0f0;
  --muted: #8a8a8a; --lime: #e8f542; --mint: #42f5a1; }
* { box-sizing: border-box; }
body { margin: 0; min-height: 100vh; background: radial-gradient(circle at 80% 0%, #e8f54222, transparent 40%), var(--bg);
  color: var(--text); font: 16px/1.5 system-ui, sans-serif; }
.app { max-width: 760px; margin: 0 auto; padding: 32px 16px; display: grid; gap: 20px; }
h1 { margin: 0; font-size: 2rem; letter-spacing: -0.03em; }
h1 span { color: var(--lime); }
.chip { display: inline-block; margin: 8px 0 0; padding: 4px 12px; border: 1px solid var(--line);
  border-radius: 999px; color: var(--mint); font-size: 0.85rem; }
.loader { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 16px; }
.bar { height: 8px; margin: 14px 0 8px; background: #222; border-radius: 99px; overflow: hidden; }
#bar-fill { width: 0; height: 100%; background: linear-gradient(90deg, var(--mint), var(--lime)); transition: width .3s; }
#status { margin: 0; color: var(--muted); font-size: 0.9rem; }
.messages { display: grid; gap: 12px; }
.bubble { max-width: 85%; padding: 12px 16px; border-radius: 16px; white-space: pre-wrap; }
.user { justify-self: end; background: #232833; border-bottom-right-radius: 4px; }
.ai { background: var(--panel); border: 1px solid var(--line); border-bottom-left-radius: 4px; }
.stats { margin-top: 8px; color: var(--lime); font: 0.78rem ui-monospace, monospace; }
form { display: flex; gap: 8px; }
input { flex: 1; padding: 12px 14px; background: var(--panel); color: var(--text);
  border: 1px solid var(--line); border-radius: 10px; font: inherit; }
button { padding: 12px 18px; background: var(--lime); color: #0a0a0a; border: 0;
  border-radius: 10px; font-weight: 700; cursor: pointer; }
button:disabled { opacity: 0.35; cursor: default; }
Enter fullscreen mode Exit fullscreen mode

4. Create main.js:

import { CreateMLCEngine } from "@mlc-ai/web-llm";

const MODEL_ID = "Llama-3.2-1B-Instruct-q4f16_1-MLC";
const $ = (selector) => document.querySelector(selector);
let engine;

$("#load").addEventListener("click", async () => {
  $("#load").disabled = true;
  engine = await CreateMLCEngine(MODEL_ID, {
    initProgressCallback: (report) => {
      $("#bar-fill").style.width = `${Math.round(report.progress * 100)}%`;
      $("#status").textContent = report.text;
    },
  });
  $("#status").textContent = `${MODEL_ID} is ready. Turn off the Wi-Fi and ask something.`;
  document.querySelectorAll("#chat [disabled]").forEach((el) => (el.disabled = false));
});

$("#chat").addEventListener("submit", async (event) => {
  event.preventDefault();
  const question = $("#prompt").value.trim();
  if (!question) return;
  $("#prompt").value = "";
  addBubble("user", question);
  const answer = addBubble("ai", "");
  const started = performance.now();
  let firstTextAt;
  const stream = await engine.chat.completions.create({
    messages: [{ role: "user", content: question }],
    stream: true,
  });
  for await (const chunk of stream) {
    const text = chunk.choices[0]?.delta?.content ?? "";
    firstTextAt ??= text ? performance.now() : undefined;
    answer.textContent += text;
  }
  const seconds = (performance.now() - firstTextAt) / 1000;
  const stats = addBubble("stats", `first text ${((firstTextAt - started) / 1000).toFixed(2)} s · ` +
    `${Math.round(answer.textContent.length / seconds)} chars/s · on this device`);
  answer.append(stats);
});

function addBubble(kind, text) {
  const element = document.createElement("div");
  element.className = kind === "stats" ? "stats" : `bubble ${kind}`;
  element.textContent = text;
  if (kind !== "stats") $("#messages").append(element);
  return element;
}
Enter fullscreen mode Exit fullscreen mode

The initProgressCallback drives the progress bar while the weights download. The chat part uses the same OpenAI-style call as before, streams the answer into a bubble, and adds a line with the time to first text and the characters per second, measured on your own machine. Every answer goes into textContent, never innerHTML, so a model answer can't inject markup into your page. To try another model, change MODEL_ID to any ID from the table.

5. Start it:

npx vite
Enter fullscreen mode Exit fullscreen mode

Open the address it prints (http://localhost:5173) in Chrome and click Load model. The first time, it downloads the weights; the status line shows the progress.

6. Turn off the Wi-Fi, reload the page and load the model again. The page still opens, because Vite is serving it from your own machine, and the model comes from Chrome's cache instead of the network. Ask it something.

I ran exactly these steps with Chrome blocked from everything except localhost: the model loaded from the cache and answered, with the first text in 0.32 seconds.

With no internet at all, it explained that running AI in the browser lets developers "leverage the power of cloud computing". It also told me a service worker is "a type of worker who provides a specific set of services or support to customers", which is a fair reminder of what a 1B model is. Gemma 4 E2B or Qwen3.5 4B give better answers, if your GPU has the memory.

The model stays cached for later visits, until Chrome or the user clears the site's data; then it downloads again. On the Windows laptop, Gemma 4 E2B took 92 seconds to download and load.


Shipping it: make the page open offline

On your machine, the local dev server covers the page. On a real website it doesn't: WebLLM caches the model, but not your HTML and JavaScript. If a user closes the tab, goes offline and opens your site again, the browser has nothing to run, so the cached model is useless.

The fix is a service worker that keeps the page's own files. Register it from your page:

if ("serviceWorker" in navigator) {
  navigator.serviceWorker.register("/sw.js");
}
Enter fullscreen mode Exit fullscreen mode

And the worker itself:

// sw.js
const CACHE_NAME = "offline-ai-shell-v1";
const APP_SHELL = ["/", "/app.js", "/styles.css", "/vendor/web-llm.js"];

self.addEventListener("install", (event) => {
  event.waitUntil(caches.open(CACHE_NAME).then((cache) => cache.addAll(APP_SHELL)));
});

self.addEventListener("fetch", (event) => {
  if (new URL(event.request.url).origin !== self.location.origin) return;
  event.respondWith(
    fetch(event.request).catch(() => caches.match(event.request)),
  );
});
Enter fullscreen mode Exit fullscreen mode

It tries the network first and falls back to the cache when there is no network. This short version serves the files cached at install, so bump CACHE_NAME when you deploy (my test page also writes fresh responses back with cache.put). The paths in APP_SHELL are illustrative: they must match the files your build really outputs. Vite adds hashes to file names, so generate that list at build time (the vite-plugin-pwa plugin does it) instead of writing it by hand. Requests to other origins (the model downloads) are left alone, because WebLLM handles those. I serve the WebLLM library from my own origin instead of a CDN, so it ends up in the same cache.

Service workers only register on https:// pages or on http://localhost, never on file://. On my test page, with the network cut by an automated test (Playwright's offline mode) and the page reloaded, Llama 3.2 1B was ready again in 1.0 second.


My test page said "online" with the Wi-Fi off

My test page shows a big badge: green ONLINE or red OFFLINE. On a MacBook, where the network was cut inside the browser, it turned red. On the Windows laptop, where the Wi-Fi was turned off in Windows, it stayed green the whole time, and every row in the results JSON was tagged "online".

The badge used navigator.onLine. MDN is blunt about it: browsers and operating systems use different heuristics, a connection to a LAN counts as online even without internet, and virtualization software can create virtual network adapters that are always "connected". Its advice is that the property is "inherently unreliable" and should only be used as a hint.

I can't tell which of those reasons applied on that laptop. I changed the page to also send a small HEAD request to Hugging Face every few seconds, with a 3-second timeout, and only show ONLINE when it succeeds. That doesn't prove the internet is available either. It only proves the one host my page depends on for downloads is reachable, which is the question the badge should answer anyway.

If your app changes behavior when it thinks it is offline, test it on the machines your users have, not just on yours.


Offline model, but is the page private?

Running the model locally means the inference never leaves the machine. It does not mean the page can't send your prompt somewhere else. A site can run Gemini Nano locally and still fetch() every question and answer to its own server. The model being local says nothing about what the rest of the JavaScript does.

Two cheap checks:

  • Open the Network tab in DevTools while you chat. A truly local page sends nothing that carries your prompt. My test page shows one HEAD request to huggingface.co every 5 seconds: that's the connectivity check, with no body.
  • Read the page's Content Security Policy. My test page only allows connections to its own origin, Hugging Face and GitHub (for the WebLLM model files):
connect-src 'self' https://huggingface.co https://*.huggingface.co https://*.hf.co https://raw.githubusercontent.com
Enter fullscreen mode Exit fullscreen mode

With that header in place, the page's own scripts can't fetch() or beacon your prompts to any other host. It reduces the exposure, it doesn't guarantee privacy: the allowed hosts can still receive whatever the page sends them, and a script can still navigate the tab to another URL.


Where this fits in a real product

My opinion: the best uses are small, frequent tasks on text the user already has in front of them, where a round trip to a server adds cost or exposure and a small model is good enough.

Use case Why in the browser
Summarizing a confidential document the user opened The text doesn't have to leave the machine for inference
Writing help in a form or editor (rephrase, shorten, fix tone) No per-request cost, works on a flight
Classifying or tagging tickets before they're sent Less load on the backend
An offline-first PWA for field work The feature keeps working without signal
Pulling fields out of pasted text (dates, amounts, names) Fast, private, and easy to check by the user

The pattern behind all of them: the model works on the user's own data, and a wrong answer is cheap because the user sees it right away.


When this is the wrong tool

Situation Better option
You need answers on the level of the biggest cloud models A cloud API. A 2B to 4B model is useful for summaries, rewriting and simple Q&A, not for deep reasoning
Your users are on phones A cloud API, or a native app. The Prompt API is desktop only
You need the same model on many machines with weak GPUs Gemini Nano's CPU path, or a server. WebLLM's 4B models need about 4 GB of GPU memory
You need a language Gemini Nano doesn't support WebLLM with a multilingual model such as Qwen
You want a model shared by every app on the machine Ollama or another local server. WebLLM's cache belongs to one origin

The cost model is also different from what "free" suggests. There is no API bill and no per-token price, but the user pays with disk space (gigabytes per model, per origin, for WebLLM), with a first download that can take minutes, and with their own GPU and battery.


How I measured

Machine Windows laptop, 32 GB RAM, AMD Radeon graphics (RDNA 3 per WebGPU), shader-f16 supported
Browser Chrome 158.0.8127.37
Gemini Nano Prompt API, model already downloaded before the test
WebLLM @mlc-ai/web-llm 0.2.88, gemma-4-E2B-it-q4f16_1-MLC
Prompt "Explain dependency injection in about 150 words and finish with a short TypeScript example."
Runs Nano: 3 benchmark runs. Gemma: 3 benchmark runs, the first one right after download. Wi-Fi on and off
When November 30, 2026
Extra checks MacBook (Apple M3), Chrome 158, Llama 3.2 1B: page reload from the cache with the network cut by Playwright, and the step-by-step project with every host except localhost blocked

First visible text is the time from sending the prompt to the first characters on screen. Output speed is tokens divided by the streaming time after the first text. WebLLM reports its output tokens; the Prompt API doesn't, so for Gemini Nano I counted them with the session's own measureContextUsage() on the final answer, which makes the Nano token numbers an approximation. Characters per second, which needs no tokenizer, told the same story: about 81 to 87 for Nano and 46 to 47 for Gemma after the first run.

This is one laptop and one prompt, a small practical experiment and not a benchmark of the models' quality. Your numbers will depend on your GPU.


FAQ

Does Gemini Nano send my prompts to Google? The Chrome docs say that after the download, using the built-in models sends no data to Google or third parties. The page calling the API is a separate question (see the privacy section above).

Can I use WebLLM in Firefox or Safari? It needs WebGPU. Check your browser's current WebGPU support before promising it to users.

How do I delete a WebLLM model? Clear the site's data in Chrome, or call deleteModelAllInfoInCache(modelId), which WebLLM exports.

Is this the same as Ollama? Same idea, different place. Ollama is a program that runs models on your machine and serves them to any app. WebLLM is a library that runs models inside one web page.


Takeaway

  • Chrome can answer offline today with a few lines of JavaScript, as long as the machine meets Gemini Nano's hardware and disk requirements.
  • Open models compiled for WebLLM run in the browser too, but it is your page that downloads and stores them, not Chrome.
  • Cache the page, not just the model. On a real site, without a service worker, an offline AI page doesn't open offline.
  • Don't build logic on navigator.onLine. It said "online" on a laptop with the Wi-Fi off.
  • A local model doesn't make a page private. Check the Network tab and the CSP.

Not every AI feature needs a cloud model. For the small ones that work on the user's own text, the browser is now a reasonable place to run inference, and the first thing I'd check before adding another API call to a product.

What would you run fully offline in the browser if the model was already on your users' machines?


I'm Diogo Soares, a Staff AI Engineer working on AI agents and legacy modernization. If this was useful, follow me here on DEV.to and on Instagram at @diogosoares.dev, where the one-minute version of this experiment (Wi-Fi off, AI still answering) is a Reel. Every article also gets a video walkthrough on my YouTube channel, Diogo Soares Dev, so subscribe there for the next ones. Let's also connect on LinkedIn, or check out diogosoares.dev.

Top comments (0)