Skip to content
WebAI

Building the retrieval half of RAG in the browser

The whole retrieval half of RAG fits in a tab: an embedding model, a vector index and a cross-encoder reranker. How the three stages connect, what each one weighs, and why swapping the embedding model means rebuilding the index from scratch.

RAG sounds like a capability of a large model, but it comes apart into pieces you can swap: an embedding model turns text into a fixed-length vector, an index finds nearby vectors, and a cross-encoder re-scores the recalled candidates. Our search-rag category is split along those lines into embedding, reranker and semantic-search, and each has a demo that runs in the browser.

Starting with the embedding model

An embedding model encodes one sentence at a time and emits a fixed-length vector, with the meaning squeezed into a few hundred numbers. all-MiniLM-L6-v2 is our default: 384 dimensions, about 21.9 MiB of weights, millisecond encoding of a short sentence on CPU. BGE Small EN and GTE Small sit around 32.4 MiB and score slightly better on retrieval benchmarks. BGE-M3 covers multiple languages and long context, but at 1.1 GB of download we rarely touch it on the client.

A sum you never bother with on a server has to be done here: index memory is rows times dimensions times bytes per value. A hundred thousand 384-dim vectors take about 147 MB as fp32 and about 37 MB as int8. Tabs have a much tighter memory budget, so local indexes almost always go int8.

The index decides recall time

A brute-force cosine scan over 100k vectors costs tens of milliseconds on CPU and grows linearly. HNSW (hierarchical navigable small world graphs) brings queries down to roughly logarithmic, which makes it the client-side default: hnswlib.js is the WebAssembly port, Voyager comes from Spotify, LanceDB pairs columnar storage with a vector index, and Vectra keeps the index in a local file.

More important than speed is that the index can stay local. Chunks, vectors and index all live on the device, and retrieval sends no request at all. For contracts, medical records or internal knowledge bases, that is often the only shape anyone will accept.

Reranking is about fixing the order

A bi-encoder has to encode query and document separately so vectors can be precomputed, and token-level interaction gets lost. "Refund policy" and "return rules" land close in vector space, but so do "no refunds" and "refunds". A cross-encoder concatenates query and candidate into one input and runs the model over the pair. Much more accurate, but one forward pass per candidate and nothing can be precomputed.

So the usual shape has two stages: embeddings recall 50 candidates, the cross-encoder cuts that to 5. MS MARCO MiniLM Cross-Encoder at about 22.1 MiB is the light option; BGE Reranker Base at about 266 MiB is stronger and takes longer to download.

StageRepresentative modelMeasured sizeOutput
Embeddingall-MiniLM-L6-v2~21.9 MiB384-dim vector
Embedding (multilingual / long)BGE-M3~1.1 GB1024-dim vector
Indexhnswlib.js / Voyager / LanceDB / VectraLibrary only, no weightstop-k neighbour ids
RerankMS MARCO MiniLM Cross-Encoder~22.1 MiBquery-document relevance
Rerank (stronger)BGE Reranker Base~266 MiBquery-document relevance
Measured sizes by stage

The code that chains it

Two-stage retrieval with transformers.js
import { pipeline } from '@huggingface/transformers';

const embed = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2', { dtype: 'q8' });
const encode = async (text: string) =>
  (await embed(text, { pooling: 'mean', normalize: true })).data;

// 1. build: encode every chunk, insert into HNSW
// 2. recall: index.search(queryVec, 50)
// 3. rerank: cross-encode (query, doc), keep the top 5

A trap we hit: index and query have to use the same embedding model and the same normalisation. Swap the model, even for one with the same dimensions, and the index must be rebuilt because similarity scores stop being comparable. Rebuilding an index in a tab takes time, so decide the model before you build it.

When local is worth it

  • Documents cannot be uploaded, so retrieval has to happen on the device
  • Intranets, flights, field work, anywhere the network is absent or poor
  • No per-token embedding API bill, which matters more as the user count grows
  • Interactive search loses one network round trip and feels noticeably different

Millions of chunks, frequent full rebuilds, or one shared index across tenants are different: the bottleneck is index operations, not latency, and the client is the wrong home.

The three demos can be tried in order: change models in the embedding demo and the similarity matrix shifts; watch the reranker reorder a candidate list; semantic search shows both stages chained.

All posts →

← Back to all posts