RAG Tutorial for Engineers: Build, Evaluate, and Maintain a Retrieval-Augmented Generation Pipeline
RAGLLMsembeddingsvector databasesAI engineering

RAG Tutorial for Engineers: Build, Evaluate, and Maintain a Retrieval-Augmented Generation Pipeline

QQubeTech Labs
2026-12-06
7 min read

A practical RAG tutorial for engineers covering ingestion, chunking, embeddings, vector search, citations, evaluation, and maintenance.

This RAG tutorial for engineers provides a practical checklist for building a retrieval-augmented generation pipeline that can find relevant technical documents, assemble grounded prompts, return citations, and be evaluated as the knowledge base and application change.

Overview

Retrieval-augmented generation, or RAG, separates an LLM application into two responsibilities. A retrieval system finds relevant passages from your documents, while a language model uses those passages to compose an answer. This is usually more maintainable than sending an entire knowledge base with every request, but retrieval alone does not make an application reliable.

A production-minded RAG pipeline needs a repeatable path from source documents to searchable chunks, a clear metadata model, controlled prompt assembly, and tests that reveal when answers are unsupported or incomplete. The exact embedding model, vector database, orchestration framework, and context-window limits may change over time. The workflow below is designed to remain useful across those implementation changes.

A simple pipeline looks like this:

  1. Collect and normalize source documents.
  2. Split documents into meaningful chunks.
  3. Generate embeddings and store them with metadata.
  4. Retrieve candidate chunks for a user question.
  5. Filter, rank, and format the retrieved context.
  6. Ask the LLM to answer only from the supplied evidence.
  7. Measure retrieval and answer quality with a versioned test set.

Keep ingestion and query-time retrieval as separate components. This makes it easier to re-index documents when chunking or embedding settings change without redesigning the user-facing application.

Checklist by scenario

When adding a new document source

  • Define ownership: Record who maintains the source, how often it changes, and whether it is authoritative for a particular question type.
  • Normalize content: Extract headings, paragraphs, tables, code blocks, and links while removing navigation elements, duplicated footers, and irrelevant boilerplate.
  • Preserve provenance: Store the source URI, title, section heading, document version or update marker, and an identifier for the original file.
  • Set access boundaries: Apply document-level permissions before retrieval results reach the model. Do not rely on the prompt to enforce authorization.
  • Run a sample inspection: Review extracted text from representative documents, including long pages, PDFs, tables, and documents containing code.

When choosing chunking settings

Chunk size should follow the structure of the material and the questions users ask. Smaller chunks can improve precision but may remove necessary context. Larger chunks preserve context but can dilute search relevance and consume more prompt space.

Document typeStarting approachWhat to check
API or product documentationSplit by heading, then by paragraph or code exampleKeep endpoint descriptions, parameters, and examples together where possible
Policies and proceduresSplit by numbered section or requirementPreserve exceptions, definitions, and scope statements
Technical troubleshooting guidesSplit by symptom, diagnosis, and resolutionDo not separate conditions from the steps they qualify
Source code and notebooksSplit by function, class, cell group, or explanatory sectionRetain imports, variable context, and comments needed to interpret a block
Tables and reference dataConvert rows into readable text with column headersVerify that each value remains associated with its label

Use overlap only where it protects meaning across boundaries. Excessive overlap can create duplicate search results and make evaluation harder. Store the chunking configuration with each index so that a result can be traced back to the process that produced it.

When designing metadata

A practical metadata record can include:

{
  "document_id": "stable-source-id",
  "chunk_id": "document-id-section-04",
  "title": "Document title",
  "source_uri": "https://example.invalid/document",
  "section": "Authentication",
  "document_version": "internal-version-or-date",
  "content_type": "api-docs",
  "access_scope": "engineering",
  "ingested_at": "timestamp",
  "embedding_version": "model-or-config-id"
}

Use stable identifiers where possible. A changing ingestion timestamp should not make it impossible to determine whether the underlying content changed. Metadata also supports filters such as product version, team, region, or access scope before semantic ranking takes place.

When building the query path

  1. Validate and normalize the user question.
  2. Apply access and business filters before or during search.
  3. Retrieve more candidates than you plan to show to the model.
  4. Re-rank or deduplicate results if similar chunks dominate the list.
  5. Assemble context with source labels and clear separators.
  6. Set a maximum context budget and define behavior when evidence is insufficient.

