Building RAG for my website
contents
People have told me my blogs are too long, I like long blogs, they don't. Too bad. I need to solve this problem, sure I can write shorter blogs, but there is no fun in that.
I wanted to search my blog content. I also wanted an LLM (large language model) on top of the blog, so that anyone can open samitmohan.github.io/ask and ask a question about the blog.
I had never built a RAG (retrieval-augmented generation) system. So I watched some Stanford videos, read some docs, and used ChatGPT to plan the project.
ChatGPT doesn't know about samitmohan.github.io. It is a general model, so it can't answer questions about my blog. I could fine-tune a model, but that's expensive and overkill. RAG is simpler. It gives the model my blog content as context at query time, and the model weights stay the same.

what this project does
The goal was to build a retrieval-augmented question-answering system that:
- Indexes all my blog posts (17 posts, ~1100 chunks, where a chunk is a small piece of a post).
- Retrieves relevant text or code chunks based on semantic similarity + intent-aware reranking + lexical boosting.
- Generates grounded, streaming answers with citations using Groq's
llama-3.3-70b-versatile. It needs no local setup. - Measures itself with an evaluation pipeline (MRR, Recall, Precision over 20 golden queries, all defined in phase 5).
architecture
This is how the UI looks

phase 1: ingestion & corpus creation
The goal of this phase is clean retrieval units from the blog content that I can inspect.

1. loading blog data
All my blog posts are Markdown files in the _posts folder of my GitHub repository. load_all_blogs.py fetches them through the GitHub API.
2. parsing markdown
Markdown can be messy. parse_markdown.py extracts structured data:
- The frontmatter: title, date and categories.
- The structure: section headings, paragraphs, code blocks and links.
I skipped a heavy Markdown AST (abstract syntax tree) parser and used regex and structure matching instead. More control, but trickier to get right. I had to use GPT.
3. cleaning without summarizing
The script clean_text.py handles normalization:
- Normalizes whitespace.
- Removes non-content "junk".
- Does not rewrite or summarize.

Retrieval depends on the source text. If the cleaning step loses or changes that text, retrieval breaks.
4. chunking (the part i got wrong the first time)
A chunk is the smallest piece of text that the retriever returns on its own to answer a question.

