Contact, if you are interested in this website / domain name / sponsorship / advertisement / partnership

Retrieval-augmented generation (RAG) explained

A practical guide to retrieval-augmented generation, covering each stage of the pipeline from parsing and chunking to hybrid search, reranking and cited answers. It also explains how to evaluate RAG quality, when long context or fine-tuning fits better and how to secure the system.

BuildingIntermediate10 min readUpdated October 10, 2026

Key takeaways

  • RAG retrieves relevant passages from your own documents at question time and asks the model to answer from them with citations, so answers stay current without retraining.
  • Most RAG failures are retrieval failures, so invest first in parsing, chunking, hybrid search and reranking.
  • Hybrid search (BM25 plus vectors, merged with reciprocal rank fusion) followed by a reranker is the highest-leverage upgrade over basic vector search.
  • Measure retrieval recall and answer faithfulness separately on a labeled set of real questions, and rerun the set on every change.
  • Enforce document permissions inside the retrieval query and treat every retrieved passage as untrusted input that may carry prompt injection.

Retrieval-augmented generation (RAG) lets a language model answer from your documents instead of from memory alone. This guide walks through the full pipeline, the choices that matter most at each stage, how to measure quality, how RAG compares with long context and fine-tuning, and the security controls a production system needs.

What RAG is and why it exists

A language model knows only what was in its training data, frozen at a cutoff date, and it knows nothing about your private files. Ask about last week's pricing change or an internal policy and it will either decline or produce a confident guess. That second failure is a hallucination.

RAG fixes this by adding a search step. Before the model answers, your application retrieves the most relevant passages from a knowledge base and places them in the prompt with an instruction to answer from those passages and cite them. The term comes from a 2020 research paper by Patrick Lewis and colleagues, and the pattern is now a standard way to connect LLMs to company knowledge.

RAG addresses four problems at once:

  • Freshness. Update a document and the next answer reflects it, with no retraining.
  • Private knowledge. The model can use content it never saw in training.
  • Verifiability. Answers can cite their sources, which grounds them in text users can check.
  • Access control. Retrieval can respect who is allowed to see which document.

RAG does not make a model smarter, and it cannot help if the right passage is never retrieved. Most RAG quality problems are search problems.

The RAG pipeline, step by step

A RAG system has an offline indexing path that prepares documents and an online query path that runs for every question.

  1. Ingest. Connectors pull content from file shares, wikis, ticketing systems, databases and websites. Record the source URL, owner, last-modified date and access permissions for every document, and schedule syncs so edits and deletions propagate.
  2. Parse. Convert each file to clean text while keeping structure: headings, lists, tables and page numbers. PDFs are the hardest case. Scanned pages need OCR, and complex layouts need a document-conversion tool such as Docling or Apache Tika rather than raw text extraction.
  3. Chunk. Split documents into passages small enough to retrieve precisely but large enough to make sense alone.
  4. Embed. An embedding model turns each chunk into a vector, a list of numbers positioned so that passages with similar meaning sit close together.
  5. Index. Store vectors, chunk text and metadata in a vector database or search engine, usually alongside a keyword index for exact terms.
  6. Retrieve. At query time, embed the question, apply metadata and permission filters and fetch the top candidates, commonly 20 to 100.
  7. Rerank. A slower, more accurate model rescores the candidates and keeps the best 5 to 10.
  8. Generate with citations. Put the passages in the prompt with numbered source labels. Instruct the model to answer only from them, cite each claim and say when the sources do not contain the answer. Before showing the response, check that every cited source ID exists.

Chunking strategies and trade-offs

Chunking decides what the retriever can find. Chunks that are too small lose context ("the limit is 30 days," with no hint of which limit), while chunks that are too large blur the embedding and waste prompt space.

StrategyHow it worksStrengthsWeaknesses
Fixed-size with overlapWindows of N tokens overlapping by 10-20 percentSimple, predictable, fastCuts through sentences, tables and sections
Recursive, structure-awareSplit on headings, then paragraphs, then sentences, until under a size limitKeeps logical units together; a strong defaultUneven sizes; depends on clean parsing
Format-specificMarkdown by heading, code by function, slides by page, tables by row groups with headers repeatedHighest fidelity for structured contentCustom code per format
SemanticStart a new chunk where similarity between neighboring sentences dropsTopic-coherent chunksMore compute at ingest; inconsistent gains; harder to debug
Parent-child (small-to-big)Match on small chunks, then send the larger parent section to the modelPrecise matching with full contextMore storage and prompt tokens
Contextual headersPrepend the document title, heading path or a short LLM-written summary to each chunk before embeddingFixes orphaned chunks; measurable recall gainsExtra cost and time at ingest

