Contents

RAG from Fundamentals to Advanced: A Panoramic Guide to Vector Retrieval, Knowledge Graphs, and Agentic RAG

LLM & RAG
#RAG#LLM#Knowledge Graph#GraphRAG#Agentic RAG#Document Parsing#Interview Questions

RAG (Retrieval-Augmented Generation) is one of the most widely adopted and fastest-evolving techniques in production LLM applications today. This post starts from first principles, covers the engineering optimizations and advanced approaches, then dives into knowledge graph construction and its use in RAG, and closes with Agentic RAG and the directions of evolution beyond 2026, with frequently asked interview questions and reference answers at the end.


1. Why RAG Is Needed

Throwing a question directly at an LLM runs into four unavoidable flaws:

  1. Knowledge cutoff: the knowledge in the model’s parameters is frozen at training time — it knows nothing about the API docs released yesterday or the meeting notes from last week.
  2. Hallucination: the model is fundamentally predicting the next token; even when it does not know the answer, it will confidently make one up.
  3. Private data is invisible: internal wikis, contracts, and tickets were never part of the training corpus.
  4. No traceability: parametric knowledge cannot tell you “which section of which document this sentence came from” — a fatal weakness in legal, medical, and operations scenarios.

The RAG idea is refreshingly plain: stop expecting the model to memorize everything — let it “open the book and look things up” before answering. Turn an external knowledge base into a searchable system, retrieve the passages most relevant to the question, splice them into the prompt, and let the LLM generate the answer — knowledge can then be updated in real time, sources can be cited, and retrieval quality can be measured and optimized on its own.

The RAG concept was proposed by Lewis et al. in 2020 (arXiv:2005.11401), originally as an end-to-end differentiable “dense vector retriever + generator” architecture; what the industry calls RAG today has generalized into the engineering paradigm of “retrieval system + LLM”.

2. RAG Fundamentals

2.1 The Three-Stage Pipeline: Indexing → Retrieval → Generation

Naive RAG: offline indexing and online retrieval-generation dual paths

Offline indexing

  • Chunking: split long documents into retrieval-friendly segments. Common strategies: fixed length (e.g., 512 tokens with 50–128 overlap), recursive separators (paragraph → sentence → character), or document-structure-aware splitting (Markdown headings, HTML tags, code function boundaries).
  • Embedding: use an embedding model (e.g., BGE, text-embedding-3, E5, GTE) to map each chunk to a dense vector ed∈R768∼1536\mathbf{e}_d \in \mathbb{R}^{768 \sim 1536}.
  • Storage: write the vectors together with the original text and metadata (source, title, page number, timestamp) into a vector database (FAISS, Milvus, Qdrant, pgvector, Weaviate, etc.).

Online question answering (Retrieval + Generation)

  1. The user’s question is likewise encoded as eq\mathbf{e}_q;
  2. Retrieve the Top-K passages by cosine similarity from the vector store:
score(q,di)=cos⁡(eq,edi)=eq⋅edi∥eq∥ ∥edi∥\mathrm{score}(q, d_i) = \cos(\mathbf{e}_q, \mathbf{e}_{d_i}) = \frac{\mathbf{e}_q \cdot \mathbf{e}_{d_i}}{\|\mathbf{e}_q\|\,\|\mathbf{e}_{d_i}\|}
  1. Exact scanning is O(N)O(N); in practice ANN (approximate nearest neighbor) indexes accelerate it: HNSW (hierarchical navigable small-world graph, arXiv:1603.09320), IVF (inverted-file clustering), ScaNN, and others, trading a small loss of recall for millisecond-level queries;
  2. Assemble “system instruction + retrieved passages + user question” into a prompt, let the LLM generate the answer, and require citations by source number (e.g., [1][3]).

2.2 A Minimal Working Example

No framework needed — sentence-transformers + numpy is enough to run the core path, which makes RAG’s “skeleton” easy to understand:

import numpy as np
from sentence_transformers import SentenceTransformer

# ---------- 1) Offline indexing ----------
docs = [
    "Sionna 是 NVIDIA 开源的可微分无线系统仿真库,基于 TensorFlow。",
    "38.901 §7.7 定义了链路级信道模型 CDL 与 TDL,每模型 24 簇。",
    "RAG 通过检索外部知识库缓解大模型幻觉,并支持答案溯源。",
]
model = SentenceTransformer("BAAI/bge-small-zh-v1.5")
emb = model.encode(docs, normalize_embeddings=True)   # [3, 384], L2-normalized

# ---------- 2) Retrieval ----------
def retrieve(query: str, k: int = 2):
    q = model.encode([query], normalize_embeddings=True)[0]
    sims = emb @ q                    # After normalization, inner product == cosine similarity
    idx = np.argsort(-sims)[:k]       # Top-K
    return [(docs[i], float(sims[i])) for i in idx]

# ---------- 3) Generation (feed the retrieved results into the prompt for the LLM) ----------
query = "CDL 模型有多少个簇?"
ctx = "\n".join(f"[{i+1}] {d}" for i, (d, _) in enumerate(retrieve(query)))
prompt = f"仅根据以下资料回答,并标注引用编号:\n{ctx}\n\n问题:{query}"
print(prompt)

The ceiling of Naive RAG is visible in this very code: single-round vector retrieval, fixed chunking, no reranking — the moment the question’s wording diverges semantically from the document’s, or the answer must combine several passages, retrieval misses. That is exactly where the optimizations in the next section start.

2.3 Choosing Between RAG and Fine-tuning

DimensionRAGFine-tuning
What it solvesInjects knowledge (facts, documents, timely information)Injects capability/style (format, tone, domain behavior)
Knowledge updatesJust update the index — minute-levelRetrain/redeploy — day-level, and recurring
TraceabilityCitations supported nativelyNot traceable
Hallucination mitigationStrong (answers anchored to retrieved evidence)Weak (can still fabricate parametric knowledge)
CostOne extra retrieval at inference time; no training costData annotation + training + version management
Catastrophic forgettingNoneYes
Private dataData stays in your own store, filterable by permissionData enters the weights — larger leak surface