Chunking took me a while to get right. An embedding model turns each chunk into a vector of numbers (phase 2 explains this). Your embedding model doesn't care about your paragraph breaks. It cares about semantic density. My first chunker was dead simple: one paragraph = one chunk. The result? 2851 chunks with a median size of 16 words. Sixteen words. Barely a sentence.
If someone asks "how does KV cache work?", and the answer spans 3 consecutive paragraphs, my old chunker would retrieve maybe 1 of those 3 paragraphs. The embedding for a 16-word chunk is noisy. It does not hold enough meaning for the vector search to work with.
The fix was obvious once I measured it:
- Merge consecutive text items within a section into one buffer
- Split by approximate token count (~200 tokens target, 50 token overlap)
- Never split code blocks (they need to be intact or they're useless)
- Prepend
[Section: {name}]to each chunk so the embedding model knows context
Without overlap, the chunker cuts a sentence at a chunk boundary in two, and neither chunk holds the whole sentence. With 50 words of overlap, each chunk starts with the last 50 words of the previous chunk, so the boundary text is complete in at least one of them.
The core splitting logic:
def _split_text_with_overlap(text: str, target: int, overlap: int) -> List[str]:
words = text.split()
if len(words) <= target:
return [text]
chunks = []
start = 0
while start < len(words):
end = start + target
chunk_words = words[start:end]
chunks.append(" ".join(chunk_words))
start += target - overlap
if start >= len(words):
break
return chunksNo tiktoken, no BPE (byte-pair encoding). Only split(). Word count is a good enough proxy for token count when you're chunking blog posts, not training a tokenizer.
Interactive: sliding window chunking
This toy splits a paragraph into 40-word chunks. Drag the slider to change the overlap. The highlighted words appear in two neighboring chunks.
The chunk count dropped from 2851 to 1111 for the same 17 blog posts. Each chunk now has enough context for the embedding model to produce a meaningful vector. Retrieval quality jumped. Phase 5 has the numbers.
phase 2: embeddings & vector store
- Store the chunks in a searchable vector index. The embedding model turns each chunk into a vector. Text with related meaning gets vectors that sit close together. For example, the vectors for "king" and "queen" land nearby because the words are related.
- Use cosine similarity to measure how close the query vector is to each stored chunk vector, and give each chunk a
score.
embeddings
I started with the Sentence Transformers library for generating embeddings:
SentenceTransformerEmbeddings("all-MiniLM-L6-v2")- 384-dimensional vectors: each chunk becomes a list of 384 numbers. More dimensions can hold more meaning, but the gains get smaller and the compute cost goes up.
- Fast inference (the Sentence Transformers docs say it is 5x faster than
all-mpnet-base-v2) - Runs locally
- Good quality for semantic search
Text and code use the same model. A metadata flag marks each chunk as text or code for the retrieval step. I prefix text chunks with "Explain the following text:\n" and code chunks with "Code example:\n" before embedding. The query gets the text prefix too. The model is the same, but the prefix moves the embedding vector toward the right semantic neighborhood.
SentenceTransformer didn't hold up in deployment. Creating query embeddings is fast, but the library takes too much memory. The Render backend kept crashing.
I switched to fastembed with TextEmbedding(model_name="BAAI/bge-small-en-v1.5"). BGE (BAAI General Embedding) small also gives 384-dimensional vectors. fastembed runs it on ONNX (Open Neural Network Exchange) Runtime without PyTorch, and the quantized ONNX weights are about 67 MB. That fits on Render.
Both models do the same job. They convert each chunk into a vector embedding. The vector store then keeps these vectors for the similarity search.
One limit to know: bge-small reads at most 512 tokens per chunk and drops the rest. Code blocks never split, so some chunks are long. 44 of the 1111 chunks have more than 512 tokens. The longest is the 200-line code block in my interview-questions post: 3,552 tokens. The search sees only its first 512 tokens, so the end of that block is invisible to retrieval.

vector store (FAISS)

Store these vector embeddings in a database.
I use FAISS (Facebook AI Similarity Search) to store the vectors. The index is IndexFlatL2, an exact brute-force index: each query compares against all 1111 vectors. FAISS isn't optimal for all scales, but for 1111 chunks it works fine. FAISS stores only the vectors, so I keep a parallel metadata store:
vector --> embedding (384-dim, L2-normalized)
payload --> { id, text, metadata: {post_title, section, date, url, type} }I normalize each vector to length 1 before I add it to FAISS. IndexFlatL2 returns the squared L2 distance, and for two unit vectors and that distance depends only on the angle between them:
So a ranking by this distance is the same as a ranking by cosine similarity. The distance goes from 0 (same direction) to 4 (opposite direction), and a distance of 1.0 is a cosine similarity of 0.5. Without normalization, the vector length also changes the distance, and the length says nothing about relevance.
For example, the query "Why do we use softmax in MNIST?" returned the chunk "Softmax is used in MNIST classification..." at a distance of 0.29. A lower distance means the chunk is closer to the query.

At this point the pipeline goes blog documents -> cleaned -> chunks -> embeddings -> searchable database.
The query also becomes an embedding, with the same model.
FAISS compares the query embedding with each chunk embedding. A lower distance means closer, but the chunk with the lowest distance is not always the correct answer.
Interactive: cosine similarity
Drag the blue vector (chunk) to change its angle to the red vector (query). Cosine similarity is 1 when the vectors point the same way, 0 when they are perpendicular, and -1 when they point in opposite directions.
phase 3: retrieval control & reranking

Raw semantic search isn't always enough. User intent varies.
- If I ask "show me code", I want code blocks.
- If I ask "why does this work", I want conceptual explanations.
retrieve.py handles this with a multi-stage pipeline:
query
|
v
intent classification (code indicators vs text indicators)
|
v
embed query (same BGE model)
|
v
FAISS search (top 10 candidates)
|
v
reranking:
- intent match: distance *= 0.5 (boost)
- intent mismatch: distance *= 2.0 (penalize)
- code intent + "code" in section name: distance *= 0.8
- lexical overlap: distance *= (1.0 - 0.3 * coverage_ratio)
- exact phrase match: distance *= 0.8
- drop chunks < 5 words
|
v
deduplicate (one chunk per post+section)
|
v
top-k chunks (k = 5)
|
v
confidence check (best distance < 1.0, else "no results")Interactive: reranking pipeline
Query: "show me the attention code" Detected intent: code
Click each step to see how the retrieval scores change. Highlighted rows changed in this step. A lower distance means more relevant. The distances are toy numbers.
Pure vector search returns "semantically similar" results, but that's not always what you want. Someone asking "show me the code for attention" doesn't want a paragraph explaining attention. They want the class SelfAttention(nn.Module) block. The intent classifier is dead simple (keyword matching on words like "code", "implement", "why" and "explain"), but the 0.5x boost / 2.0x penalty makes a real difference.
The lexical overlap part is a poor man's BM25 (Best Matching 25). BM25 is the standard keyword ranking function in search engines. It scores a chunk by how often each query word appears, gives rare words more weight, and corrects for chunk length. My version counts the fraction of query words (longer than 2 letters) that appear in the chunk text. If every query word appears, the reranker multiplies the distance by 0.7. If you search for "softmax" and a chunk contains the word "softmax", it should float to the top even if some other chunk is slightly closer in embedding space.
The intent weights push a lot of irrelevant results out of the top 5 before the LLM ever sees them.

phase 4: prompting & generation
Simple RAG dumps chunks into the LLM prompt and hopes for the best. That works poorly.

Adding a system prompt that explains the context and gives answer instructions makes a real difference.
prompt construction
I tell the LLM what each retrieved chunk is:
[TEXT | source=ai_engineering_KV_Cache_0]
KV caching stores previously computed key-value pairs so the model
doesn't recompute attention for prior tokens during autoregressive generation...
[CODE | source=math_for_ai_Self_Attention_Code_0]
class SelfAttention(nn.Module):
def __init__(self, d_model, n_heads):
...Then I append the user's question. This formatting stops the model from "guessing" the context type. It also gives the model source IDs to refer to, and these IDs are the same IDs that the citations use.

generation (Groq + streaming)
This was the biggest pain point of v1. I was running Ollama (a tool that runs LLMs locally) with qwen2.5:7b. It worked great on my laptop but was useless for anyone else.
The fix was embarrassingly simple: Groq, a hosted inference API. Free tier, fast inference, always available. I swapped Ollama for Groq's API running llama-3.3-70b-versatile (about 9x the parameters of my old local model: 70B vs 7.6B) and the whole deployment headache just... disappeared.
from groq import Groq
client = Groq(api_key=GROQ_API_KEY)
def generate_stream(prompt):
stream = client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=[
{"role": "system", "content": prompt["system"]},
{"role": "user", "content": prompt["user"]},
],
stream=True,
)
for chunk in stream:
if chunk.choices[0].delta.content:
yield chunk.choices[0].delta.contentThe other big upgrade is streaming. In v1, the user clicked search, waited 5-10 seconds staring at "workin...", then got the full answer dumped at once. Now the frontend reads Server-Sent Events (SSE) and renders tokens as they arrive, with a cursor animation. Feels like ChatGPT.
The SSE format is simple. Each event is one data: line followed by a blank line:
data: {"token": "KV"}
data: {"token": " caching"}
data: {"token": " stores"}
...
data: {"done": true, "citations": [...]}The frontend reads this with a ReadableStream reader. It debounces the markdown re-render by 80 ms, so it doesn't call marked.parse() on every single token. When done arrives, it removes the streaming cursor.
citations & grounding
The citations come from the retrieved chunks, not from the LLM:
- The backend records every chunk that goes into the prompt.
- It returns those chunks as citations with the answer.
An example response:
Answer: Softmax converts logits into probabilities...
Sources:
600+ leetcode questions: lessons_intro_0(text, section=intro)
This part was easy because I store metadata with the vectors. The backend returns the source of each chunk with the answer.
phase 5: measuring retrieval quality
This is the part most RAG tutorials skip, and it's the part that matters most. You can build the prettiest pipeline in the world, but if you can't measure whether it retrieves the right chunks, you're just vibing.
I built an evaluation pipeline (eval/evaluate.py) that:
- Loads 20 hand-written test queries from
eval/golden_set.json - Each query has ground-truth annotations: which blog post should be retrieved, which section, what intent
- Runs each query through the full retrieval pipeline (no LLM, only the retriever)
- Computes three standard IR (information retrieval) metrics: MRR@k, Recall@k, Precision@k
MRR (mean reciprocal rank) looks at the rank of the first correct result for each query. If it's #1, the score is 1.0. If it's #3, the score is 1/3 = 0.33. If it's not in the top k at all, the score is 0. MRR@k is the mean of these scores over all queries.
Recall@k is the fraction of queries with at least one correct result in the top k. Strictly, this is the "hit rate" in the figure at the end of this post. Textbook recall@k divides the correct results found by all correct results for the query.
Precision@k is the fraction of the top k results that are relevant, averaged over all queries.
The golden set:
{
"query": "How does KV cache work in transformers?",
"relevant_posts": ["AI engineering"],
"relevant_sections": ["KV Cache", "KV Caching: Core Idea"],
"intent": "text"
}Writing these queries is the hard part. You have to know your own content well enough to say "this query should hit this section of this post." I wrote 20 of them covering different posts, intents, and difficulty levels.
the results
This is what made the chunking rewrite worth it. Same embedding model, same retrieval logic, same everything. The only difference is how the text gets chunked.
Retrieval metrics: old chunking vs new chunking
The numbers:
============================================================
Retrieval Evaluation | 20 queries
============================================================
Metric @1 @3 @5
-----------------------------------------
MRR 0.450 0.558 0.571
Recall 0.450 0.700 0.750
Precision 0.450 0.250 0.180
-----------------------------------------MRR@1 went from 0.10 to 0.45, a 4.5x improvement. The correct result was #1 for 2 of the 20 queries. Now it is #1 for 9 of them.
Recall@5 went from 0.45 to 0.75, so 15 of the 20 queries now get a relevant result in the top 5. With the old chunking, 11 of the 20 queries missed entirely.
The 5 remaining misses are queries like "What is RLHF?" (reinforcement learning from human feedback), where the relevant content exists in a larger merged chunk with a section title that doesn't match. Fixable with better section-level metadata, but 75% recall is solid for a personal blog search engine.
The lesson here is what Karpathy keeps saying: don't just train, evaluate. The eval pipeline is 150 lines of code and a JSON file with 20 entries. It took maybe an hour to write. But it's the difference between "I think my RAG works" and "I can show you that MRR@1 improved by 4.5x when I changed chunking strategy." One of these is a side project, the other is engineering.
persistence & deployment
persistence
Every time a user hits samitmohan.github.io/ask, the backend can't re-embed 17 blog posts from scratch. Index once, store in data/faiss/, done.
I save the FAISS index and metadata to disk and commit them to git. On restart:
- No re-embedding.
- No re-indexing.
- The backend loads the index from disk and can answer the first query.
deployment (the v1 struggle and the fix)
v1 was a mess deployment-wise. I had this Rube Goldberg setup:
- Backend on Render (free tier), which handles retrieval
- LLM on my laptop via Ollama, which only works when my laptop is open
- ngrok tunnel connecting my laptop's Ollama to the Render backend