A reasonable starting point is structure-aware chunks of roughly 300-800 tokens with 10-15 percent overlap, each prefixed with its document title and section heading. Then tune against an evaluation set rather than intuition. Anthropic reported that prepending generated context to each chunk before embedding cut top-20 retrieval failures by 35 percent in its tests, and by 49 percent when combined with contextual keyword search. The token counter helps you check chunk sizes.

Retrieval: embeddings, vector stores, hybrid search and reranking

Embedding models and vector databases

Choose the embedding model carefully, because changing it later means re-embedding everything. Compare candidates on a sample of your own queries, and check language coverage, maximum input length and vector size, which drives storage cost. Many current models can output shortened vectors (Matryoshka-style), trading a little accuracy for much smaller indexes. The options below were current as of October 2026.

CategoryExamplesWhen to choose
Hosted embedding APIsOpenAI text-embedding-3-small and -large; Cohere Embed v4 and v5; Voyage AI's voyage-4 family, including voyage-code-4; Google's Gemini Embedding 2Fastest start with no GPUs; your text is sent to the provider
Open-weight embedding modelsQwen3-Embedding (0.6B, 4B, 8B); BGE-M3 (dense, sparse and multi-vector in one model); EmbeddingGemma; nomic-embed-textData stays in-house; runs on your own hardware, including through Ollama
Vector search in an existing databasepgvector for PostgreSQL; vector fields in Elasticsearch and OpenSearchYou want one system with joins, transactions, backups and familiar operations
Dedicated vector databasesQdrant, Milvus, Weaviate, Chroma and LanceDB (open source); Pinecone (managed service)Large scale, high query volume, built-in hybrid search and multi-tenancy

Most of these use approximate nearest-neighbor indexes such as HNSW, which give up a sliver of recall for large speed gains. Store the embedding model name and version with every vector so incompatible vectors never mix in one index.

Vector search matches meaning, so "how do I get my money back" finds a passage titled "Refund policy." It is weaker on exact strings such as product codes, error messages, names and rare acronyms. BM25, the classic keyword-ranking algorithm, has the opposite profile. Hybrid search runs both and merges the results.

The usual merge method is reciprocal rank fusion (RRF). Each document scores the sum of 1 / (k + rank) across the result lists, where k is a smoothing constant that Elasticsearch sets to 60 by default. A chunk ranked first by keywords and third by vectors scores 1/61 + 1/63, about 0.0323, beating a chunk ranked second in only one list (1/62, about 0.0161). Because RRF uses ranks rather than raw scores, you never have to reconcile two incompatible scoring scales.

Reranking

Embedding search compares a precomputed document vector with a query vector. A reranker, usually a cross-encoder, reads the query and each candidate together and scores relevance directly, which is more accurate but too slow to run over a whole corpus.

The standard pattern retrieves 50 to 100 hybrid candidates and reranks them down to the best 5 to 10. Options include Cohere's rerank-v4.0 models (pro and fast), Voyage AI's rerankers and open-weight models such as Qwen3-Reranker and the BGE reranker family. In Anthropic's tests, adding reranking on top of contextual embeddings and keyword search raised the reduction in retrieval failures to 67 percent.

Watch: What is Retrieval-Augmented Generation (RAG)? (IBM Technology). A short whiteboard explanation of retrieval-augmented generation, where the system fetches relevant documents and hands them to the model alongside the question. It is a good first introduction for product managers and developers meeting RAG for the first time.

How to evaluate a RAG system

Evaluate retrieval and generation separately, or you will not know which half to fix. Start with 50 to 200 real questions, each labeled with the passages that answer it and a reference answer.