In one sentence: “Use RAG to change knowledge, use fine-tuning to change behavior” — and the two are often combined: fine-tuning teaches the model the domain voice and output format, while RAG supplies the facts.

3. RAG Optimization Techniques and Advanced Approaches

3.1 A Four-Stage Optimization Map Across the Pipeline

The industry has evolved Naive RAG into Advanced RAG / Modular RAG: decompose the pipeline into independently replaceable modules (arXiv:2407.15181 proposes LEGO-style module orchestration) and optimize module by module, stage by stage.

RAG four-stage optimization technique map

1) Pre-retrieval — fix the question

  • Query rewriting/expansion: rewrite colloquial questions into retrieval-friendly phrasing; multi-query expansion generates several variants, retrieves each, then fuses the results.
  • HyDE (arXiv:2212.10496): have the LLM first “hallucinate” a hypothetical answer document, then use that hypothetical document for vector retrieval — the vector distance between document and document is closer than between question and document.
  • Query decomposition: split compound questions into sub-questions (“What are the X of A and B?” → two queries), retrieve each, then aggregate — solving “one retrieval cannot cover everything”.
  • Routing and intent detection: decide which store to search and whether to search at all (chit-chat gets answered directly).

2) Retrieval — fix the index and recall

  • Hybrid search: BM25 sparse retrieval (strong at exact term matching, domain jargon, model numbers) + dense vector retrieval (strong at semantic generalization), dual-path recall fused with RRF (Reciprocal Rank Fusion):
RRF(d)=∑r∈检索器1k+rankr(d),k≈60\mathrm{RRF}(d) = \sum_{r \in \text{检索器}} \frac{1}{k + \mathrm{rank}_r(d)}, \qquad k \approx 60

RRF uses only ranks, not scores, naturally sidestepping the problem of incomparable score scales across different retrievers:

def rrf(rank_lists, k=60):
    """rank_lists: an ordered list of document ids returned by each retriever"""
    score = {}
    for ranks in rank_lists:
        for pos, doc_id in enumerate(ranks):
            score[doc_id] = score.get(doc_id, 0) + 1.0 / (k + pos + 1)
    return sorted(score, key=score.get, reverse=True)
  • Advanced chunking strategies: structure-aware chunking (by heading or function boundaries), semantic chunking (split where the vector similarity between adjacent sentences drops sharply), late chunking (embed the whole long text first, then split and pool, preserving global context — Jina 2024), and pre-generating a “contextual summary” for each chunk to prepend before encoding (Anthropic’s contextual retrieval, reported to cut the retrieval failure rate by ~49%, and by ~67% when combined with reranking).
  • Metadata filtering: filter by time range, department, or document type before vector retrieval to shrink the candidate space.
  • Small-to-big / parent-document retrieval: match precisely at fine granularity (sentence level) but return the coarser unit it belongs to (paragraph/whole section) as the generation context — getting both match precision and information completeness.

3) Post-retrieval — fix the context

  • Reranking: loosen the initial Top-K recall to 50–150, then use a cross-encoder (bge-reranker, Cohere Rerank, ColBERT-style late interaction) to precisely rank each question–passage pair and keep the top 5–10. A bi-encoder encodes question and document independently — fast but coarse; a cross-encoder lets them interact fully in the attention layers — accurate but slow — hence its use only on small candidate sets.
  • Context compression: LLMLingua-style methods drop low-information tokens, mitigating “lost in the middle” (arXiv:2307.03172: model performance drops sharply when key information sits in the middle of a long context) while saving token cost.
  • Deduplication and diversity: MMR (maximal marginal relevance) prevents the Top-K from being all near-duplicate passages.

4) Generation and evaluation — close the loop

  • Prompt level: require “explicitly refuse when the material is insufficient” and per-sentence citation numbers.
  • Evaluation metrics split into two layers:
    • Retrieval quality: Recall@k, MRR, nDCG (with a labeled set);
    • Generation quality: faithfulness (whether the answer sticks to the retrieved evidence — a direct measure of hallucination), answer relevance (whether it addresses the question), context precision/recall. RAGAS (arXiv:2309.15217) uses LLM-as-judge to compute these metrics automatically, paired with a fixed evaluation set to form a regression loop — optimizing RAG without an evaluation set is tuning blind.

3.2 Multi-Hop Reasoning and the Introduction of GraphRAG

Vector retrieval has a structural flaw: it can only recall passages that are literally or semantically close to the question. It is powerless for questions like:

“Which state is the alma mater of the CEO who acquired company X located in?”

The answer needs three hops — acquisition → CEO → alma mater → state — with each hop’s information scattered across different documents, and no single query embedding can approximate all the passages at once. There are two ways out: decompose the question into multiple rounds of retrieval (the Agentic approach, see Section 8), or organize the knowledge itself as a graph — which is GraphRAG.

4. Building Knowledge Graphs

4.1 Knowledge Graph Basics

The atomic unit of a knowledge graph is the triple:

(头实体 h, 关系 r, 尾实体 t)例:(Sionna, 实现, 38.901 CDL 模型)(\text{头实体 } h,\ \text{关系 } r,\ \text{尾实体 } t) \qquad \text{例:}(Sionna,\ \text{实现},\ \text{38.901 CDL 模型})

Graph structure natively supports multi-hop reasoning: start from any entity and walk along the edges to combine related facts at any hop count — something vector similarity cannot do.

4.2 Traditional Construction Pipeline vs. LLM-Driven Construction

The classic pipeline (the Neo4j / graph database ecosystem): schema design → entity recognition (NER) → relation extraction (RE) → entity alignment/disambiguation → knowledge fusion → loading. The pain point is the domain-transfer cost of NER/RE — switch domains and you must re-annotate data and retrain models.

