Skip to content

RAG in 50 lines of TypeScript

PLACEHOLDER post. A minimal retrieval-augmented generation pipeline: chunk, embed, retrieve, answer with sources.

[Your Name] 1 min read
Documents flowing into a vector database and out as an answer

Placeholder post. Replace this file with your own article, or delete it.

Retrieval-augmented generation (RAG) sounds complicated, but the core loop is small:

  1. Split documents into chunks
  2. Turn each chunk into an embedding
  3. Find the chunks closest to the question
  4. Ask the model to answer using only those chunks

Retrieval

ts
function cosine(a: number[], b: number[]) {
  let dot = 0, na = 0, nb = 0;
  for (let i = 0; i < a.length; i++) {
    dot += a[i] * b[i];
    na += a[i] ** 2;
    nb += b[i] ** 2;
  }
  return dot / (Math.sqrt(na) * Math.sqrt(nb));
}
 
export function topK(query: number[], chunks: { text: string; vector: number[] }[], k = 4) {
  return chunks
    .map((c) => ({ ...c, score: cosine(query, c.vector) }))
    .sort((a, b) => b.score - a.score)
    .slice(0, k);
}

Answering with sources

Pass the top chunks into the prompt, numbered, and ask the model to cite them like [1]. That single instruction does more for trust than anything else in the pipeline.