Skip to main content
This lesson extends a semantic search system into a Retrieval-Augmented Generation (RAG) pipeline. Instead of returning only matching documents (for example, returning remote-work-policy.pdf for the query β€œwork from home”), the RAG pipeline retrieves relevant context and uses a large language model (LLM) to generate concise, grounded answers such as: β€œYes β€” employees may work up to three days per week from home.” Key concepts covered:
  • Vector store initialization and persistence (ChromaDB)
  • Semantic embeddings with sentence-transformers
  • Smart document chunking for context preservation
  • LLM integration and prompt engineering for RAG
  • A complete pipeline that returns answers with source attributions
Project files:

Environment setup and verification

Install required libraries. Common libraries used in this lab: After installing, run the verification script to confirm dependencies and environment variables are available:
Example verification output:
Once dependencies are confirmed, proceed to initialize the vector store and embedding model.

Task 1 β€” Setup the vector store (ChromaDB)

Create a persistent ChromaDB client and a collection to store document embeddings. Load the sentence-transformers model all-MiniLM-L6-v2 (384-d vectors) to embed document chunks and queries. Example setup code (task_1_setup_vectorstore.py):
Expected run summary:
This collection is your persistent RAG memory where company documents are stored as vectors for semantic retrieval.

Task 2 β€” Document processing and smart chunking

Chunking strategy is critical for RAG quality. Prefer paragraph-based chunking with small overlaps so chunks preserve complete thoughts and transitions. This helps the LLM use coherent context without requiring large token budgets. Example implementation (task_2_document_processing.py):
Notes:
  • Paragraph-based chunking preserves semantics better than fixed-character slices.
  • Make chunk size and overlap parameters configurable for tuning to prompt token limits.

Task 3 β€” LLM integration

Connect a deterministic, production-ready LLM client (for example, GPT-4.1 Mini via an OpenAI-compatible client). Use conservative generation settings (low temperature, token limits) to reduce hallucination and produce concise answers. Example code (task_3_llm_integration.py):
Example test output:
With the LLM client verified, you can assemble a RAG prompt template and wire retrieval and generation together.

Task 4 β€” Prompt engineering for RAG

Craft a prompt template that:
  • Injects retrieved context chunks into the prompt,
  • Explicitly instructs the model to answer only from the provided context,
  • Requires a fixed fallback phrase when the context does not contain the answer to avoid hallucination.
Example prompt builder (task_4_prompt_engineering.py):
Design prompts that explicitly constrain the model to the retrieved context and provide a clear fallback phrase for missing information to prevent hallucinations.
Example generated answer (illustrative):

Task 5 β€” Complete RAG pipeline

Assemble the end-to-end pipeline:
  1. Embed the user’s query using the same embedding model that encoded document chunks.
  2. Query ChromaDB for top-k most relevant chunks (semantic search).
  3. Build a context-aware prompt from those chunks.
  4. Send the system + user prompt to the LLM to generate an answer.
  5. Return the answer along with source attributions (document metadata).
Example pipeline (task_5_complete_rag.py):
Example run and result (illustrative):
This pattern ensures queries are answered using retrieved context and that sources are included for traceability and auditability.

Practical considerations and next steps

  • Tune chunking size and overlap to balance contextual completeness against token limits for your target LLM.
  • Experiment with embedding models (quality vs. cost) and with LLM temperature/length settings.
  • Add filters for document recency, confidentiality tags, or department-level access control.
  • Implement caching, rate limiting, and logging for production usage.
  • Consider connecting to HR systems or identity-aware access control when answers depend on user-specific entitlements.
Handle confidential or restricted documents with care. Ensure access controls and document classification are enforced before including sensitive content in embeddings or returning it in generated answers.
Suggested links and references:
A hand-drawn diagram of a retrieval-augmented generation (R.A.G.) system showing documents (legal, customer support) feeding a vector database into an LLM that processes a user question and produces a generated answer. The sketch also labels it a "Simple Chat App" and shows an example question about remote work policy for international employees.
The diagram above illustrates the simple chat app architecture: documents are embedded into a vector DB, relevant chunks are retrieved for a user question, and an LLM produces a grounded answer that includes source attributions. You’re now set up with a working RAG architecture β€” retrieval, augmentation, and generation β€” ready to iterate and adapt for your production use case.

Watch Video

Practice Lab