In the LLM era, graph construction has become prompt-driven extraction: give the LLM a text span plus an output format (JSON schema), and it directly emits entities and relation triples:

EXTRACT_PROMPT = """从下面文本中抽取知识图谱三元组。
只输出 JSON 数组,元素格式 ["头实体", "关系", "尾实体"]。
实体用规范化的名词短语,关系用简短动词短语。

文本:{chunk}
"""
# triples = json.loads(llm(EXTRACT_PROMPT.format(chunk=doc.text)))

The engineering points that go with it:

  • Entity disambiguation/alignment: “北大”, “Peking University”, and “PKU” must normalize to the same node — a three-step approach: alias table + vector-similarity clustering + LLM adjudication;
  • Schema constraints: a predefined whitelist of entity/relation types prevents the LLM from freelancing two spellings of the same relation (e.g., “located_in_province” vs. “located_province”) and fragmenting the graph;
  • Incremental updates: when a document changes, re-extract only the affected TextUnits and do a triple-level diff.

4.3 The GraphRAG Indexing Pipeline (Microsoft GraphRAG)

Microsoft’s GraphRAG (arXiv:2404.16130, From Local to Global) standardizes the above into a single indexing pipeline whose core innovations are community detection + hierarchical summarization:

GraphRAG indexing flow and Local/Global query modes

  1. TextUnit splitting: slice the corpus into overlapping text units that serve as fine-grained anchors for later extraction and citation;
  2. LLM extraction: for each TextUnit, extract entities, relations, and claims (structuring even the event-style descriptions of “what an entity did”);
  3. Graph construction and disambiguation: merge same-name entities into an attributed graph;
  4. Hierarchical Leiden clustering: recursively partition the graph into communities (hierarchical Leiden), yielding a coarse-to-fine multi-level community tree — each entity belongs to one community at every level;
  5. Community report generation: bottom-up, generate an LLM summary for each community (member entities, relations, key events, overall description), forming “topic-level knowledge”.

Once indexed, queries take two paths:

ModeMechanismBest for
Local SearchQuestion → matched entities → expand the neighborhood subgraph → link back to the original TextUnits“What is the relationship between X and Y?” (specific entities, few hops)
Global SearchTraverse all community reports at one level → Map stage answers per community → Reduce stage aggregates“What topics is this corpus discussing overall?” (corpus-level summarization)

The cost deserves an honest statement too: indexing makes heavy LLM calls (full-corpus per-unit extraction + per-community summarization), with token cost and build time far above a vector index; frequently updated data makes graph maintenance expensive. GraphRAG therefore suits corpora that are static or low-frequency-updated and need global understanding and multi-hop reasoning.

4.4 Alternative Graph-Based Indexing Approaches

  • RAPTOR (arXiv:2401.18059): recursive clustering + summarization builds a tree (leaves = original chunks, internal nodes = cluster summaries); at query time, mix retrieval across levels — no explicit entity extraction needed, a lightweight take on “hierarchical global understanding”.
  • HippoRAG (arXiv:2405.14831): inspired by hippocampal indexing theory; open extraction builds the graph and personalized PageRank scores retrieval, achieving multi-hop association in a single retrieval pass at far lower cost than GraphRAG’s community summaries.
  • LightRAG (arXiv:2410.05779): dual-level retrieval (low-level entities/relations + high-level topic keywords), drops community reports, friendly to incremental updates, lightweight to ship.
  • Think-on-Graph (ToG) (arXiv:2307.07697): no pre-built community summaries; at inference time the LLM performs depth-first exploration on the graph, expanding candidate paths hop by hop and pruning by relevance — handing “graph traversal” itself to the LLM as dynamic decisions.

5. Applying Knowledge Graphs in RAG

Graphs enter a RAG system in three typical patterns, from least to most invasive:

  1. The graph as one retriever (hybrid architecture): the vector store keeps working as usual; meanwhile maintain an entity index — entities recognized in the query go through graph retrieval (1–2 hop neighborhoods
    • linked original text), fused with the vector recall via RRF before reranking. Lowest retrofit cost, markedly stronger multi-hop ability.
  2. GraphRAG-style global index: the full pipeline from Section 4.3 with Local/Global dual-mode querying. Suits report analysis, intelligence assessment, and compliance auditing — scenarios that “need both the facts and the big picture”.
  3. Graph-constrained generation: at generation time, use the graph to validate factual consistency (entity relations in the answer must have a supporting path in the graph), upgrading hallucination detection from “LLM self-assessment” to “structured verification”.

Selection criteria (a frequent interview topic):

  • Questions dominated by literal/semantic similarity (FAQs, document QA) → vector RAG suffices;
  • Questions frequently need cross-document association, aggregate statistics, or global summarization → GraphRAG;
  • Graph quality hinges on extraction quality: botched entity disambiguation makes graph retrieval inject noise instead;
  • High update frequency or tight budget → prefer lightweight options such as RAPTOR / LightRAG / HippoRAG.

6. PDFs and DOCX Files with Charts and Tables: Document-Level RAG Processing

So far we have assumed “the document is already clean text”. In reality, enterprise corpora are PDFs and DOCX files with tables, charts, formulas, and multi-column layouts — feeding raw pdfplumber text into RAG yields garbage: scrambled reading order, tables collapsed into one-line strings, and charts entirely lost. This section walks through the processing pipeline and tool choices across the indexing, retrieval, and generation stages.

