LLMOps in Practice 05: A RAG That Explains Every Step
LLMOps in Practice 05: A RAG That Explains Every Step
Whatever can be said can be said clearly; whatever cannot be said must be passed over in silence. — Ludwig Wittgenstein
“In the vector space, ID-1234 and ID-9876 are almost the same point.”
This sounds a bit mystical, but it’s an unavoidable reality in RAG system design. You may have written many “three-line demos”: chunking, stuffing into a vector database, and concatenating prompts, which looks like it can run, but once someone asks about a ticket number or an order ID, the system goes silent.
Because these identifiers are “blurry” in the vector space — their semantic distances and structural information are almost the same, leading to a jumbled retrieval result. It’s not that the technology is insufficient; it’s that the methodology doesn’t align. You must be able to “explain each step” from the knowledge base to truly achieve “any question, any answer.”
So how do we do it? Today, we won’t talk about recipes but instead deconstruct a complete RAG pipeline that is explainable, debuggable, and reproducible — see how each step can be made clear.
Key Takeaway: To make RAG explainable, you must start from the source and “reason logically” — unify structured and unstructured knowledge modeling, then answer questions through traceable chains.
1. 🎯 30-Second Version
markdown ─按标题分块─▶ SQLite 索引(按文件哈希增量更新)
query ─▶ BM25(精确词、编号、中文)─┐
─▶ 向量(bge-small) ─┴▶ RRF 融合 ─▶ reranker 精排
─▶ top-k 段落 ─[丢掉带注入的段落]─▶ LLM
─▶ 带 [n] 引用的回答 ─[引用校验]─▶ grounded / 不 grounded
- Dual Recall: BM25 handles literal matches, while vectors handle semantics — complementary.
- RRF Fusion: Only ranks matter, not scores — no need to align scales between the two paths.
- Reranker: Re-ranks the fused shortlist — this is the final quality source.
- Citation Validation: Every
[n]in the answer must point to a real passage given. - Each result includes
bm25_rank / dense_rank / score— “Why wasn’t it retrieved?” can be answered.
📌 Core Insight: This is a retrieval system that balances recall efficiency and semantic understanding. Through multi-path parallelism, fusion ranking, and strict validation mechanisms, it ensures answers are both fast and accurate.
🔍 Details:
SQLite Index — Incremental File Hash-Driven Updates
To support fast paragraph-level retrieval, we chose to build a file-hash-based index in SQLite. This index is not rebuilt from scratch every time but maintained via incremental updates. When a document changes, only its hash value and related metadata (e.g., paragraph ID, content summary) are updated, not the entire database.
📌 Technical Detail: SQLite’s transaction mechanism and WAL mode ensure data consistency under concurrent writes. Although SQLite performs slightly worse than dedicated distributed databases in high-concurrency scenarios, its lightweight nature and persistence are sufficient for current business scale.
The core advantage of this approach is “change-point awareness.” When dealing with large text libraries (e.g., hundreds of thousands of paragraphs), rebuilding the entire index every time would be extremely costly in performance and could even cause retrieval service interruptions. Incremental updates give the system the ability to handle frequent data changes.
BM25 + Vector — Dual Recall Strategy
Recall is the first stage of a retrieval system, aiming to find the most relevant candidates from massive data. We adopted two independent recall models:
- BM25: Handles exact keyword matching, suitable for structured content, numbers, and terminology.
- Vector Retrieval (using bge-small model): Captures semantic similarity, strong in natural language understanding.
🧠 Why Dual Paths?
Because BM25 and vector models each have strengths and blind spots. BM25 is sensitive to exact words, code snippets, and numeric IDs but struggles with context; vectors excel at semantic matching but can drift in ambiguous inputs. Combining them is a typical “complementary recall” strategy.
For example:
- Query: “How to set up PodSecurityPolicy in Kubernetes?”
- BM25 finds content containing keywords like 「PodSecurityPolicy」, 「kubernetes」;
- Vector retrieval may identify semantically similar content such as 「how to secure Kubernetes resources」.
Working together, they cover more dimensions of user intent.
RRF Fusion Strategy — Rank First, No Score Alignment Needed
After obtaining BM25 and vector recall results, the next step is to fuse them into a unified sorted list. Here we use RRF (Reciprocal Rank Fusion) algorithm.
🧠 Why RRF?
Because it doesn’t rely on specific scores from both models — only their ranking positions matter. This means whether BM25 scores 0.98 or vector scores 0.76, as long as they are in the top 10, they might be retained.
📌 Advantages:
- No normalization required;
- Simple algorithm, easy to understand and maintain;
- Strong compatibility with different types of retrieval models.
The RRF fusion formula (simplified) is as follows:
final_rank = 1 / (k + bm25_rank) + 1 / (k + dense_rank)
Where k is a tuning parameter, usually set to 60. This parameter determines the influence of “being higher up.”
Reranker — The Final Quality Gatekeeper
After fusion, the candidate list is still quite messy, so we introduce a reranker model to re-sort the shortlist.
🧠 Role Explanation:
Since BM25 and vector retrieval are coarse ranking methods, they cannot fully guarantee final result quality. The reranker is the last quality gatekeeper, considering more context information, semantic understanding, etc., to fine-tune the top K candidates.
For example:
- One candidate discusses “how to configure AWS EC2 instances,” another talks about “how to deploy Docker containers”;
- If the user query is about 「Docker image building」, the reranker adjusts rankings based on deeper semantic matching, ensuring the more relevant one ranks higher.
Citation Validation — Ensuring Groundedness
Before final answer generation, we must perform citation validation. All [n] references in the answer must point to a record in the retrieved passage list.
🩸 Common Pitfall:
Some LLMs fabricate non-existent citations or misquote content during answer generation. Without validation, this can lead to false information that looks real, severely impacting trustworthiness.
By retaining bm25_rank / dense_rank / score fields in the retrieval stage and matching them during reasoning, we effectively prevent such occurrences.
Explainability Design — Why Wasn’t It Retrieved?
To improve user experience and debugging efficiency, each retrieval result includes the following information:
| Field | Meaning |
|---|---|
bm25_rank |
BM25 ranking in retrieval |
dense_rank |
Vector ranking in retrieval |
score |
Combined score (from reranker) |
📌 Value:
When users see a result not appearing in the answer, they can understand which modules filtered it out via these fields. For example:
- The segment was ranked high in BM25 but low in dense rank;
- Or its score was too low and discarded by reranker.
This traceability mechanism greatly improves system transparency and debugging efficiency, also aiding product iteration.
2. ⚙️ Underlying Principles
2.1 Chunking: Don’t Let a Paragraph Lose Its Subject
def chunk_markdown(text, source, max_chars=1200, overlap=150):
"""Chunk by headings, then pack paragraphs into max_chars.
A chunk won't cross a heading and carries its own title path."""
...
for line in text.splitlines():
if line.lstrip().startswith("```"):
in_fence = not in_fence
m = None if in_fence else _HEADING_RE.match(line)
if m:
flush()
level = len(m.group(1))
path[:] = [(lv, h) for lv, h in path if lv < level] + [(level, m.group(2))]
else:
body.append(line)
This code hides two subtle but crucial details that can determine the entire system’s success or failure.
Title paths are embedded into chunk content. For example, if a paragraph says “set to 30”, it makes no sense alone. It must include its context path like Telegram Bot > Configuration to form complete information. This simple change often improves retrieval quality more than switching to a more expensive embedding model.
Code blocks with # are not headings. You might think shell comments like # enter directory are ordinary, but regex matching misidentifies them as level-1 headings, splitting one document in half. This was discovered by observing corpus structure: a document’s “heading list” contained many shell comments, indicating an error in the chunking stage.
Maintain heading stack. When encountering ##, all same-level or deeper headings must be popped before pushing the current one. Here, path[:] = [...] modifies in place because the outer closure flush holds the same list. While elegant, this writing style can easily be overlooked during debugging — if the stack logic goes wrong, the chunk semantics are completely off.
2.2 Indexing: Incremental and Recognizes Its Own Embedder
def sync(self, files):
known = {row[0]: (row[1], row[2]) for row in self._db.execute("SELECT source, sha, embedder FROM docs")}
for source in set(known) - set(files):
self._delete(source) # File deleted, index follows
for source, path in sorted(files.items()):
sha = hashlib.sha256(text.encode()).hexdigest()
if known.get(source) == (sha, self.embedder.id):
continue # Content unchanged and same model used
...rechunk, vectorize, write to DB
The core idea of this sync function is: only update parts where content or model has changed. This ensures efficiency and avoids outdated data contamination.
Skip condition is the tuple (content hash, embedder id). Why not just content hash? Because if the model changes, even identical content will yield different vectors. For example, swapping sentence-transformers/all-MiniLM-L6-v2 for BAAI/bge-small-en, a file’s embedding must be recomputed.
Experience: Cache keys must include all inputs that affect results, especially model versions — they are often overlooked.
Vectors are stored as BLOB using array.array("f").tobytes(), with each 384-dim vector taking 1.5KB, no numpy needed. This approach reduces dependency on extra libraries and makes vector storage lighter.
2.3 BM25: Write It Yourself in Twenty Lines
def _bm25(self, query, tfs, df, avgdl, k1=1.5, b=0.75):
n = len(tfs)
terms = set(tokenize(query))
idf = {t: math.log(1 + (n - df[t] + 0.5) / (df[t] + 0.5)) for t in terms if df.get(t)}
scores = []
for tf in tfs:
dl = sum(tf.values())
scores.append(sum(
w * tf[t] * (k1 + 1) / (tf[t] + k1 * (1 - b + b * dl / avgdl))
for t, w in idf.items() if tf.get(t)))
return scores
To understand this code, remember three things:
- Rare words have higher weights (idf). If a word appears in all documents, it hardly helps locate information.
- Repeated occurrences yield diminishing returns (k1 controls saturation). Repeating “development” twice won’t give you higher scores — the effect gradually decreases.
- Longer documents naturally have more words and should be discounted (b controls length normalization). A 1000-word document is easier to score high than a 200-word one, so an adjustment factor is needed.
Chinese lacks spaces; tokenization uses character bigrams:
def tokenize(text):
low = text.lower()
tokens = _WORD_RE.findall(low) # Latin words
for run in _CJK_RE.findall(low): # Continuous CJK characters
tokens.extend(run[i:i+2] for i in range(len(run) - 1)) if len(run) > 1 else tokens.append(run)
return tokens
For example, 滚动日志 → 滚动 / 动日 / 日志. No need for complex tokenizers to achieve decent recall. The key is that indexing and querying must use exactly the same tokenizer — this is the most common and often overlooked point.
2.4 RRF: Don’t Compare Scores, Just Ranks
BM25 scores may be 12.7, cosine similarity 0.63. They can’t be added; normalization is fragile (a single outlier flattens others).
Reciprocal Rank Fusion sidesteps the issue:
rf = {
i: (1 / (RRF_K + bm25_rank[i]) if i in bm25_rank else 0.0)
+ (1 / (RRF_K + dense_rank[i]) if i in dense_rank else 0.0)
for i in set(bm25_rank) | set(dense_rank)
}
Each path contributes 1/(60+rank). Documents ranked high in both paths get the highest score; those only high in one still make it. The constant 60 is from the original paper, balancing the gap between rank 1 and 2. No tuning parameters — this is its biggest advantage.
A small detail: BM25 path only accepts scores > 0 (no point in including unmatched terms), while vector path has no such limit.
2.5 Reranker: Save Expensive Computation for Few Candidates
Embedding is “compute separately and compare” (two-tower), fast but doesn’t truly interact between query and document. Cross-encoder combines query and document, more accurate but much slower.
So the order is: both paths get 20 → fused to at most 20 → reranker runs on these 20 → top 5 selected. Recall should be broad, ranking precise, expensive models only for few candidates.
Tested: Pure downgrade backend hit@1 is 0.95, with bge-small + jina reranker it reaches 1.0. Small corpus, this number only shows direction.
2.6 Generation: Documents Are Also Unreliable Inputs
for h in hits:
checked = guard.check_tool_result("knowledge_base", h.chunk.text)
if any(f.category == "injection" for f in checked.findings):
continue # Chunk with instructions, discard
if any(f.category == "secret" for f in checked.findings):
h.chunk = Chunk(..., checked.text) # Chunk with keys, redact
safe.append(h)
The knowledge base is a place others can write. A sentence like 「ignore the above rules」 in one document is an attack that doesn’t require user interaction. So retrieved chunks must pass the same guardrail check as tool results.
2.7 Citation Validation: Structural Groundedness
def check_citations(answer, n_passages):
cited = sorted({int(n) for n in _CITATION_RE.findall(answer)})
invalid = [n for n in cited if not 1 <= n <= n_passages]
abstained = ABSTAIN.lower()[:40] in answer.lower()
return {..., "grounded": abstained or (bool(cited) and not invalid)}
Only 3 passages given, but answer cites [7] — fabricated citation. No citations at all — no traceability. Both are deemed ungrounded.
This is structural validation, not semantic: it cannot ensure that [1] actually supports the first passage. That’s LLM evaluation (faithfulness scoring) in testing. But it’s cheap, deterministic, and runs on every request — it blocks the most outrageous cases.
3. 🧭 Why This Approach, Not Others
Why SQLite + linear scan instead of vector DB?
The corpus size handled in this project is tens to thousands of chunks. At this scale, pure Python scanning takes from a few milliseconds to dozens — fully sufficient. Vector databases mainly solve million or even ten-million approximate nearest neighbor problems, which introduces an extra service and complex deployment logic at such scales.
Our code explicitly sets this boundary: when chunk count exceeds several thousand, switch _dense to pgvector or HNSW — the rest of the pipeline remains unchanged. First define where a solution fails, rather than immediately adopting heavy tools.
This reflects pragmatic engineering thinking: not every problem needs a cannon to kill a mosquito, especially when system complexity hasn’t reached that level yet. We prefer investing time in refining small, elegant toolchains over introducing unnecessary abstractions and dependencies from the start.
📌 Key Insight: Data scale determines tech choice boundaries. Prematurely introducing complex systems may bury future maintenance costs.
| | | — |
Why Not LangChain / LlamaIndex?
The entire pipeline is only a few hundred lines of code. Each stage’s input/output can be printed and inspected. Debugging retrieval quality is mostly about “checking intermediate results,” which these frameworks hide.
In model tuning or debugging retrieval errors, seeing each chunk’s vector and score directly is very useful. While LangChain and LlamaIndex offer powerful abstractions, they are too deeply encapsulated, making debugging difficult. We prefer a transparent, controllable system over one that runs blindly via config files.
This is also the essence of “tools serving me”: not using frameworks for their own sake, but choosing systems that quickly expose problems.
📌 Key Insight: Debugging efficiency matters more than encapsulation depth. In small-scale experiments, transparency and observability beat high-level abstraction.
| | | — |
Why Not Use Score Thresholds to Reject Answers?
Reranker scores vary with model changes — for example, downgrade backend gives 0–1 coverage, while jina outputs logits. Hardcoding a threshold will likely fail when switching models.
Therefore, we don’t use score thresholds to reject answers but instead delegate rejection logic to explicit rules in the prompt, plus citation validation as a fallback. Only in extreme cases like “nothing retrieved” do we short-circuit before model switching.
This avoids threshold失效 due to model switching and makes system behavior more predictable and controllable.
🩸 Blood-tears Reminder: Don’t use a static threshold to control dynamic reranker scores. They change with model versions, training data, even token distribution. Switching models can cause logical collapse.
4. 🔬 Common Follow-ups
Q: How to debug “The document is there but not found”?
This scenario is common among RAG practitioners. A direct way to troubleshoot is calling the POST /rag/search endpoint and paying attention to bm25_rank and dense_rank in the response.
These two rankings represent different retrieval strategies:
- BM25 Rank: Based on statistical models of term frequency and document length, suitable for keyword matching.
- Dense Rank: Calculated via vector similarity, better for semantic understanding.
If neither path ranks the target paragraph in top 20, the issue likely lies in chunking or tokenization — e.g., text cut too finely or keywords not recognized. If it enters top 20 but is ultimately discarded, the reranker (re-ranker) probably did the dirty work — filtering out otherwise suitable segments.
So debugging by stages and checking ranks rather than guessing final results is much more efficient. It’s like driving to a crossroad: first check traffic lights, then road conditions, and finally decide which path to take — not just rush in blindly.
📌 Key Takeaway: For “document exists but not found” issues, inspect bm25_rank and dense_rank paths separately to determine if it’s a chunking or reranker logic problem.
Q: English query, Chinese docs — does it work?
This touches the limitation of lexical retrieval. We use semantic search via vector space, but input and output must be language-consistent.
Example: A test question passed in downgrade backend but failed after adding an English document. Originally just a lucky overlap, now the issue surfaced.
The question now explicitly declares requires: ["semantic_embedder"], meaning it must rely on semantic embedding models — which are highly sensitive to language consistency.
In short, if you ask in English but only provide Chinese docs, the system finds no semantic connection points in vector space and thus fails to retrieve. This is one of the fundamental differences between semantic and lexical retrieval — the former understands “meaning,” while the latter only matches “literal”.
📌 Key Takeaway: Lexical retrieval cannot cross-language match; semantic search requires consistent input/output language, otherwise it fails due to vector space incompatibility.
Q: Is Overlap Necessary?
This is subtle. When an answer spans two chunk boundaries, overlap becomes key.
We usually set chunks around 150 characters — conservative. If longer, the chunk topic may become blurred, affecting retrieval accuracy. If the answer itself straddles a chunk boundary, overlap helps “re-assemble” the information.
More importantly, we enforce a rule: no cross-title. This ensures each chunk’s topic remains as singular as possible, avoiding confusion from inconsistent titles.
For example, a document titled 「财务系统配置」 (Financial System Configuration) has segments:
-
- User permission settings
-
- Database connection configuration
-
- Log output strategy
If we don’t strictly follow title boundaries during chunking, one chunk might contain both user permissions and database connections — a fragmented chunk that impacts retrieval efficiency and may cause semantic drift.
📌 Key Takeaway: Appropriate overlap in chunking helps cross-segment matching, but avoid cross-title chunks to ensure semantic consistency.
5. 🛠 Roll Your Own
This section isn’t about “how to do it,” but “how to figure out what to do.” The real technical details often lie in the process of pushing through and coding yourself. So don’t just read how others did it — get hands-on.
1. Write a Function Chunking by Headings, Test It on a Doc with Shell Code Blocks
Initially, we wanted to understand how content starting with ### should be extracted. This seems simple but easily fails when dealing with nested structures, special characters, and shell script blocks.
We wrote a chunking function that splits documents by ### level-1 headings. Then tested it on a document containing shell scripts:
### Project Startup Process
```bash
#!/bin/bash
mkdir -p /tmp/project
ls -la /tmp/project
Deployment Configuration
Some deployment-related configuration notes.
The function correctly extracted two segments: the first was the shell script block under "Project Startup Process," and the second was text under "Deployment Configuration." This test confirmed that chunking logic behaves well in complex document structures.
#### 2. Handwrite BM25, Validate with Three Small Docs: Rare Words Ranked First
In retrieval systems, BM25 is a classic but often overlooked algorithm. To understand why it works, we handwrote a simplified version.
Assume three small documents:
| Doc | Content |
| ------ | ------ |
| D1 | Rare word A B C |
| D2 | Common word B C D |
| D3 | Common word C D E |
Query with "Rare word A": result is D1 ranked first. Because rare words appear frequently in this document and rarely elsewhere, it fits BM25 logic.
This small experiment confirmed that BM25 prioritizes documents containing query terms that are rare across the corpus — hence better than simple matching or TF-IDF for relevance ranking.
#### 3. Add BM25 + RRF to a Vector-Only System, Compare Results with Numbered Queries
Originally, the system only used vector similarity for results, but performance was unsatisfactory: some semantically similar documents with different keywords were ranked lower.
We introduced BM25 as an additional sorting factor and used RRF (Reciprocal Rank Fusion) to merge vector and BM25 rankings. Benefits:
- Vector retrieval handles "semantically similar" content;
- BM25 handles "keyword-precise" content;
- RRF combines both, outputting a more balanced and reasonable ranking.
Example query Q1:
> **Q1**: List system change records from the past year
After adding BM25 and RRF, results better match user expectations:
- Result 1: A document with keywords like "change", "record", "year" (high BM25 rank)
- Result 2: Semantically similar but not explicitly mentioning keywords (high vector similarity)
This combination effectively improves recall and relevance scores.
#### 4. Implement `check_citations`, Feed It a Fake Citation Answer
In knowledge base Q&A systems, models sometimes fabricate citations. For example, an answer mentions "see reference [123]" but that citation doesn’t exist in the database.
We implemented a `check_citations` function to validate references:
```python
# Example logic
for citation in answer.citations:
if citation not in valid_sources:
raise ValueError(f"Invalid citation: {citation}")
During testing, we fed the model a fake citation answer — the function accurately identified and raised an error. This confirms our validation mechanism works.
5. Place a Document with Injection Statements in Knowledge Base, Confirm It Doesn’t Enter Model Context
This is a critical step: we worried that malicious or test content written directly into the knowledge base might pollute model input — e.g., SQL injection, shell commands, or formatting statements.
We placed a document containing:
SELECT * FROM users WHERE id = 1;
Then confirmed:
- The model does not use this document content as context in answer generation;
- The model does not attempt to execute this SQL.
This shows the system’s context cleaning mechanism is effective, preventing malicious content from entering the model reasoning pipeline.