Figure: the v1 architecture. The frontend calls /retrieve for the FAISS search and /generate for the local LLM.

It worked, but the LLM was offline 90% of the time. Not useful for anyone who isn't me, sitting at my desk, with Ollama running.
v2 is much simpler. The backend runs on Render and the LLM runs on Groq. Neither needs my laptop. No tunnels, no local dependencies, no dual-mode architecture. Set GROQ_API_KEY as an environment variable on Render and you're done. The Render free tier still sleeps when idle, so the first request after a quiet period can wait 50 seconds or more (the banner in the screenshot below says so).

The streaming endpoint (/query/stream) does retrieval and generation in one request and streams the tokens back as SSE. The frontend handles the rest. No WebSockets, no polling. It is a standard HTTP response with the text/event-stream content type.
@app.post("/query/stream")
def query_stream_endpoint(req: RetrieveRequest):
retrieved = retrieve(req.query, vector_store, k=req.top_k)
if not is_confident(retrieved):
def empty_stream():
yield f"data: {json.dumps({'done': True, 'citations': [], 'no_results': True})}\n\n"
return StreamingResponse(empty_stream(), media_type="text/event-stream")
chunks = [r["chunk"] for r in retrieved]
return StreamingResponse(
answer_with_citations_stream(req.query, chunks),
media_type="text/event-stream",
)The final pipeline:
Figure: the RAG request path, from question to streamed answer.
- GitHub Pages UI captures input.
- FastAPI backend processes the request.
- FAISS performs retrieval.
- Reranker reorders the results by intent + lexical overlap.
- Groq (llama-3.3-70b) streams the response.
- UI renders tokens as they arrive and shows the source cards.

