Runoob Tutorial ArchiveEnglish

RAG and Knowledge Retrieval

RAG and Knowledge Retrieval

RAG (Retrieval-Augmented Generation) is one of the most mainstream LLM deployment architectures currently.

The core idea of RAG is:To allow the LLM to first retrieve relevant content from an external knowledge base when answering questions, and then generate the answer based on the retrieved results,rather than relying solely on the knowledge memorized during model training.

This solves two core pain points of LLMs: knowledge cutoff date (the model doesn't know what happened after training) and hallucination problem (the model invents answers when uncertain).


Basic principles of RAG

A complete RAG system consists of two pipelines:Offline indexing pipeline(Preprocessing documents and storing them in the vector database) andOnline query pipeline(Receiving user questions, retrieving, and generating).

The offline stage splits the original documents into chunks, converts them into vectors using an Embedding model, and stores them in the vector database.

The online stage also converts the user question into a vector, finds the most similar document chunks from the database, concatenates them into context, and passes them to the LLM to generate an answer.

The figure below shows the complete request flow of RAG:

RAG basic flow diagram Complete RAG request flow: the user query is converted into a query vector by the embedding model, similar document chunks are retrieved from the vector database, the question and retrieval results are concatenated into a prompt, and the LLM generates the final answer. User question Embedding Convert to query vector Vector database Similarity retrieval Top-K Prompt concatenation Question + document chunk LLM generation Answer based on retrieval results Offline indexing (one-time preprocessing) Original document Split / clean Embedding Convert to document vector Write Vector database Online query flow (every request goes through this)

Data preprocessing and document chunking

Pre-challenges: Complex document parsing

Before chunking, RAG often facesformatting parsingchallenges. Especially tables, images, and multi-column layouts in PDFs, Word documents, or scans, where ordinary text extraction easily causes semantic confusion.

The current mainstream industry solution is to introducedocument parsing engines(such as LlamaParse, Unstructured) or multimodal large models to convert complex text and images into structured Markdown, laying the foundation for subsequent high-quality chunking.

Document Splitting Strategy

Document splitting is the foundation of RAG effectiveness; the splitting granularity directly affects retrieval quality. Blocks that are too large introduce noise, and blocks that are too small lose context. Common strategies are as follows:

Splitting Strategy Applicable Scenarios Advantages Disadvantages
Fixed-size Splitting General Text Simple to implement and fast May cut off semantically complete sentences
Recursive character splitting Structured text (Markdown, code) Prioritize splitting by semantic boundaries such as paragraphs and sentences Slightly more complex to implement, requires setting a reasonable list of delimiters
Semantic splitting (Semantic) Long documents, books Utilize Embedding to calculate the similarity between adjacent sentences, automatically finding semantic turning points for splitting High computational cost, slow preprocessing speed
Parent-child document retrieval
(Small-to-Big) Comprehensive coverage of scenarios Use "small chunks" for high-precision vector retrieval, and return the corresponding "large chunk" (parent document) to the LLM upon a hit, balancing retrieval accuracy and context completeness. Database design and maintenance costs double

In practice, often add during splittingOverlap, meaning adjacent blocks share some characters to prevent important information from being truncated at the boundaries. Typical configuration: block size 512 tokens, overlap 50~100 tokens.

Example: Recursive splitting using LangChain

from

langchain.

text_splitter

import

RecursiveCharacterTextSplitter

splitter

=

RecursiveCharacterTextSplitter

(

    chunk_size

=

512

,

       

Maximum tokens per chunk

chunk_overlap

=

50

,

     

The number of overlapping tokens between adjacent chunks to prevent information loss at the boundaries

separators

=

[

"\n\n"

,

"\n"

,

"。"

,

"."

,

" "

,

""

]

 

Prioritize splitting by paragraph and sentence

)

chunks

=

splitter.

split_text

(

document_text

)

print

(

f

"Split into {len(chunks)} document chunks"

)


Vector retrieval

Embedding model

Embedding models are responsible for converting text into dense vectors (usually a float array of 768 or 1536 dimensions). Texts with similar semantics are closer in vector space, which is the mathematical basis for similarity search.

Common Embedding Model Comparison:

Model Dimension Applicable Language Features
text-embedding-3-small(OpenAI) 1536 Multilingual High cost-performance ratio, suitable for large-scale indexing
text-embedding-3-large(OpenAI) 3072 Multilingual Highest accuracy, higher cost
BAAI/bge-m3 1024 Chinese and English Open source, excellent Chinese performance, supports multiple languages
sentence-transformers/all-MiniLM-L6-v2 384 English Small footprint, fast speed, suitable for ultra-light local deployment

Similarity calculation and ANN algorithms

The core of retrieval is measuring distance. The most commonly used isCosine Similarity, which calculates the cosine of the angle between two vectors, with a value range of [-1, 1], where closer to 1 means more similar. In addition, there is Dot Product and L2 Distance., it calculates the cosine of the angle between two vectors, with a range of [-1, 1], where values closer to 1 are more similar. There is also the Dot Product and L2 Distance.

To achieve millisecond-level retrieval in millions of vectors, databases usually adoptApproximate Nearest Neighbor (ANN) algorithms(such asHNSWand IVF). HNSW is the most mainstream algorithm currently, which achieves an order of magnitude improvement in search speed by building a multi-layer skip graph network, sacrificing very little accuracy.


Advanced RAG

Basic architecture (Naive RAG) often faces issues such as inaccurate retrieval and "context drowning" due to redundant information. Advanced RAG achieves this throughpre-retrieval optimization → retrieval fusion → post-retrieval optimizationThe three-stage architecture is solved.

1. Pre-retrieval: Query Optimization

Users' original questions are often not precise enough:

2. Hybrid Search

Combinevector retrieval(understands semantics, high fault tolerance) andkeyword retrieval(BM25, high matching accuracy) results by weight. This is particularly important when encountering proper nouns, product models, or code snippets, because traditional vector retrieval is prone to "failing" on specific proper nouns.

3. Post-retrieval optimization: Reranking

This is acoarse ranking -> fine rankingtwo-stage design. Although vector retrieval is fast, the scoring is not precise enough. Reranking introducesCross-Encoder model(such asbge-reranker), which takes pairs of "question" and "document" as input to the model for joint inference scoring. It has a large computational load and is only responsible for selecting the top 5 from the top 20.

Example: Reranking process pseudocode

from

sentence_transformers

import

CrossEncoder

reranker

=

CrossEncoder

(

"BAAI/bge-reranker-v2-m3"

)

1. Coarse ranking: Vector retrieval quickly recalls Top-50

candidates

=

vector_store.

similarity_search

(

query

,

k

=

50

)

2. Fine Ranking: Constructing [Question, Document] pairs for precise scoring

pairs

=

[

[

query

,

doc.

page_content

]

for

doc

in

candidates

]

scores

=

reranker.

predict

(

pairs

)

3. Filter the Top-5 passed to the LLM

ranked_docs

=

sorted

(

zip

(

scores

,

candidates

)

,

reverse

=

True

)

final_docs

=

[

doc

for

_

,

doc

in

ranked_docs

[

:

5

]

]

4. Self-RAG and CRAG (Corrective RAG)

Incorporate a self-reflection mechanism. For example, CRAG (Corrective RAG) has the LLM act as a "judge" to score the retrieved results. If the local knowledge base does not contain the document or the quality is very low, the system will automatically trigger Web Search (such as Google API) as a supplement, significantly reducing hallucinations.


GraphRAG: Knowledge Graph + Retrieval Fusion

Traditional RAG treats the knowledge base as independent text fragments and cannot answer complex questions that requirecross-document, multi-hop reasoning.GraphRAGIntroduce a Knowledge Graph to explicitly model entities and relationships.Introduce Knowledge Graph to explicitly model entities and relationships.

GraphRAG architecture diagram GraphRAG fuses vector retrieval with knowledge graphs: the user question triggers both vector retrieval and graph retrieval simultaneously, and the fused results are fed into the LLM to generate the answer. User issue Vector retrieval Relevant document chunks Graph retrieval Entity-relation subgraph Context fusion Document chunk + graph path Entity A → relation → Entity B Entity B → relation → Entity C

Core steps of GraphRAG

  1. Knowledge constructionIn the offline phase, use LLM to extract triples (subject, relation, object) from documents and write them to a graph database like Neo4j.
  2. Dual-path retrievalFor entities in the query, not only perform traditional vector retrieval but also trigger graph traversal in the knowledge graph to extract multi-hop relationship chains.
  3. Graph-text fusion generationAssemble the "snippets" retrieved by vector search and the "path structures" retrieved by graph search into the Prompt, allowing the LLM to have both a global view and grasp specific details.

GraphRAG content reference:https://www.runoob.com/ai-agent/graphrag-usage.html


Technology and Database Selection Recommendations

Database/Tool Selection Type Recommended Deployment Scenarios
Pinecone / Zilliz Cloud Fully Managed Cloud Service Out-of-the-box, do not want to maintain infrastructure. Pairing with Cohere Rerank + GPT-4o is the fastest commercialization solution.
Qdrant Open source + Managed Written in Rust, excellent memory management, extremely high performance. Suitable for enterprise-grade private deployment.
Weaviate / Elasticsearch Open source + Managed Comes with a very mature BM25 + vector hybrid search, preferred for scenarios with many proper nouns.
Milvus Open source distributed Suitable for ultra-large-scale enterprise search platforms of billions to tens of billions.
Chroma / FAISS Local/Embedded Extremely lightweight, no need to deploy a separate service. Very suitable for local development and personal knowledge base project validation.

RAG Evaluation Metrics (RAGAS Framework)

RAG system evaluation cannot be based on intuition alone; the mainstream approach usesRAGASframework to conduct automated quantitative testing from two dimensions: "Retrieval" and "Generation":