6.1 Why Is It Hard

  • A PDF is a “what-you-see-is-what-you-get” instruction set, not structured text: the text stream order ≠ the visual reading order; two-column layouts, headers/footers, and footnotes interleave; tables are just line segments plus scattered text with no semantic boundaries; charts are a blob of pixels.
  • Tables are the disaster zone: merged cells, nested headers, tables spanning pages — after naive extraction the row–column–value relations are all lost, and an LLM cannot reconstruct 2D structure from a 1D string.
  • Charts (bar/line/pie) carry numbers and trends; text extraction gains nothing from them.
  • DOCX is relatively friendly: OOXML carries semantic tags (heading levels, tables, inline images), but inline images are still black boxes; and Office charts are often OLE objects — whose underlying data (the Excel source) can be extracted, a unique DOCX advantage over PDF.

6.2 Indexing Stage: Two Technical Routes

Dual-route RAG pipeline for PDFs/DOCX with charts

Route A: Text-based parsing (Parse → Serialize) — the mainstream approach

Pipeline: layout analysis (reading order, block types) → table structure recognition (convert to Markdown/HTML) → formula OCR (convert to LaTeX) → chart region cropping → VLM-generated chart descriptions → structure-aware chunking (split by heading/table/chart unit, keeping page numbers and bounding boxes as metadata for citation positioning) → text embedding into the store.

# Docling (IBM open source, MIT): PDF/DOCX -> structured document object -> Markdown
from docling.document_converter import DocumentConverter
from docling.chunking import HybridChunker

conv = DocumentConverter()
result = conv.convert("quarterly_report.pdf")   # Parses layout/tables/images
doc = result.document

chunker = HybridChunker()                       # Structure-aware chunking; tables stay Markdown
for chunk in chunker.chunk(doc):
    meta = chunk.meta           # Heading path, page number, element type (table/figure/...)
    text = chunk.text           # Tables serialized to Markdown, ready for embedding
    # vector_store.upsert(id=..., text=text, metadata={...meta})

The key trick for chart handling is dual representation: generate a “VLM summary + key values” text for each chart/table used for retrieval (queries hit the summary), while keeping the original cropped image (an asset-id pointer) for looking at the image at generation time — retrieve by text, answer by pixels.

Route B: Vision-native (no OCR) — the ColPali paradigm

Render each PDF page as an image, encode it with a VLM (PaliGemma/Qwen-VL backbone) into per-patch multi-vectors (roughly 1024 128-dimensional vectors per page), and score retrieval with ColBERT-style late-interaction MaxSim:

score(q,P)=∑i=1∣Eq∣max⁡j  eq(i)⋅eP(j)\mathrm{score}(q, P) = \sum_{i=1}^{|E_q|} \max_{j} \; \mathbf{e}_q^{(i)} \cdot \mathbf{e}_P^{(j)}
  • Pros: skips the entire fragile OCR/layout-analysis/chunking pipeline; charts, formulas, scans, and complex layouts are natively retrievable (“the page that looks like the answer”);
  • Cons: storage inflates by ~30× (multi-vectors), needing pooling/quantization compression (engineering optimizations such as the Visual RAG Toolkit and PULSAR); the generation side must use a multimodal LLM to take page screenshots.

DOCX specifics: use python-docx / Unstructured to split directly by XML semantics (heading/table/image) — no layout analysis needed; for charts, prefer extracting the OLE underlying data into Markdown tables (numeric QA accuracy far exceeds “reading values off the image”); purely scanned DOCX should go down Route B.

6.3 Retrieval Stage

  • Route A: chart/table chunks participate in ordinary hybrid retrieval via “summary + key values”; metadata filtering (element type = table/figure, page range, document source);
  • Route B: encode the query, run MaxSim against the page multi-vectors, and return the whole page screenshot on a hit;
  • When both routes coexist, fuse the results with RRF, then rerank (a VLM can visually rerank on “does this page/pass contain the answer”);
  • Citation positioning: the page + bbox carried by each chunk lets answers jump to and highlight the exact location in the original document.

6.4 Generation Stage

GeneratorInputBest for
Text LLMTable Markdown, chart VLM summariesSummary-style/trend-style questions; low cost
Multimodal LLM (GPT-4o/Claude/Qwen-VL)Retrieved passages + original chart screenshotsQuestions needing “read values off the image, compare magnitudes, describe trends”
Code / NL2SQLUnderlying table data (DataFrame)Precise numeric computation, aggregation and sorting — never let a VLM do chart arithmetic in its head

Engineering points: control the token count when serializing tables to Markdown (for large tables give only the relevant rows/columns, or CSV slices); VLM reading carries hallucination risk — for number-sensitive scenarios use the two-step “extract data → compute with code → fill in the conclusion” method.

6.5 Tool Overview and Comparison

ToolTypeTablesChartsFormulasDeployment/LicenseHighlights
MinerU (OpenDataLab)Local parsing pipelineStrongCrop + describeStrong (UniMERNet → LaTeX)Open source AGPL, GPU-friendlyThe PDF-Extract-Kit full stack; high accuracy on academic/complex layouts
Docling (IBM)Local parsing libraryStrongExtract + region metadataSupportedMIT/Apache, fully localHybridChunker structure-aware chunking, DocTags VLM (Granite-Docling-258M), native LangChain/LlamaIndex/Haystack integration, ships with an MCP server
UnstructuredPartitioning engine (OSS + SaaS)MediumPartition markingWeakOpen source + commercial APIUnified partition model across 30+ formats; full enterprise ecosystem; good docx/pptx semantic handling
LlamaParse (LlamaCloud)Cloud VLM parsingStrongVLM-mode descriptionSupportedSaaS, per-page billingDeep LlamaIndex integration; VLM mode works well on complex tables/charts
MarkerLocal conversionMediumImage extractionSupportedGPL (commercial use requires a license)Fast PDF → Markdown with a PyMuPDF fallback; good for bulk rough conversion
DeepSeek-OCR (DeepSeek-AI)Open-source document VLMStrong (Markdown tables out of the box)Image/text descriptionStrong (formulas → LaTeX)MIT, self-hosted (~3B)DeepEncoder “optical context compression” slashes visual tokens; accurate on scans, complex layouts, and reading order; vLLM/Transformers ecosystem
dots.ocr (Xiaohongshu Hi Lab)Open-source document VLMStrong (layout + content in one pass)Regions + reading orderSupportedMIT, lightweight 1.7B, localA single model unifying layout detection and content recognition; 100+ languages; switch tasks by changing the prompt; fast inference
ColPali / ColQwenVision multi-vector retrievalParsing-freeNativeNativeOpen-source modelsNo OCR, no chunking; page-level retrieval; storage needs multi-vector optimization
Traditional libraries (PyPDF2/pdfplumber/python-docx)Rule-based extractionWeakNoneNoneFreeOnly fit simple-layout, digital-native PDF/DOCX; guaranteed to fail on complex layouts

