RAG Tutorial: Build a Retrieval-Augmented Generation Pipeline from Documents to Cited Answers
RAGretrieval augmented generationembeddingsvector databasesLLM app development

RAG Tutorial: Build a Retrieval-Augmented Generation Pipeline from Documents to Cited Answers

PPromptCraft Studio
2026-12-05
7 min read

Learn how to build a RAG application with clean documents, tuned retrieval, cited answers, cost estimates, and repeatable evaluation.

This RAG tutorial explains how to build a retrieval-augmented generation pipeline that turns documents into grounded, cited answers. You will learn how to clean and chunk source material, create embeddings, store vectors, retrieve and rerank relevant passages, assemble context for an LLM, estimate operating costs, and test whether retrieval is actually improving answer quality.

Overview

Retrieval-augmented generation, or RAG, separates an AI question-answering application into two related jobs. A retrieval system finds relevant information from your documents, while a language model uses that information to produce an answer. The model does not need to contain every answer in its training data because the application supplies current, domain-specific context at query time.

A practical RAG pipeline usually follows this path:

  1. Collect documents and record their source metadata.
  2. Extract text, remove avoidable noise, and normalize formatting.
  3. Split the text into retrievable chunks.
  4. Create an embedding for each chunk.
  5. Store embeddings, text, and metadata in a vector database or comparable search index.
  6. Embed the user’s question and retrieve candidate chunks.
  7. Optionally rerank those candidates with a second relevance model.
  8. Assemble a bounded context and send it to the language model.
  9. Return an answer with citations that point back to the source documents.

Architecture diagram description: A document-ingestion lane flows from files to text extraction, cleaning, chunking, embedding, and vector storage. A query lane flows from the user question to query embedding, metadata filtering, similarity search, optional reranking, context assembly, and the LLM. The final response passes through citation formatting and application-level validation before reaching the user.

RAG is not a replacement for evaluation or prompt design. The retrieval prompt, answer instructions, citation rules, and refusal behavior still matter. For reliable system instructions, see System Prompt Design: A Framework for Reliable Roles, Rules, and Output Formats.

How to estimate

Before choosing infrastructure, estimate both the ingestion workload and the recurring query workload. Keep the calculation in variables so it remains useful when model or database pricing changes.

Define:

  • D = number of documents
  • T = average source tokens per document
  • C = target chunk size in tokens
  • O = overlap between adjacent chunks, expressed as a decimal
  • Q = expected queries per month
  • K = chunks retrieved for each query
  • R = chunks retained after reranking
  • I_e ext{ and }O_e = average input and output tokens sent to the answer model per query

A first estimate of chunk count is:

chunks per document ≈ T / (C × (1 − O))

Round up for planning, then add a margin for short sections, tables, headings, and documents that cannot be split cleanly. Total embedded text is approximately:

total embedding tokens ≈ D × T

That figure is useful for estimating one-time ingestion work. Query volume determines recurring embedding and generation work:

monthly answer-model tokens ≈ Q × (I_e + O_e)

To estimate spend without hard-coding changing prices, multiply each token category by the current provider rate:

monthly model cost ≈ (embedding tokens × embedding rate) + (Q × input tokens × input rate) + (Q × output tokens × output rate)

Then add vector storage, database operations, reranking, file storage, observability, and application hosting as separate line items. Treat this as a planning model, not a bill. Actual usage changes with retries, re-indexing, cache hits, long questions, and unusually large documents.

Inputs and assumptions

Clean documents before chunking

Extraction quality often matters more than a small change in model selection. Remove repeated headers, navigation, boilerplate, broken line wraps, and duplicated content where possible. Preserve titles, section headings, tables, lists, page numbers, URLs, publication dates, and access permissions as metadata. Do not silently discard content that may be needed to explain an answer.

A reusable ingestion record can look like this:

{
  "document_id": "unique-id",
  "source_uri": "https://example.com/source",
  "title": "Document title",
  "section": "Heading path",
  "page": 1,
  "updated_at": "source timestamp",
  "access_scope": "team-or-permission-label",
  "text": "cleaned source text"
}

Choose chunks for meaning, not only size