MetricQuestion it answersHow to measure
Retrieval recall@kDid the right passage appear in the top k?Compare retrieved chunk IDs with labeled ones; no LLM needed
Ranking quality (MRR, nDCG)How high did relevant passages rank?Standard information-retrieval formulas over the same labels
FaithfulnessIs every claim in the answer supported by the retrieved context?An LLM judge checks each claim against the passages
Answer relevanceDoes the answer address the question asked?LLM judge or human rating
Citation accuracyDo cited sources support the sentences that cite them?Spot checks plus automated claim-to-source matching

Open-source frameworks automate much of this evaluation. Ragas provides context precision, context recall, faithfulness and response relevancy metrics. TruLens popularized the "RAG triad" of context relevance, groundedness and answer relevance, while DeepEval, Arize Phoenix and promptfoo add test runners, tracing and regression checks. Calibrate any LLM judge against a few dozen human ratings before trusting it, and rerun the suite whenever you change chunking, embeddings, prompts or models.

RAG vs long context vs fine-tuning

Several frontier models now accept around 1 million tokens, so you can sometimes paste a whole knowledge base into the prompt. Fine-tuning is a third option. Each solves a different problem.

ApproachBest forLimits
RAGLarge or changing knowledge bases, citations, per-user permissionsEngineering effort; quality capped by retrieval
Long contextOne-off analysis of a few documents; small corpora (under roughly 200K tokens) that rarely changeCost and latency on every query; facts buried mid-context get missed
Fine-tuningConsistent style, format and domain behaviorUnreliable for teaching facts; no citations; stale once trained

Cost makes the trade-off concrete. At an example rate of $2 per million input tokens, sending a 200,000-token corpus with every question costs $0.40 per query, or $12,000 for 30,000 queries a month. Prompt caching at an example cached rate of $0.10 per million cuts that to about $600 plus cache writes. Retrieving 8,000 tokens of context instead costs $0.016 per query, or $480 a month, and answers arrive faster.

Accuracy matters too. The 2023 "Lost in the Middle" study found that models use information at the start and end of a long input more reliably than information in the middle. See context windows explained for more, and fine-tuning vs RAG vs prompting for a full decision guide.

Security: permissions and prompt injection

RAG connects a model to sensitive data. The OWASP Top 10 for LLM Applications (2025 edition) lists the two biggest resulting risks: prompt injection (LLM01) and vector and embedding weaknesses (LLM08).

Document-level permissions

The model must never see a passage the user is not allowed to read. Copy access-control lists into each chunk's metadata during ingestion, filter on the authenticated user's identity and groups inside the retrieval query and sync permission changes as fast as content changes. Never rely on the system prompt to withhold restricted text; once it is in the context window, assume it can leak. Use separate indexes or namespaces per customer in multi-tenant products, and protect stored embeddings as carefully as the text they came from.

Prompt injection in retrieved content

Any retrieved document can contain text that reads like instructions, such as a hidden line in a web page or PDF telling the model to ignore its rules. This is indirect prompt injection, and no filter stops it completely, so limit the damage:

  • Wrap retrieved passages in clear delimiters and tell the model they are reference data, not instructions.
  • Grant the least privilege possible; a RAG chatbot rarely needs tools that send email or change records.
  • Require human approval for consequential actions and validate outputs with deterministic code.
  • Strip or flag hidden text during parsing, and control which sources can enter the index.
  • Do not auto-render model-generated links or images, a known channel for leaking data.

For broader controls, read the LLM security and privacy guide.

A reference architecture

This design suits most internal knowledge assistants. It has two paths that share one index, plus a feedback loop.

Indexing path. Connectors detect new, changed and deleted documents and place them on a queue. A parsing service converts each file to structured text, and a chunker emits passages with metadata: source URL, title, heading path, timestamps and access groups. An enrichment step adds contextual headers, and an embedding service writes vectors and text to a versioned store that supports both vector and BM25 search, so a bad build can be rolled back.

Query path. The API authenticates the user and resolves their groups. A rewrite step turns follow-ups such as "what about Canada?" into standalone queries. Hybrid retrieval runs with a permission filter, fuses about 50 candidates with RRF and passes them to a reranker that keeps the top 8.

A context builder orders the passages, enforces a token budget and assigns source numbers. The LLM answers with inline citations, a validator confirms the cited IDs exist and guardrails screen the output before it streams to the user with clickable sources.

Feedback loop. Log queries, retrieved IDs, scores, answers and user ratings under your data-retention policy. Add failed questions to the evaluation set, and rerun the suite before every change to chunking, models or prompts.