Worth noting is the open-source document VLM category that emerged in 2025 (DeepSeek-OCR, dots.ocr, plus PaddleOCR-VL, olmOCR, etc.): a single model end-to-end emits Markdown/JSON, its accuracy on scans and complex layouts already approaches or surpasses traditional parsing pipelines, and MIT-class licenses are commercial-friendly. Newer MinerU releases are adopting VLMs as well. If you want to self-host “one model does all parsing,” prefer this category; if you don’t want to self-host, LlamaParse or a general-purpose VLM (GPT-4V/Qwen-VL) is the equivalent option.

Selection advice:

  1. Tight budget, sensitive data → Docling / MinerU deployed locally (Docling has a friendlier ecosystem and license; MinerU is stronger on formulas and academic layouts); to self-host a single end-to-end parsing model, or for scan-heavy corpora, switch to DeepSeek-OCR / dots.ocr (MIT-licensed, lightweight to deploy);
  2. Moderate document volume, want it hassle-free → LlamaParse or similar cloud VLM parsing, pay per page;
  3. Charts/scans/extremely complex layouts, and multimodal generation is affordable → layer the ColPali route on top as a page-level retrieval fallback;
  4. Table numeric QA is the core scenario → whichever route you pick, structure the tables into Markdown/SQL and use code execution on the generation side to guarantee precision.

7. Engineering Toolchain and Selection: Tools for Every Stage

The optimizations so far were organized by method; this section lays out the selection decisions engineering actually has to make, organized by stage: which tool or model to use at each link, their respective pros and cons, and open-source projects you can deploy directly.

Five-stage selection overview of the end-to-end RAG toolchain

7.1 Stage-by-Stage Tool Comparison

1) Document parsing and chunking: see Section 6.5 for the parsing tool comparison (MinerU/Docling/LlamaParse/DeepSeek-OCR/dots.ocr, etc.). At the chunking-library level: LlamaIndex’s node-parser family (SemanticSplitter, SentenceWindow, MarkdownNodeParser), LangChain TextSplitters, and the lightweight purpose-built Chonkie (token-level semantic chunking, pure Python with no heavy dependencies).

2) Embedding models (pick by language and task using the MTEB leaderboard):

ModelLicenseStrengthsWeaknesses
BGE-M3 (BAAI)Open source, MITOne model outputs dense + sparse + multi-vector — hybrid retrieval out of the box; strong in Chinese and English; 8K contextSelf-hosting needs a GPU to reach full throughput
jina-embeddings-v3Open weights89+ languages, Matryoshka dimensions truncatable (1024 → 256 to save storage), task-specific LoRA adaptersThe API tier has a free-quota cap
text-embedding-3-large (OpenAI)APIHassle-free, broad ecosystem compatibilityClosed source, data leaves your boundary, 3072-dim storage is expensive
voyage-3.5 family (MongoDB Voyage)APIStrong finance/legal/medical domain editions, 128K contextClosed source
Cohere Embed v4APINative image + text multimodal input, top of MTEBClosed source, billed per token
e5-mistral-7bApacheLLM-based embedding, high quality on long text7B inference cost is high

3) Vector storage:

SystemPositioningHybrid searchScaleOps burden
pgvectorPostgres extensionVector + full-text supported since 0.8Comfortable at millionsLowest (effectively free if you already run PG)
ChromaPrototyping/embeddedWeak100K–1MLow
FAISSLibrary (not a service)Requires bolting on BM25 yourselfBillions on a single machineYou wrap the service yourself
QdrantPurpose-built vector DB (Rust)Sparse vectors built inTens of millions–hundreds of millionsMedium, resource-efficient
MilvusDistributed vector DBSupportedBillionsHigh (many components)
WeaviateVector + inverted all-in-oneNative hybridHundreds of millionsMedium
OpenSearch/ESSearch engine with vectors addedThe strongest BM25Hundreds of millionsAn easy add-on if you already run ES

4) Retrieval and reranking: on the sparse side, BM25 (Elasticsearch/ OpenSearch/Tantivy) or learned-sparse SPLADE; fuse with RRF (see Section 3.1). Rerankers:

RerankerLicenseNotes
bge-reranker-v2-m3Open sourceMultilingual, the price-performance baseline; the default self-hosted pick
mxbai-rerank-v2Open sourceQwen2-based, strong on English
Cohere Rerank 4APIMultilingual + multimodal, state-of-the-art quality
Jina Reranker m0API / open weightsChunk-level reranking for long documents
LLM listwise (RankGPT-style)Any strong modelHand the candidate list to an LLM to rank — most accurate, most expensive, slowest

5) Evaluation and observability:

ToolPurposeNotes
RAGASMetric computation (faithfulness/relevancy/precision)LLM-as-judge, the de facto standard
DeepEvalUnit-test-style LLM evaluation, plugs into pytest/CIThe best engineering ergonomics
Arize PhoenixRetrieval/generation tracing + evaluation + dataset managementOpenInfer open specification
LangfuseFull-chain observability, A/B, cost tracking, evaluation regressionOpen source, self-hostable
TruLensThe “RAG triad” feedback functionsBroad framework integrations

