← Back to writing

Build · Scope: global engineering practice · AI builds 1/3

Semantic search over our own articles, with a local model

A small, runnable build: index this site’s English and Turkish articles with a multilingual embedding model on your own machine, search by meaning, and look honestly at where it works and where it does not.

This article was prepared with AI assistance, from the sources listed at the end and the working code in this repository. All outputs shown are from real runs.

Searching for meaning, not words

Ask “why does a longer input cost more memory?” over this site’s Turkish articles and a keyword search has nothing to work with: the Turkish text does not contain a single one of those English words. Semantic search compares meaning instead, and in the run shown below it found the right Turkish section anyway.

It does that with embeddings. Google’s machine learning course describes them as dense vector representations that capture semantic relationships: texts with similar meaning end up close together. Finding relevant passages this way is also the retrieval half of retrieval-augmented generation (RAG), introduced by Lewis and colleagues in 2020. This build stops at retrieval; generating an answer comes later in the Learning AI series.

A small multilingual model on your own machine

The site is bilingual, so the model has to place Turkish and English text in the same space. Multilingual E5 was trained for exactly that; the small version produces 384 numbers per text and is released under the MIT licence. Transformers.js runs it in Node.js with no API key and no cost per request; the first run downloads the model once.

One detail matters a lot: the model card says every input should start with “query: ” or “passage: ”. Documents get the passage prefix, questions the query prefix. Leaving it out quietly makes results worse.

From articles to an index

Each section of each article becomes one chunk, in each language, with the article title and section heading in front. That gives specific matches and stays well under the model’s 512-token limit, beyond which text is cut off. At the time of writing, nine articles produced ninety chunks.

Once: build the indexEvery search9 articlesEnglish + Turkish90 chunksone per sectionEmbeddings"passage: " prefixindex.json384 numbers eachQuestionany languageEmbedding"query: " prefixCosine similaritysort, keep the top 3
Indexing happens once; a search only embeds the question and compares it with the stored vectors.

Comparing vectors

Because the vectors are normalised, cosine similarity is just a dot product. The search embeds the question, scores every chunk and keeps the best three. For a few hundred chunks a plain array is plenty; a vector database becomes worth it when you have many thousands.

const cosine = (a, b) => a.reduce((sum, x, i) => sum + x * b[i], 0);

const hits = index
  .map((chunk) => ({...chunk, score: cosine(queryVector, chunk.vector)}))
  .sort((a, b) => b.score - a.score)
  .slice(0, 3);

Producing the embeddings

The embedding function loads the model once, adds the right prefix and averages the token vectors into one normalised vector per text. The 8-bit quantised model keeps the download small and is fast enough on a laptop.

The chunking step is a few lines over the same content records the site is built from.

import {pipeline} from '@huggingface/transformers'; // 4.3.1

const MODEL = 'Xenova/multilingual-e5-small';
let extractor;

export async function embed(texts, kind) { // kind: 'query' | 'passage'
  extractor ??= await pipeline('feature-extraction', MODEL, {dtype: 'q8'});
  const output = await extractor(
    texts.map((t) => `${kind}: ${t}`),
    {pooling: 'mean', normalize: true},
  );
  return output.tolist();
}

const chunks = articles.flatMap((a) =>
  ['en', 'tr'].flatMap((lang) =>
    a[lang].sections.map((s, i) => ({
      id: `${a.id}#section-${i + 1}`,
      lang,
      text: `${a[lang].title}. ${s.heading}. ${s.paragraphs.join(' ')}`,
    })),
  ),
);

What the searches returned

Indexing took about nine seconds. The first two searches below find exactly the right section. The third shows the multilingual part: an English question, restricted to Turkish chunks, lands on the Turkish context-window section.

$ npm run index
Indexed 90 chunks from 9 articles in 9191 ms; 384 dimensions.

$ npm run search -- "junior geliştiriciler AI yüzünden öğrenmiyor mu"
0.899  [tr] Hız geldi, öğrenme azaldı › Kimin yazdığı belli, kimin anladığı belli değil
0.878  [tr] AI ekipte kişisel bir tercih olarak kalmamalı › Sınır nerede
0.876  [tr] Hız geldi, öğrenme azaldı › AI’dan bugün ne istiyoruz

$ npm run search -- "why do I get a different answer to the same question"
0.865  [en] How a large language model works: … › Why the same question gets different answers
0.856  [en] Eight correct answers: is that really 100%? › When the grader is a model
0.853  [en] Eight correct answers: is that really 100%? › What to check next

$ npm run search -- "why does a longer input cost more memory" --lang tr
0.788  [tr] Büyük dil modeli nasıl çalışır: … › Context window, modelin çalışma belleği
0.786  [tr] Büyük dil modeli nasıl çalışır: … › Aynı soruya neden farklı yanıtlar geliyor
0.781  [tr] “Karpathy kuralları”nı Karpathy yazmadı › Karpathy aslında ne gözlemledi

Where it missed

Not every query worked. Asking in Turkish how much text a model can see at once should return the context-window section, yet it is not in the top three. Adding the words “context window” to the question fixed it, but the right section then tied with another at 0.874. An English question about separating instructions from data, restricted to Turkish, missed the matching section of the prompting note entirely.

$ npm run search -- "modelin aynı anda ne kadar metin görebildiği"
0.852  [tr] Büyük dil modeli nasıl çalışır: … › Aynı soruya neden farklı yanıtlar geliyor
0.850  [tr] Büyük dil modeli nasıl çalışır: … › Metni devam ettiren bir model
0.846  [tr] “Karpathy kuralları”nı Karpathy yazmadı › Karpathy aslında ne gözlemledi

$ npm run search -- "keep instructions separate from the data" --lang tr
0.792  [tr] Hız geldi, öğrenme azaldı › Kodu AI yazsa da sahibi sizsiniz
0.789  [tr] Bir yazıyı iki dilde yayımlamak › Eksik çeviri varsa ne oluyor?
0.784  [tr] AI emin görünüyor. Sonucu yayımlayalım mı? › Sıra önemli

Reading the scores

All scores sit between roughly 0.78 and 0.90. The model card explains why: training with a low temperature makes cosine similarities cluster between about 0.7 and 1.0, and what matters is the order of results, not their absolute values. So a fixed cut-off like “only show results above 0.8” would be meaningless here.

The gaps between the first and third result are often smaller than one hundredth. That is the honest state of a small model over long chunks. Shorter chunks, a larger model or combining keyword and vector search could help, but you only know which change helps if you measure it. That is the subject of the next build: a small harness for testing prompts and retrieval against expected answers.

References

  1. Google Machine Learning Crash Course: Embeddings
  2. Lewis et al.: Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (arXiv, May 2020)
  3. Wang et al.: Multilingual E5 Text Embeddings: A Technical Report (arXiv, February 2024)
  4. intfloat/multilingual-e5-small model card (Hugging Face)
  5. Transformers.js documentation (Hugging Face)