A production-ready retrieval-augmented generation (RAG) application does more than place documents in a vector database and ask an LLM for an answer. It must preserve document meaning, retrieve the right evidence, show where the answer came from, and fail safely when the evidence is missing. This RAG tutorial provides a reusable checklist for building document question-answering applications, from parsing and chunking through evaluation, citations, monitoring, and ongoing maintenance.
Overview
RAG combines information retrieval with text generation. Instead of relying only on a model's internal knowledge, the application searches a controlled document collection and supplies relevant passages to the model at request time. The model then uses those passages to compose an answer.
A practical RAG pipeline usually contains these stages:
- Ingest: collect documents and record their source, owner, version, access rules, and update date.
- Parse: extract usable text and structure from PDFs, web pages, office files, tickets, or database records.
- Chunk: divide content into retrievable units while preserving headings, relationships, and useful context.
- Embed and index: convert chunks into vectors and store them with searchable text and metadata.
- Retrieve: use a user query, metadata filters, keyword search, vector search, or a combination of methods to find evidence.
- Assemble: place selected passages into a controlled prompt with instructions about evidence and uncertainty.
- Generate and cite: produce an answer that links claims to source passages or document locations.
- Evaluate: test retrieval quality, answer correctness, citation support, latency, cost, and fallback behavior.
A simple architecture looks like this:
Documents → Parser → Chunks + Metadata → Embeddings → Vector/Keyword Index
↓
User question → Query processing → Retrieval + Filters → Ranked context
↓
Prompt assembly → LLM → Answer + citations
↓
Logs, feedback, evaluationKeep retrieval and generation separate in your design. If an answer is wrong, you should be able to determine whether the correct passage was not retrieved, the prompt was assembled poorly, or the model misunderstood adequate evidence.
For production work, define the application's answer policy before writing the prompt. Decide whether the assistant may summarize, whether it must quote exact language for sensitive fields, how it should handle conflicting documents, and what it should say when no supporting passage is available. Your RAG system should be designed to abstain rather than confidently fill gaps.
Checklist by scenario
Scenario 1: Building the first document question-answering prototype
- Choose a narrow knowledge domain and a small, representative document set.
- Assign a stable document identifier and retain the original source location.
- Extract headings, paragraphs, lists, tables, page numbers, and meaningful labels where possible.
- Normalize obvious formatting noise without destroying code, formulas, product names, or legal wording.
- Start with chunks based on document structure rather than an arbitrary character count.
- Store each chunk with metadata such as document ID, title, section, page, version, tenant, and permissions scope.
- Implement a basic retrieval trace so developers can inspect the passages sent to the model.
- Require the model to answer only from supplied context and to state when the context is insufficient.
- Display citations that a user can follow back to a document and location.
Scenario 2: Improving irrelevant or incomplete retrieval
- Save the original question, any rewritten query, retrieved chunk IDs, scores, filters, and final answer.
- Test exact names, acronyms, natural-language questions, and questions that require information from more than one section.
- Compare vector search with keyword or hybrid retrieval for identifiers, error codes, product names, and exact phrases.
- Adjust chunk boundaries before simply increasing the number of retrieved chunks.
- Use metadata filters for tenant, product, language, date, document type, or access scope.
- Consider a reranking stage when initial retrieval returns broadly related but poorly ordered passages.
- Check whether parsing removed table headers, footnotes, page relationships, or other information needed to interpret a passage.
Scenario 3: Serving multiple users or document collections
- Enforce authorization before retrieval results reach the prompt, not only in the user interface.
- Keep tenant or collection boundaries explicit in the index and query layer.
- Make document deletion and replacement operations propagate to the search index.
- Version ingestion jobs and record which parser, chunking settings, and embedding configuration produced each record.
- Define behavior for duplicate documents, superseded policies, conflicting versions, and partially indexed collections.
- Limit citations to sources the requesting user is allowed to open.
- Test cross-tenant leakage and stale-content scenarios as part of release validation.
Chunking decision table
| Content type | Useful starting approach | What to preserve |
|---|---|---|
| Policies and manuals | Split by heading and subsection, with modest overlap where a rule spans sections | Section path, exceptions, revision date, page |
| Technical documentation | Keep procedures, code blocks, and explanations together when possible | Version, commands, prerequisites, warnings |
| Tables and catalogs | Convert rows into readable records or retain table structure | Column headers, units, row labels |
| Support tickets | Group by issue or conversation rather than fixed-size fragments | Status, timestamps, product, resolution |
| Long reports | Use hierarchical sections and retrieve at more than one granularity | Title, section, summary, page references |
There is no universal chunk size. The right boundary is the smallest unit that answers a likely question without requiring the model to reconstruct missing context. Validate the choice against real queries rather than treating a framework default as a design decision.
What to double-check
Document quality and ingestion
Inspect representative source files manually. Scanned PDFs may need OCR; multi-column layouts can produce scrambled reading order; tables may lose their headers; and repeated page elements can pollute retrieval. Keep the original file and a traceable parsed version so ingestion errors can be diagnosed.
Make ingestion idempotent. Reprocessing the same source should update the intended records instead of creating uncontrolled duplicates. Use content hashes or another stable change-detection method, and define what happens when a source is removed.
Retrieval and metadata
Metadata is part of the answer system, not merely an indexing convenience. A query about a particular product, date range, region, or policy version should be able to narrow the candidate set. Confirm that filters are applied consistently and that missing metadata does not silently broaden access.
Measure retrieval independently from generation. Create a small evaluation set containing a question, the expected supporting document or passage, and notes about acceptable answers. Review whether the correct evidence appears in the retrieved set and whether it is ranked prominently enough for the context budget.
Prompt assembly and citations
Use a prompt that clearly separates instructions, user input, and retrieved evidence. Tell the model to distinguish supported statements from uncertainty, ignore instructions embedded in retrieved documents, and cite the relevant source for material claims. Keep the context format consistent, for example:
Source: handbook.pdf | Section: Leave policy | Page: 12
Evidence:
[retrieved passage]
User question:
[user question]
Answer using only the evidence above. If it does not support an answer, say so.Do not treat a citation label as proof by itself. Check that each citation points to the passage that supports the claim and that users can access it. If the answer combines multiple sources, make that relationship visible.
Fallbacks, safety, and operations
Define a fallback for empty retrieval, low-confidence retrieval, conflicting sources, model errors, and unavailable search services. A useful fallback may ask the user to narrow the question, direct them to the source collection, or state that the system cannot verify the answer.
Protect sensitive data throughout ingestion, indexing, logging, and model calls. Redact or restrict fields where necessary, and avoid logging complete prompts and documents by default. For broader application controls, see the AI guardrails checklist.
Common mistakes
- Using embeddings as a complete search strategy: semantic similarity can miss exact identifiers and may return conceptually related but operationally wrong passages. Test keyword or hybrid retrieval where precision matters.
- Making chunks too large: large passages consume context and mix unrelated instructions. Start from meaningful sections and inspect retrieved context.
- Making chunks too small: isolated sentences can lose definitions, conditions, and headings. Preserve the context needed to interpret each unit.
- Ignoring document versions: an answer can appear reasonable while relying on an obsolete policy. Store and filter by revision or effective date.
- Trusting retrieval scores blindly: scores are useful signals, not universal confidence values. Validate them against labeled examples.
- Skipping citations: users and reviewers cannot verify answers, and developers lose a key debugging aid.
- Putting authorization in the prompt: instructions cannot replace access control. Filter protected content before it enters the model context.
- Evaluating only fluent answers: a polished response may still be unsupported. Score evidence retrieval, factual support, citation accuracy, and abstention behavior separately.
- Changing several variables at once: changing the parser, chunking, embedding model, retrieval count, and prompt together makes regressions difficult to explain. Version changes and compare them systematically.
When you change models or providers, review the related LLM API migration checklist. When prompt behavior changes, keep prompts versioned and testable using a prompt testing framework.
When to revisit
Revisit this RAG checklist whenever the underlying inputs change, not only when the application code changes. Schedule a review before major planning or content cycles, and repeat it after any of the following events:
- A new document source, file format, language, or collection is added.
- Documents gain tables, scanned pages, images, code, or more complex layouts.
- Chunking, parsing, embedding, vector database, reranking, or model settings change.
- Users report irrelevant answers, missing citations, stale information, or excessive refusals.
- Permissions, tenant boundaries, retention rules, or document ownership change.
- Latency, token usage, indexing failures, or search costs increase.
- A model or API provider changes its context behavior, structured output support, limits, or SDK syntax.
Before releasing an update, rerun a fixed evaluation set and compare retrieval, answer support, citations, latency, and cost with the previous version. Add every confirmed failure to the test set. Then manually inspect a small sample of successful and unsuccessful traces, because aggregate scores can hide failures in a particular document type or user group.
For a practical release routine, confirm that ingestion is reproducible, deleted content is no longer retrievable, access filters are enforced, citations resolve correctly, and the no-answer path is understandable. Keep a short configuration record covering parser version, chunking rules, embedding configuration, retrieval settings, prompt version, and model identifier. That record turns future debugging from guesswork into a repeatable investigation.
Finally, treat RAG as a maintained application feature rather than a one-time integration. The most reliable document question-answering systems are those with observable retrieval, explicit evidence rules, controlled access, and a review process that adapts when documents, workflows, or tools change.