Figure: a general RAG system. Mine skips the safety filters, the query expansion and the image index.
testing
repo structure
rag-for-blogs/
├── pyproject.toml # Pinned deps, dev extras (pytest)
├── config.py # Centralized settings (Groq, embeddings, chunking params)
├── .env.example # GROQ_API_KEY, GITHUB_TOKEN
├── data/
│ └── faiss/ # Pre-built FAISS index + metadata (committed to git)
├── ingestion/
│ ├── load_all_blogs.py # Fetch posts from GitHub API
│ ├── parse_markdown.py # Frontmatter + structure extraction
│ ├── clean_text.py # Normalize without summarizing
│ └── chunker.py # Overlap-aware chunking (~200 token target, 50 overlap)
├── embeddings/
│ ├── embed_chunks.py # FastEmbed (BAAI/bge-small-en-v1.5, 384-dim)
│ └── vector_store.py # FAISS index + metadata persistence
├── retrieval/
│ └── retrieve.py # Intent classification, reranking, lexical boosting
├── generation/
│ ├── groq_client.py # Groq SDK wrapper (streaming + blocking)
│ ├── answer.py # LLM call
│ ├── answer_with_citations.py # Streaming SSE + citation attachment
│ ├── prompt_builder.py # System + user prompt construction
│ └── formatter.py # Post-processing
├── eval/
│ ├── golden_set.json # 20 hand-curated test queries
│ └── evaluate.py # MRR@k, Recall@k, Precision@k
├── tests/ # 32 tests (chunker, retrieval, embeddings, integration)
├── backend/
│ └── app.py # FastAPI + streaming endpoint
└── index.html # Frontend with SSE consumption32 tests across 4 files. I'm not aiming for 100% coverage. The tests cover the parts that matter for an ML pipeline:
- 13 chunker tests check metadata, size bounds, overlap, code block integrity and edge cases (empty input, consecutive merging, text-code-text sequences).
- 13 retrieval tests check intent classification, confidence thresholds, code detection, the intent boost in reranking and deduplication.
- 4 embedding tests check deterministic output, the 384 dimensions, empty input, and that different prefixes give different embeddings.
- 2 integration tests run the full ingest-embed-query pipeline on synthetic docs and check confidence filtering on unrelated queries.
uv run python -m pytest tests/ -v
# 32 passed in 0.31sI mark the 8 slow tests (the ones that load the embedding model) with @pytest.mark.slow. Skip them during development with -m "not slow".
final thoughts
Lessons from building RAG:
- RAG is mostly data engineering, not model selection. The chunking rewrite improved MRR@1 by 4.5x with the same embedding model.
- Measure everything. The eval pipeline is the most valuable file in the repo. Without it, the chunking rewrite would have been a guess.
- Intent control beats larger embeddings. A simple keyword-based intent classifier + distance multipliers outperforms throwing more dimensions at the problem.
- Don't over-engineer deployment. v1 had tunnels, dual modes, and local LLM. v2 has one env var. Use hosted inference APIs when they're free and good enough.
You can test it at samitmohan.github.io/ask
Source code: github.com/samitmohan/rag-for-blogs
# Run it locally
git clone https://github.com/samitmohan/rag-for-blogs
cd rag-for-blogs
export GROQ_API_KEY=gsk_your_key_here
uv sync --all-extras
uv run uvicorn backend.app:app --reload --port 8000
# open localhost:8000demo
appendix: how to measure RAG accuracy

The eval pipeline measures retrieval quality, not generation quality. That's intentional. Retrieval is the bottleneck. Retrieve the right chunks and a 70B model generates a good answer. Retrieve garbage and no prompt engineering saves you.
To measure generation quality you'd need human evaluation or an LLM-as-judge setup (feed the answer + ground truth to GPT-4 and ask it to score). That's a project for another day.
- I built a much simpler project, a customer support bot, to learn the RAG basics (LangChain for everything). The code is here.