Build a retrieval-augmented generation application with a repeatable workflow for loading documents, creating useful chunks, indexing embeddings, retrieving evidence, reranking results, and producing transparent citations. This RAG tutorial includes scenario-based checklists, practical defaults, validation steps, and fallback behavior you can revisit whenever your data sources, models, or retrieval stack changes.
Overview
Retrieval-augmented generation, or RAG, combines a language model with an external knowledge collection. Instead of asking the model to answer from its general training alone, the application retrieves relevant passages and places them in the model’s context. The model then uses that supplied evidence to produce an answer.
A reliable RAG system is more than a vector database connected to an LLM. Its quality depends on the complete path from source document to final response:
- Ingestion: discover, load, and identify source files.
- Cleaning: remove extraction noise while preserving meaning and structure.
- Chunking: divide content into passages that are specific enough to retrieve and complete enough to answer from.
- Embedding: convert chunks and queries into vectors that support semantic matching.
- Retrieval: select candidate passages using vector, keyword, or hybrid search.
- Reranking: reorder candidates using a more precise relevance step when needed.
- Generation: give the selected evidence to the model with instructions about grounding and citations.
- Evaluation: measure retrieval quality, answer quality, citation correctness, latency, and cost.
Keep source metadata with every chunk. Useful fields include document ID, title, URL or file path, page or section, version, access scope, ingestion timestamp, and chunk position. Metadata is essential for filtering, debugging, permissions, and citation formatting.
Choosing a chunking strategy
| Strategy | How it works | Best fit | Trade-off |
|---|---|---|---|
| Fixed-size | Splits text by a target character or token length, often with overlap. | Consistent text with simple structure. | May cut across headings, lists, or explanations. |
| Recursive | Attempts larger boundaries first, then falls back to smaller separators. | General documentation and mixed prose. | Requires tuning separators and limits. |
| Structure-aware | Uses headings, paragraphs, tables, pages, or code blocks. | Technical documentation and policy content. | Depends on reliable parsing and layout detection. |
| Semantic | Groups neighboring sentences or sections by meaning. | Long-form content with uneven topic boundaries. | More processing and less predictable chunk sizes. |
There is no universal chunk size. Start with a structure-aware or recursive approach, preserve headings in each chunk, and test several sizes against representative questions. Overlap can help preserve context at boundaries, but excessive overlap increases index size and may cause redundant retrieval results.
Checklist by scenario
When adding a new document source
- List supported formats, such as HTML, Markdown, PDF, plain text, office documents, or exported records.
- Choose an extraction method appropriate to the format. Confirm whether the source contains scanned pages, tables, columns, code, or images that need special handling.
- Normalize encoding, whitespace, repeated headers, footers, navigation elements, and boilerplate.
- Preserve meaningful hierarchy, including document titles, headings, list labels, page numbers, and section names.
- Assign a stable document ID and record source ownership, version, permissions, and update time.
- Make ingestion repeatable. A changed source should update or replace the correct records rather than create duplicates.
- Run a small inspection sample before embedding the full collection. Review extracted text and metadata manually.
When designing chunks
- Define the unit a user is likely to ask about: a procedure, product rule, troubleshooting step, contract clause, or concept.
- Keep headings and parent context with the body text when they clarify meaning.
- Avoid chunks that contain several unrelated topics merely because they fit a length limit.
- Use overlap only where the meaning regularly crosses boundaries.
- Store the original text separately from any cleaned or normalized representation so citations can be checked.
- Test questions that require a detail at the beginning, middle, and end of a source section.
When implementing retrieval
- Embed documents and queries with compatible model choices and consistent preprocessing.
- Use metadata filters for tenant, product, language, date, document type, or access scope before returning context.
- Consider hybrid retrieval when exact terms, identifiers, names, or error codes matter as much as semantic similarity.
- Retrieve enough candidates for recall, then reduce the set before generation if the context becomes noisy.
- Use reranking when top vector matches are plausible but not consistently the most useful passages.
- Deduplicate overlapping chunks from the same source and retain a clear ordering for the model.
- Log query text, applied filters, retrieved IDs, scores, reranking results, and final context for diagnosis.
When producing answers and citations
- Tell the model to use the supplied context as the primary evidence and to say when the evidence is insufficient.
- Require citations to reference actual retrieved source IDs, titles, pages, or section names rather than allowing invented links.
- Place citations close to the claims they support.
- Validate that every citation maps to a retrieved passage and that cited text supports the associated claim.
- Define a fallback for no-result, low-confidence, conflicting, outdated, or permission-filtered retrieval.
- Separate retrieved evidence from user instructions and untrusted document content.
A simple generation instruction can be framed as: answer using only the provided evidence; distinguish direct support from reasonable uncertainty; cite the source identifier after each material claim; and return a no-evidence response when the context does not support an answer. The exact wording can vary, but the behavior should be tested rather than assumed.
What to double-check
Retrieval quality
Create a small evaluation set containing real questions, expected source documents, and notes about the required evidence. Check whether the correct source appears in the retrieved candidates before judging the generated answer. If it does not, changing the prompt will not solve the underlying retrieval problem.
Review both recall and precision. Recall asks whether the necessary passage was found. Precision asks whether the returned passages are relevant enough to avoid distracting the model. Track failure categories such as poor extraction, weak chunk boundaries, missing metadata, incorrect filters, terminology mismatch, and stale index records.
Grounding and citations
Inspect answers for claims that go beyond the context. A citation is not proof of grounding if the cited passage does not support the wording. Test paraphrases, multi-part questions, questions with ambiguous terms, and requests that combine information from several documents.
Security and access control
Apply authorization before context reaches the model. Do not rely on the model to hide restricted text after retrieval. Treat documents as potentially untrusted input: a document can contain instructions intended to manipulate the application rather than information relevant to the user’s question. For a broader review, use a dedicated prompt injection defense checklist.
Operational behavior
Measure ingestion failures, embedding failures, empty retrievals, model errors, latency, token usage, and citation validation failures. Streaming can improve perceived responsiveness, but it does not replace retrieval and answer validation; review the guidance on streaming responses and error handling when designing the delivery layer.
Common mistakes
- Indexing raw files without inspection: headers, footers, navigation, OCR errors, and duplicated text can dominate retrieval results.
- Using one chunk size for every source: a support article, legal clause, table, and code reference have different natural boundaries.
- Retrieving too much context: more text can increase distraction, latency, and token consumption without improving the answer.
- Ignoring exact matches: model names, ticket IDs, commands, and version strings may require keyword or hybrid search.
- Filtering after retrieval: authorization and tenant boundaries should be applied before context is assembled.
- Allowing unsupported answers: instruct and test the system to acknowledge missing evidence instead of filling gaps confidently.
- Changing several variables at once: changing the parser, chunking, embedding model, retriever, and prompt together makes regressions difficult to explain.
- Skipping version tracking: record the embedding model, chunking configuration, parser version, prompt version, and index build so results can be reproduced.
RAG performance is also connected to the surrounding LLM application. Review context window management when retrieved passages compete with conversation history, and review cost optimization, caching, and batch processing before scaling ingestion or query volume.
When to revisit
Revisit this workflow whenever a source changes, a document format is added, permissions are revised, users report missing evidence, or the application moves to a different embedding, reranking, vector search, or language-model component. Also schedule a review before seasonal planning cycles or other periods when source content and query volume change substantially.
Use this update checklist:
- Sample newly ingested documents and compare extracted text with the originals.
- Re-run a fixed evaluation set and compare retrieval, answer, citation, latency, and cost results.
- Check that metadata filters and authorization still work for every tenant or user role.
- Inspect no-result and low-confidence behavior, including conflicting or stale documents.
- Review index rebuild and rollback procedures before changing embeddings or chunking rules.
- Record the change in a versioned configuration or changelog.
- Keep a small set of known failures and confirm that a change improves them without creating regressions.
Before shipping, confirm that every source can be traced from original document to cleaned text, chunk, retrieved result, cited passage, and final answer. That traceability turns a RAG application from a promising demo into a maintainable part of an LLM application.