A prompt should tell the model what evidence it may use, how to handle conflicts, and when to say that the available documents do not answer the question. Require citations that point to retrieved source identifiers rather than allowing the model to invent URLs or references.

When evaluating a first version

Create a small, representative test set before tuning the pipeline. Each test case should include a question, the expected source document or section, an acceptable answer outline, and any important negative condition. Include questions that require combining two documents, questions with ambiguous terminology, and questions for which the correct response is “not found.”

Evaluate retrieval and generation separately. Retrieval checks whether the required evidence appears in the candidate set. Answer checks whether the response is accurate, complete, appropriately qualified, and supported by the retrieved evidence. Record the index version, prompt version, model configuration, and evaluation date for every run.

What to double-check

Embedding and vector search assumptions

Confirm the embedding model's input limits, output shape, supported languages, and versioning behavior before creating an index. Changing an embedding model generally requires a compatible re-indexing plan; do not assume vectors from different models can be compared meaningfully. Verify the vector database's distance metric, filtering syntax, deletion behavior, and handling of duplicate identifiers.

Context and prompt assembly

Measure the size of retrieved text after formatting, not only the size of individual chunks. System instructions, conversation history, tool output, and citations all consume context. If the context budget is exceeded, use a deterministic trimming or selection policy rather than silently dropping arbitrary passages.

Keep instructions distinct from evidence. A useful pattern is to label each passage with a source and chunk identifier, then instruct the model to cite only those labels. Escape or isolate document text so content inside a document cannot override the application's instructions.

Source quality and conflicts

Retrieval can surface a technically relevant but outdated page. Add version and status metadata, then decide how the application handles conflicts. The answer policy might prefer an approved source, show both versions, or ask the user to clarify. Make this decision explicit and test it.

Operational behavior

  • Log query identifiers, retrieved chunk identifiers, latency, and failure categories without exposing sensitive content unnecessarily.
  • Monitor empty retrievals, repeated fallback answers, unusually large contexts, and citation mismatches.
  • Provide a way to inspect the evidence behind an answer during debugging.
  • Use access controls, retention rules, and redaction appropriate to the documents being indexed.
  • Test ingestion failures separately from model failures so a broken source connector is not mistaken for poor prompting.

Common mistakes

  • Indexing everything without cleaning it: Menus, repeated headers, stale pages, and duplicated content can crowd out useful passages.
  • Choosing chunks by character count alone: A fixed size can split a definition from its exception or a code example from its explanation.
  • Testing only easy questions: A pipeline may answer obvious queries while failing on conflicting versions, negative questions, or multi-step tasks.
  • Evaluating only the final answer: A fluent answer can hide a retrieval failure. Inspect the evidence and citation mapping independently.
  • Using top-k as a quality guarantee: Retrieving more chunks does not ensure that the correct source is present or that the model will use it.
  • Letting the model decide permissions: Authorization belongs in the application and retrieval layer, not in natural-language instructions.
  • Changing several variables at once: Change the chunking rule, embedding model, prompt, or ranking method separately when diagnosing quality.
  • Skipping version tracking: Without index, prompt, and model identifiers, it is difficult to explain why an answer changed.

For prompt and response behavior, a versioned test process is useful. QubeTech's prompt testing workflow offers a related way to compare changes systematically. For documentation sources, the AI-assisted API documentation workflow can help structure the source material before ingestion.

When to revisit

Revisit the pipeline before a seasonal planning cycle, whenever a workflow or source system changes, and after a significant update to an embedding model, vector database, orchestration framework, or LLM. Also review it when users report missing citations, repeated “I don't know” responses, answers based on old material, or unexpectedly high query costs and latency.

Use this maintenance sequence:

  1. Collect recent failure examples and classify them as ingestion, retrieval, ranking, prompt, model, or source-quality issues.
  2. Update the evaluation set with those examples, including the expected evidence and acceptable answer behavior.
  3. Inspect document extraction and metadata before changing model settings.
  4. Run a controlled comparison of the current and proposed configuration.
  5. Check retrieval quality, answer grounding, citations, latency, access controls, and operational logs.
  6. Record the decision, configuration versions, known limitations, and a date for the next review.

Start with a narrow, inspectable corpus and a small test set. Expand only after you can explain which documents were retrieved, why they were selected, and whether the final answer stayed within the evidence. That discipline turns a basic vector search LLM application into a maintainable retrieval-augmented generation system.

Related Topics

#RAG#LLMs#embeddings#vector databases#AI engineering
Q

QubeTech Labs

Technical Editor

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.