- RAG
- TypeScript
- LLMs
- Placeholder
RAG in 50 lines of TypeScript
PLACEHOLDER post. A minimal retrieval-augmented generation pipeline: chunk, embed, retrieve, answer with sources.
Placeholder post. Replace this file with your own article, or delete it.
Retrieval-augmented generation (RAG) sounds complicated, but the core loop is small:
- Split documents into chunks
- Turn each chunk into an embedding
- Find the chunks closest to the question
- 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.