RAG Tutorial for Developers: Build a Grounded Question-Answering Pipeline
A retrieval-augmented generation (RAG) system connects an LLM to your own document collection so it can answer questions using relevant, traceable context. This guide provides a reusable implementation checklist covering document preparation, chunking, embeddings, vector search, prompt assembly, citations, validation, and troubleshooting.
Overview
A basic RAG pipeline has two stages: indexing and answering. During indexing, your application loads source documents, cleans them, divides them into chunks, creates an embedding for each chunk, and stores the embeddings with searchable metadata in a vector database or another retrieval system. During answering, the application embeds the user's question, retrieves relevant chunks, places those chunks into a controlled prompt, and asks the LLM to produce an answer grounded in that context.
The LLM is not the retrieval system. It generates language, while the retrieval layer decides which source material is available for the answer. Separating these responsibilities makes the application easier to test and troubleshoot.
A practical architecture usually looks like this:
- Source collection: Documents, web pages, tickets, manuals, or structured records.
- Preparation: Parsing, cleaning, normalization, access-control filtering, and metadata extraction.
- Chunking: Splitting content into retrievable units while preserving useful meaning.
- Embedding: Converting chunks and questions into vectors using a selected embedding model.
- Indexing: Storing vectors, text, identifiers, and metadata in a vector search system.
- Retrieval: Searching for relevant chunks, optionally with keyword, metadata, or reranking filters.
- Generation: Supplying retrieved context and instructions to the LLM.
- Validation: Checking relevance, citations, formatting, permissions, and unsupported claims.
Before implementation, define what “grounded” means for your use case. It may mean that every factual statement has a source citation, that the model refuses when evidence is insufficient, or that answers are limited to a specific document collection.
Checklist by scenario
1. Preparing a new document collection
- Identify authoritative sources and remove duplicates or obsolete copies.
- Preserve document titles, section headings, URLs, page numbers, dates, and ownership information where available.
- Extract text without losing table labels, list relationships, or heading hierarchy.
- Normalize whitespace and remove navigation, repeated footers, boilerplate, and unrelated page elements.
- Attach metadata such as document ID, department, product, language, publication date, and access scope.
- Record the source version so an answer can be traced back to the indexed material.
Do not treat all files as plain text. A policy, spreadsheet, support ticket, and product manual may require different parsing rules. If the extraction step produces broken sentences or scrambled tables, improving retrieval later will not fully repair the pipeline.
2. Choosing a chunking strategy
- Split on semantic boundaries such as headings, paragraphs, procedures, or question-and-answer pairs.
- Keep chunks large enough to contain an answer but small enough to avoid unrelated material.
- Use limited overlap when a sentence or definition may depend on the preceding chunk.
- Store the parent document and section path with every chunk.
- Test chunking on long procedures, tables, code samples, and documents with nested headings.
There is no universal chunk size that works for every collection. Start with a simple, reproducible rule, then evaluate whether retrieved chunks contain complete answers. If a chunk frequently begins with “this process” or “the following exception” without the preceding explanation, the boundaries need attention.
3. Building retrieval and answer generation
- Embed the user's question with the same compatible embedding approach used for indexed chunks.
- Retrieve more candidates than you plan to place in the final prompt, then filter or rerank them.
- Apply metadata and permission filters before context reaches the model.
- Remove near-duplicate chunks to preserve room for distinct evidence.
- Include source labels beside each context block.
- Instruct the model to answer only from the supplied context and to say when the evidence is insufficient.
- Require a consistent citation format, such as document title plus section or URL.
A simple prompt assembly pattern is:
System: Answer using only the supplied context. If the context does not support an answer, say so. Do not invent citations.
Context:
[Source 1: title, section]
Relevant text...
[Source 2: title, section]
Relevant text...
User question:
...
Response requirements:
- Answer directly.
- Cite the supporting source after each material claim.
- Identify uncertainty where the sources disagree.Keep retrieval instructions separate from application rules, formatting requirements, and user content. For broader prompt design guidance, see the system prompt design guide.
4. Adding evaluation before release
- Create representative questions, including easy, ambiguous, multi-part, and unanswerable examples.
- Label which documents and passages should support each answer.
- Measure retrieval separately from generation.
- Check whether citations actually support the claims they follow.
- Include permission-boundary tests and prompt-injection attempts inside retrieved content.
- Review latency, token usage, failure handling, and empty-result behavior.
A prompt testing and evaluation framework is useful here because a fluent answer can still be unsupported. Keep test cases with the application and rerun them after changing the embedding model, chunking logic, retrieval parameters, or LLM.
What to double-check
Retrieval quality
Inspect retrieved results for both relevance and completeness. A result can match the question's vocabulary while missing the paragraph that contains an exception. Test synonyms, abbreviations, misspellings, natural-language questions, and queries that combine several constraints. Consider hybrid retrieval when exact terms, product codes, or names matter as much as semantic similarity.
Context assembly
Confirm that the final prompt contains the intended chunks in a predictable order and that source labels remain attached after trimming or reranking. Monitor context length rather than assuming that more retrieved text produces a better answer. Excess context can bury the most relevant evidence and increase cost or latency.
Grounding and citations
Ask whether each answer claim is supported, not merely whether the response includes a citation. A citation pointing to a related document is insufficient if the cited passage does not establish the claim. For high-impact workflows, use a second validation step, structured claim extraction, or human review instead of relying only on a confidence statement from the same model.
Security and permissions
Apply authorization before generation. Do not retrieve a private document and expect the LLM to hide it reliably. Treat indexed text as untrusted input: documents may contain instructions that conflict with the application's rules. Delimit retrieved content and tell the model to treat it as evidence, not as executable instructions.
Operational behavior
Define what happens when the vector database is unavailable, no result passes the relevance threshold, a source has changed, or the LLM request times out. The application should fail clearly rather than silently answer from general model knowledge. For production API concerns, use the LLM API integration checklist.
Common mistakes
| Symptom | Likely cause | Useful check |
|---|---|---|
| Empty or weak results | Bad extraction, mismatched embedding setup, overly strict filters, or an unsuitable query | Search the raw text and inspect the indexed chunks before changing the prompt |
| Relevant words but wrong passage | Chunks are too broad, metadata is missing, or semantic search needs keyword support | Compare chunk boundaries and test hybrid retrieval or reranking |
| Answers combine unrelated sources | Too many candidates or duplicate content enters the context | Reduce final context, deduplicate, and preserve source boundaries |
| Confident unsupported answers | The prompt permits general knowledge or the application ignores empty retrieval | Add an explicit abstention rule and test unanswerable questions |
| Correct answer with wrong citation | Citations are generated independently of evidence mapping | Attach source IDs to chunks and validate citations against retrieved text |
| Private information appears | Authorization was applied after retrieval or not at all | Filter by user permissions before vector search and test cross-user queries |
Another common mistake is changing several variables at once. If you replace the embedding model, alter chunking, change the retrieval count, and rewrite the prompt together, you will not know which change affected quality. Keep configuration versioned and make one controlled change at a time. The prompt versioning workflow can help separate prompt changes from application changes.
When to revisit
Review this RAG pipeline before adding a new document collection, changing document ownership, expanding supported languages, or moving from an internal prototype to a user-facing workflow. Revisit it whenever users report missing evidence, irrelevant answers, stale citations, or unexpected refusals.
Schedule a technical review after changing any of the following:
- Embedding or generation model.
- Vector database, indexing method, or retrieval API.
- Chunking and metadata rules.
- Context limits, token budgets, or latency targets.
- Access-control logic or document ingestion sources.
- Prompt instructions, citation format, or answer schema.
At each review, rerun a fixed evaluation set, inspect retrieval traces, verify citations, and compare costs and response times against the previous version. Update the architecture checklist when the tools or workflows change. For planning token budgets and throughput, consult the AI API cost and context planning guide.
Final implementation checklist: clean the sources, preserve metadata, test chunk boundaries, evaluate retrieval independently, enforce permissions before generation, constrain the prompt, require useful citations, handle insufficient evidence, log the pipeline stages, and rerun tests after every material change. This sequence gives you a dependable starting point for building a RAG chatbot or any other grounded question-answering application.