6) Orchestration frameworks: LlamaIndex (a data framework with the richest RAG abstractions), LangGraph (graph-style agent orchestration, the default pick for Agentic RAG), Haystack 2.x (explicit pipelines, clean component swaps, widely deployed in enterprises), R2R (a REST-service backend).

7.2 Selection Guide

ScenarioRecommended stack
Prototype/personal (<100K chunks)Docling + BGE-M3 + pgvector/Chroma + RAGAS — runs on a single machine
Small-to-mid production (millions)MinerU/Docling + BGE-M3 or jina-v3 + Qdrant (hybrid) + bge-reranker-v2-m3 + LangGraph + Langfuse/Phoenix
Large-scale/multi-tenantLlamaParse or self-built parsing + voyage-3/embed-v4 + Milvus/OpenSearch + Cohere Rerank + DeepEval in CI
Data-sensitive, fully localAll open source: Docling + BGE-M3 + Qdrant + bge-reranker + a local LLM + RAGAS

Three decision shortcuts: Already on Postgres → start with pgvector, don’t adopt a dedicated store; Chinese/multilingual → BGE-M3 or jina-v3 over OpenAI; When retrieval quality falls short, add reranking first (the largest gain for the smallest change), then consider swapping the embedding model.

7.3 Deployable Open-Source Projects

End-to-end engines (one-command docker compose, with UI/permissions/ citations included):

ProjectLinkMapping to the chapters of this article
RAGFlowgithub.com/infiniflow/ragflowThe closest fit for “complex-document RAG”: DeepDoc layout/table parsing (Section 6), interpretable chunking templates, GraphRAG (Section 4), agent workflow orchestration (Section 8), citation positioning, evaluation views. Apache-2.0
Kotaemongithub.com/Cinnamon/kotaemonSelf-hosted chat-with-docs: chart/table QA out of the box, multi-LLM/embedding providers, local models, agentic pipeline configuration
R2Rgithub.com/SciPhi-AI/R2RProduction-grade REST backend: hybrid + KG + agentic search, built-in evaluation, auth/multi-tenancy — “Backend-as-a-Service for RAG”
Difygithub.com/langgenius/difyPlatformized LLMOps: visual RAG pipelines + agent orchestration + app publishing, friendly to non-engineering teams
Onyx (formerly Danswer)github.com/onyx-dot-app/onyxEnterprise search + QA: 40+ connectors (Confluence/Drive/Slack…), permission inheritance
Verbagithub.com/weaviate/VerbaWeaviate’s official end-to-end RAG app; a small codebase, great for learning and modifying
PrivateGPTgithub.com/zilliztech/private-gptFully local, offline document QA for privacy scenarios

Framework/component level (when building your own chain):

Evaluation: RAGAS github.com/explodinggradients/ragas · DeepEval github.com/confident-ai/deepeval · Phoenix github.com/Arize-ai/phoenix · Langfuse github.com/langfuse/langfuse

**If you just want one complete open-source reference implementation covering “complex PDF/DOCX parsing + index optimization + reranking + agentic

  • evaluation”: pick RAGFlow first; choose R2R for a backend-API shape; choose the LangGraph templates + Docling + Qdrant combo when you want to write the orchestration logic yourself.**

8. Agentic RAG

8.1 From “Pipeline” to “Decision Loop”

All the approaches so far are still a fixed pipeline: retrieval happens before generation, and happens exactly once. Agentic RAG hands the decisions — whether to retrieve, what to retrieve, how good the retrieval was — to the model to execute dynamically inside a loop (Agentic RAG survey: arXiv:2501.09136):

Agentic RAG: the plan-retrieve-reflect loop

Four key capabilities:

  • Planner/Router: judge the question’s complexity — answer directly / single-round retrieval / decompose into subtasks; pick a data source per subtask (vector store, graph, web, SQL, memory).
  • Retrieval as a tool: the retriever is demoted to one of the tools the agent can call, alongside code execution, database queries, and the browser.
  • Reflection and self-evaluation: after each retrieval round, assess the sufficiency and consistency of the evidence; if insufficient, rewrite the query or switch tools and retrieve again — iterate until convergence or a budget cap is hit.
  • Memory: short-term conversation memory + long-term user/task memory, avoiding repeated retrieval and supporting personalization.

8.2 Representative Methods

MethodCore mechanismSource
Self-RAGTrains the model to emit reflection tokens (Retrieve / ISREL / ISSUP / ISUSE), deciding autonomously when to retrieve and grading the evidencearXiv:2310.11511
CRAG (Corrective RAG)A separate retrieval evaluator labels documents “correct / ambiguous / incorrect”; on incorrect, discard and fall back to web search, with knowledge refinementarXiv:2401.15884
Adaptive-RAGRoutes by a question-complexity classifier: direct answer / single-round / multi-round iterative retrievalarXiv:2403.14403
RQ-RAG / various agentic pipelinesMulti-step agent workflows: query decomposition + multi-source orchestration + generation verification—
Deep Research-style productsMulti-agent long tasks: plan the report structure → parallel multi-round retrieval → cross-verification → synthesize into proseOpenAI / Gemini / open-source implementations

8.3 Agentic RAG and Reasoning (Reasoning RAG)

The change since 2025 is the fusion of RAG with reasoning models (System 2) (surveys: arXiv:2506.10408, arXiv:2507.09477): models like the o-series / R1 interleave retrieval actions inside the chain of thought (search inside CoT) — “look things up wherever the thinking goes”, with retrieval and reasoning alternating rather than retrieve-then-think. Two technical routes:

  • Prompt-engineering style: have the reasoning model call retrieval tools within its CoT (SimpleRL-RAG, Search-R1 style);
  • Training style: RL-fine-tune the model to learn “when to retrieve and what to retrieve” (RaR, DeepRetriever style).

The cost is latency and token spend rising several-fold — Agentic/Reasoning RAG is not the default answer; it is reserved for the 10%–20% of complex questions that a single retrieval cannot answer well.