Start with chunks that contain one coherent idea, procedure, policy rule, or subsection. Use headings as boundaries when possible. Overlap can protect context at boundaries, but excessive overlap increases storage and retrieval duplication. Test several chunk sizes on a small evaluation set rather than assuming one universal setting.

Use metadata deliberately

Metadata filters can prevent irrelevant retrieval before similarity search or narrow the candidate set afterward. Useful fields include product, language, document type, publication status, department, date range, and access scope. Access filtering is a security requirement: a result should not appear merely because its text is semantically similar.

Compare components by workload

ComponentDecision criteriaQuestions to test
Embedding modelLanguage coverage, domain fit, dimensions, latency, and costDoes it separate relevant and irrelevant passages in your corpus?
Vector storeFiltering, durability, scaling, operations, and deployment modelCan it enforce metadata constraints and support re-indexing?
RerankerRelevance improvement versus added latency and costDoes it improve the top results on difficult queries?
Answer modelContext capacity, instruction following, latency, and output controlsCan it cite only the supplied evidence and acknowledge gaps?

Worked examples

Assume a knowledge base contains D = 2,000 documents with an average of T = 1,500 tokens each. If the initial chunk target is C = 400 tokens with O = 0.15 overlap, the planning estimate is:

1,500 / (400 × 0.85) ≈ 4.4 chunks per document, or roughly 8,800 chunks before adjustments.

That estimate tells you to plan for approximately 3 million source tokens during ingestion. It does not tell you that 400-token chunks are correct. Build a test set of real questions, label which passages contain the answer, and compare chunk sizes using retrieval recall and answer faithfulness.

Example 2: a citation-focused support assistant

Suppose the application receives Q = 10,000 monthly questions. It retrieves K = 12 candidates, reranks them, and retains R = 5 passages for the final prompt. If each retained passage averages 300 tokens, the retrieved evidence contributes about 5 × 300 = 1,500 context tokens per query, before adding instructions and the user question.

To control cost and latency, test whether five passages outperform three, whether a reranker improves answer quality enough to justify its work, and whether repeated questions can use a safe cache. The best setting is the least context that reliably supports a correct, well-cited answer—not the largest possible prompt.

Retrieval-quality checks

  • Recall: Did the retrieved set contain the passage needed to answer?
  • Ranking: Were the most useful passages near the top?
  • Grounding: Does every important claim follow from the retrieved evidence?
  • Citation accuracy: Does each citation identify the passage that supports the claim?
  • Abstention: Does the application say that evidence is insufficient instead of inventing an answer?

Keep these cases in a regression set. For broader testing practices, use the LLM Evaluation Guide: Metrics, Test Sets, and Regression Testing for AI Features. If answers remain unreliable despite relevant retrieval, consult the LLM Hallucination Troubleshooting Checklist.

When to recalculate

Revisit the RAG estimate whenever an input changes, not only when the application fails. Recalculate after adding a large document collection, changing chunk size or overlap, switching embedding models, changing the number of retrieved passages, enabling reranking, or expanding the answer model’s context. Re-index when source content, permissions, parsing logic, or metadata changes.

Pricing and infrastructure assumptions also need review when providers change rates, storage terms, model availability, or usage limits. Keep rates in configuration rather than embedding them in application code. Record the date of each estimate and the assumptions behind it so a later comparison is meaningful.

Use this implementation checklist before release:

  1. Define supported questions and sources.
  2. Clean a representative document sample.
  3. Test at least two chunking strategies.
  4. Attach source and permission metadata to every chunk.
  5. Measure retrieval before tuning the answer prompt.
  6. Validate citations against source passages.
  7. Test no-answer, conflicting-source, stale-document, and unauthorized-access cases.
  8. Log retrieval results, model inputs, outputs, latency, and estimated usage without exposing sensitive content unnecessarily.
  9. Recalculate monthly costs using current inputs before expanding traffic.

Start with a narrow, measurable corpus and a small evaluation set. Once retrieval is dependable, improve context assembly, answer instructions, and user experience. This sequence makes a RAG application easier to debug and gives every future model, pricing, or dataset change a clear baseline for comparison.

Related Topics

#RAG#retrieval augmented generation#embeddings#vector databases#LLM app development
P

PromptCraft Studio

AI Development Editorial Team

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.