Common mistakes and how to fix them

FailureSymptomFix
Poor parsingGarbled tables, merged columns, missing scanned pagesLayout-aware parsing and OCR; inspect parsed output by hand
Orphaned chunksRight fact, wrong product or yearAdd titles, heading paths or contextual summaries to chunks
Vector-only searchMisses part numbers, error codes and namesAdd BM25 and fuse with RRF
Too much contextSlow, costly answers that overlook the key passageRerank and send fewer, better chunks
Stale indexAnswers cite deleted or outdated documentsIncremental sync with delete handling; show document dates
Ungrounded answersModel fills gaps from memoryInstruct it to answer only from sources and admit gaps; track faithfulness
No evaluation setQuality regresses quietly after changesBuild a labeled set from real queries and run it automatically
  • Parsed output spot-checked for tables, headings and scanned pages
  • Chunks carry title, section, date and permission metadata
  • Hybrid retrieval plus reranking, tuned on labeled queries
  • Recall@k and faithfulness tracked on every change
  • Permission filters enforced in the retrieval query, not the prompt
  • Retrieved text treated as untrusted input

Next steps

Estimate per-query cost for your retrieval budget with the LLM cost calculator, and see how much text fits in different prompt sizes with the context window visualizer. Then read fine-tuning vs RAG vs prompting to confirm RAG is the right tool for your problem. If you are building a production knowledge assistant and want an experienced reviewer, you can hire an LLM expert.

Sources

  1. Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (Lewis et al., 2020)
  2. Lost in the Middle: How Language Models Use Long Contexts (Liu et al., 2023)
  3. Introducing Contextual Retrieval (Anthropic, September 2024)
  4. OWASP Top 10 for LLM Applications 2025: LLM01 Prompt Injection
  5. Reciprocal rank fusion (Elasticsearch reference)
  6. Hybrid and multi-stage queries (Qdrant documentation)
  7. pgvector: open-source vector similarity search for Postgres
  8. Ragas documentation: available metrics
  9. Vector embeddings guide (OpenAI API documentation)
  10. Qwen3-Embedding model card (Qwen, Hugging Face)

Written by the LLModel editorial team and checked against the sources above on October 10, 2026. Found an error? Send a correction.

Frequently asked questions

What is RAG in simple terms?

Retrieval-augmented generation is a pattern where an application searches your documents for passages relevant to a question, pastes the best ones into the prompt and asks the language model to answer using only those passages, ideally with citations. The model supplies language skills and reasoning, while the search step supplies current, private and verifiable facts that were never part of its training data.

Is RAG better than fine-tuning?

They solve different problems. RAG is better for knowledge: facts that change, large document collections, citations and per-user permissions. Fine-tuning is better for behavior: a consistent tone, a strict output format or a specialized task the base model handles poorly. Many production systems combine them, using a fine-tuned or well-prompted model that answers from retrieved passages.

Do I need a vector database for RAG?

Not necessarily. Small collections can be searched in memory, and if you already run PostgreSQL, the pgvector extension adds vector search alongside your existing data. Search engines such as Elasticsearch and OpenSearch combine keyword and vector search. Dedicated vector databases such as Qdrant, Milvus or Pinecone make sense at large scale or when you need built-in hybrid search and multi-tenancy.

What chunk size should I use for RAG?

A common starting point is 300 to 800 tokens per chunk with 10 to 15 percent overlap, split along headings and paragraphs rather than at fixed character counts. Prefix each chunk with its document title and section heading. Then test two or three sizes against a labeled set of real questions, because the best size depends on your documents and query style.

Do long context windows make RAG obsolete?

No, but they shrink the cases where RAG is required. If your corpus is small, changes rarely and has no permission boundaries, sending it all with prompt caching can be simpler. For large or changing collections, RAG remains cheaper per query, faster and easier to cite, and models can still overlook facts buried in the middle of very long inputs.

Need hands-on help building it?

RAG, agents, fine-tuning or a production chatbot: describe the project and we'll suggest an approach and, if you want, partners who build it.

  • Free and vendor-neutral: no model provider pays for placement.
  • Your details go only to partners you agree to.

Takes about 2 minutes. No sales calls unless you ask for one.