9. The Future of RAG: Where It Is Heading

RAG technology evolution timeline

1. Will long context (Long Context) replace RAG? Million-token windows make “stuff the whole corpus into the prompt” look feasible, but three practical constraints keep RAG from dying: 1) cost and latency — stuffing full-length documents per request costs orders of magnitude more at inference; 2) lost in the middle (arXiv:2307.03172) — position-sensitive performance decay persists; 3) permissions and auditing — the retrieval layer natively supports filtering passages by user permission and logging citations. The mainstream consensus is fusion: RAG selects the material, long context chews on it — retrieve a small set of high signal-to-noise evidence and let the model cross-compare thoroughly within the long window.

2. Memory systems become a layer of their own RAG retrieves “knowledge about the world”; memory systems retrieve “the history of interactions” (Mem0, Letta/MemGPT, Zep, etc.). User preferences, long-running task state, and cross-session facts accumulate into a structured memory store, running in parallel with knowledge retrieval as a standard Agent component.

3. Multimodal RAG Retrieval targets expand from text to images, tables, audio, video, UI screenshots, and code. CLIP-style cross-modal embeddings + visual document retrieval (ColPali does late-interaction retrieval directly on page screenshots, skipping OCR parsing) make “retrieve page 7 of a chart-heavy PDF” a first-class citizen.

4. Graph + Agentic fusion Agentic RAG treats the knowledge graph as an explorable tool: the agent walks multi-hop paths on the graph and dynamically expands subgraphs as reasoning requires (the ToG idea, agenticized); GraphRAG’s community summaries serve as the agent’s “global map”. The 2025–2026 survey (arXiv:2507.16507) explicitly lists “Agentic GraphRAG” as an active direction for the next phase.

5. From RAG to Context Engineering The essence of the “RAG is dead” debate (multiple 2026 industry analyses): narrow Naive RAG (one-shot vector retrieval + concatenation) is indeed dying out, replaced by the broader context engineering — dynamically orchestrating “what goes into the limited context window, where it comes from, and in what structure”: retrieval, graphs, memory, tool outputs, compression, and ranking are all its instruments. RAG is no longer an architecture but a context-supplying capability.

6. Retrieval as infrastructure Hybrid retrieval becomes the default, reranking becomes routine, evaluation (RAGAS / end-to-end A/B) enters CI, and enterprise-grade RAG evolves into a data product with “permission governance, observability, and regression testing”.

10. Frequently Asked Interview Questions (Q&A)

Q1: Explain RAG in one sentence — what problem does it solve? A: Before generating, retrieve relevant evidence from an external knowledge base and place it in the context, solving the LLM’s four problems of stale knowledge, hallucination, invisible private data, and untraceable answers. In essence, it is an “open-book exam”.

Q2: What is the difference between RAG and fine-tuning? Which to use when? A: RAG injects knowledge, updates by just changing the retrieval store, and is traceable; fine-tuning injects behavior/style/format, bakes knowledge into the weights, costs a lot to update, and is untraceable. Frequently changing knowledge or citations required → RAG; output format, domain voice, task-specific capability → fine-tuning; the two can stack.

Q3: How do you chunk? How to set size and overlap? A: There is no universal value — it depends on the answer’s granularity: FAQ-style, one block per sentence; expository text, 256–512 tokens with 10–15% overlap; structured documents, split by heading/function boundaries to keep semantics intact. Advanced options: small-to-big (retrieve small, return big), late chunking, context-enriched chunks. Tune driven by evaluation: compare chunking schemes with Recall@k.

Q4: Retrieval recall is low — how to optimize systematically? A: Troubleshoot by stage — pre-retrieval: query rewriting/expansion, HyDE, query decomposition; retrieval: hybrid search (BM25 + vectors + RRF), metadata filtering, a stronger embedding model, better chunking; post-retrieval: rerank as a backstop. First build a labeled evaluation set (Recall@k/MRR), otherwise optimization is unmeasurable.

Q5: What is the principle of HyDE, and when does it apply? A: Have the LLM first generate a hypothetical answer document and retrieve with its embedding — because “document-to-document” is closer in vector space than “question-to-document”. Suits domains with heavy jargon where users’ phrasing diverges sharply from the documents’; the downside is reliance on the LLM’s priors — when the model knows nothing about the domain, the hypothetical document itself goes off track.

Q6: Why is reranking needed? What is the difference between bi-encoder and cross-encoder? A: A bi-encoder encodes query and document independently — precomputable and fast, but shallow interaction limits accuracy; a cross-encoder feeds (q, d) jointly through full attention — accurate, but every pair must be computed fresh, so it is slow. Hence the engineering pattern “coarse recall Top-100 → cross-encoder rerank to Top-5”, balancing efficiency and quality.

Q7: How do you evaluate a RAG system? A: Two layers: the retrieval layer uses Recall@k, MRR, nDCG (needs labels); the generation layer uses faithfulness (answer–evidence consistency, measuring hallucination), answer relevance, and context precision/recall, computable automatically with RAGAS’s LLM-as-judge. In practice, run a fixed evaluation set as regression plus online A/B.

Q8: How does RAG reduce hallucination? A: Retrieval quality is fundamental (garbage in, garbage out); prompt constraints (“answer only from the material; refuse when the material is insufficient”); require per-sentence citation numbers; after generation, verify with faithfulness checks (NLI or LLM adjudication) and regenerate on failure; for critical scenarios, layer a knowledge graph for structured fact validation.

Q9: What does GraphRAG solve over vector RAG? At what cost? A: It solves two things vector retrieval cannot: multi-hop association (graph paths natively connect scattered facts) and global understanding (community summaries support “what is this corpus about” queries). Costs: expensive LLM calls during indexing, complex graph maintenance, best suited to low-frequency-update corpora; for simple specific-entity questions it may not beat vector retrieval.

Q10: How is a knowledge graph built? How is entity disambiguation done? A: The mainstream in the LLM era is “schema constraints + prompt extraction” of triples, then entity alignment for normalization (alias table + vector clustering + LLM adjudication), with triple-level diffs for incremental updates. Disambiguation is the make-or-break factor for graph quality — done poorly, graph retrieval injects noise instead.

Q11: What does the Leiden algorithm do in GraphRAG? A: It performs hierarchical community detection on the extracted entity graph (Leiden improves on Louvain, guaranteeing community connectivity with more stable convergence). The community tree is summarized bottom-up, and Global Search is Map-Reduce over those community reports.

Q12: What is the difference between Self-RAG and CRAG? A: Self-RAG trains the model to emit reflection tokens, internalizing “should I retrieve, does the evidence support it, is the answer useful” into the model’s decoding process; CRAG leaves the generation model untouched and bolts on a lightweight retrieval evaluator that labels documents, triggering corrective actions (rewrite / fall back to web search) when retrieval is poor. The former changes the model; the latter changes the flow.

Q13: What is the essential difference between Agentic RAG and traditional RAG? A: Traditional RAG is a fixed pipeline (retrieve once → generate); Agentic RAG is a decision loop — the model autonomously plans the retrieval strategy, selects multi-source tools, evaluates the evidence, and iterates when it is insufficient. It suits multi-hop, cross-source, highly dynamic complex questions; the cost is latency and expense — unnecessary for simple questions.

Q14: With million-token long context, is RAG still necessary? A: Yes. The three constraints — cost/latency, lost-in-the-middle, and permission filtering with citation auditing — remain. The future is the fusion of “RAG selects the material + long context chews on it”, and generalizing RAG into context engineering.

Q15: How do you handle multi-hop questions (cross-document association)? A: Three routes: 1) query decomposition + iterative retrieval (Agentic); 2) the knowledge graph route (GraphRAG Local Search / HippoRAG’s PPR / ToG graph exploration); 3) RAPTOR’s hierarchical summary tree with cross-level retrieval. Production systems often combine 1) + 2).

Q16: How do you do RAG on PDFs containing tables and charts? A: Two routes at indexing time: 1) text-based parsing — layout analysis + table structure recognition (convert to Markdown/HTML) + formulas to LaTeX + charts cropped and described by a VLM, then structure-aware chunking into the store (tools like MinerU, Docling, LlamaParse); 2) vision-native — render whole pages to images and do multi-vector retrieval with ColPali-style models, no OCR. The key trick is dual representation for charts: summary text drives retrieval, the original image drives “looking at the picture” at generation time; for precise numeric questions, convert tables to data and compute via code/NL2SQL — don’t let the VLM do mental arithmetic.

Q17: How to choose between ColPali-style visual retrieval and traditional OCR parsing pipelines? A: ColPali skips the entire fragile OCR/layout/chunking pipeline and is natively friendly to charts, formulas, scans, and complex layouts, but storage inflates (thousands of vectors per page, needing pooling/quantization), the generation side must use a multimodal LLM, and passage-level citation positioning is weaker. Text-based parsing pipelines give precise citations and structured table data, with a mature engineering ecosystem. The common production pattern is hybrid: the text route as primary, the visual route as fallback for complex pages.

Q18: You are asked to build a production-grade RAG from scratch — how do you pick the tool stack? A: The shortest path per stage: parsing with Docling/MinerU (fully local for sensitive data) or LlamaParse (pay for convenience); for embeddings, BGE-M3 for Chinese/multilingual (dense + sparse all in one); for the vector store, pgvector if you already run Postgres, scaling to Qdrant/Milvus as volume grows; retrieval as hybrid + RRF, with bge-reranker-v2-m3 or Cohere Rerank for precision ranking; orchestration with LangGraph/Haystack; evaluation with RAGAS + DeepEval in CI, and Langfuse/Phoenix for online observability. The principle: at each stage, start with the minimal stack that is “good enough and replaceable”, let evaluation data drive upgrades — rather than piling on the full suite from day one.

11. References

  • Lewis et al., Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks, arXiv:2005.11401
  • Gao et al., Retrieval-Augmented Generation for Large Language Models: A Survey, arXiv:2312.10997
  • Singh et al., Agentic Retrieval-Augmented Generation: A Survey, arXiv:2501.09136
  • Retrieval-Augmented Generation with Reasoning: A Survey, arXiv:2507.09477; Reasoning-RAG survey, arXiv:2506.10408
  • Edge et al., From Local to Global: A Graph RAG Approach to Query-Focused Summarization, arXiv:2404.16130; GraphRAG official documentation
  • Sarthi et al., RAPTOR, arXiv:2401.18059; Gutiérrez et al., HippoRAG, arXiv:2405.14831; Guo et al., LightRAG, arXiv:2410.05779
  • Asai et al., Self-RAG, arXiv:2310.11511; Yan et al., Corrective RAG, arXiv:2401.15884; Gao et al., HyDE, arXiv:2212.10496
  • Es et al., RAGAS, arXiv:2309.15217; Liu et al., Lost in the Middle, arXiv:2307.03172
  • Malkov & Yashunin, HNSW, arXiv:1603.09320; Modular RAG, arXiv:2407.15181
  • Faysse et al., ColPali: Efficient Document Retrieval with Vision Language Models, arXiv:2407.01449; Docling; MinerU; Unstructured; LlamaParse
  • NVIDIA, How to Build a Document Processing Pipeline for RAG with Nemotron (multimodal document pipeline); Visual RAG Toolkit, arXiv:2602.12510; PULSAR, arXiv:2608.28572
  • Industry trend analyses (2026): AI Agent Knowledge Retrieval in 2026, RAG Is Dead, Long Live RAG, RAG 2026: From Vector Search to Intelligent Retrieval Systems

Comments

Loading comments…

    ← Back to home