CHAPTER 16: BUILDING RETRIEVAL-AUGMENTED GENERATION (RAG) PIPELINES

Master enterprise AI grounding. Learn how to combine vector search retrieval with OpenAI chat completions to build robust Retrieval-Augmented Generation (RAG) pipelines that eliminate hallucinations and answer queries from private knowledge bases.

πŸ“š Grounding LLMs in Private Enterprise Data

While foundation models possess broad general knowledge, they lack awareness of private corporate documents, proprietary databases, and real-time internal wikis. Fine-tuning models is often expensive and inflexible. Retrieval-Augmented Generation (RAG) solves this by dynamically searching your private document store for relevant context when a user asks a question, injecting those snippets into the prompt, and instructing the model to synthesize an accurate, source-grounded answer.

1. The End-to-End RAG Architecture
Understanding the two core phases of a RAG pipeline: offline document ingestion and online query execution.
RAG Pipeline Workflow Matrix
RAG ARCHITECTURE PHASES:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ PHASE                  β”‚ STEPS                                                                  β”‚ DESCRIPTION                               β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ 1. Ingestion Pipeline  β”‚ Load $\rightarrow$ Chunk $\rightarrow$ Embed $\rightarrow$ Store       β”‚ Parse raw documents, split into 500-token β”‚
β”‚                        β”‚                                                                        β”‚ chunks, generate vectors, save in DB.     β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ 2. Retrieval Pipeline  β”‚ Query $\rightarrow$ Embed $\rightarrow$ Search $\rightarrow$ Synthesizeβ”‚ Embed user query, search vector DB for    β”‚
β”‚                        β”‚                                                                        β”‚ top matches, inject into prompt for LLM.  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Architectural Definition: RAG separates long-term knowledge storage (vector database) from short-term reasoning (LLM context window), ensuring answers are verifiable and up-to-date.
2. Constructing RAG Prompt Templates
Structuring system instructions and prompt context blocks to prevent hallucination and enforce strict grounding.
RAG Prompt Template Structure
RAG PROMPT TEMPLATE:
System:
"You are a helpful enterprise knowledge assistant. Answer questions strictly based on the provided context excerpts. If the answer cannot be found in the context, state: 'I cannot find the answer in our internal knowledge base.'"

User:
"Context Excerpts:
---
{retrieved_chunks}
---

User Question: {user_query}"
Engineering Insight: Explicitly instructing the model to refuse answering when context is missing is critical for preventing hallucinations in enterprise RAG applications.
3. Python Code Example: Complete RAG Pipeline
A production Python script demonstrating an end-to-end RAG pipeline: document embedding, similarity retrieval, prompt augmentation, and OpenAI chat synthesis.
Python (rag_pipeline_demo.py)
import numpy as np
from openai import OpenAI

# 1. Mock Enterprise Knowledge Base (Documents)
knowledge_base = [
    {"id": "DOC-1", "text": "CloudScale API rate limits are set to 10,000 requests per minute for Enterprise tier customers."},
    {"id": "DOC-2", "text": "To reset your CloudScale database password, navigate to Dashboard > Security > Reset Master Credentials."},
    {"id": "DOC-3", "text": "CloudScale data centers are SOC2 Type II certified and located in US-East and EU-Central regions."}
]

def cosine_similarity(a, b):
    return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))

def run_rag_pipeline(user_query: str):
    client = OpenAI()
    
    print(f"[*] User Query: \"{user_query}\"\n")
    
    # 2. Generate embedding for user query
    query_resp = client.embeddings.create(
        model="text-embedding-3-small",
        input=user_query
    )
    query_vector = np.array(query_resp.data[0].embedding)
    
    # 3. Retrieve relevant document chunks via cosine similarity search
    scored_docs = []
    for doc in knowledge_base:
        doc_resp = client.embeddings.create(
            model="text-embedding-3-small",
            input=doc["text"]
        )
        doc_vector = np.array(doc_resp.data[0].embedding)
        score = cosine_similarity(query_vector, doc_vector)
        scored_docs.append((score, doc["text"]))
        
    # Sort by highest similarity score and select top 2 chunks
    scored_docs.sort(key=lambda x: x[0], reverse=True)
    top_chunks = [chunk[1] for chunk in scored_docs[:2]]
    
    context_block = "\n\n".join([f"- {chunk}" for chunk in top_chunks])
    print(f"[*] Retrieved Context Chunks:\n{context_block}\n")
    
    # 4. Augment Prompt and Call Chat Completions API
    system_prompt = (
        "You are an enterprise knowledge assistant. Answer questions strictly based "
        "on the provided context excerpts. If the answer is not present in the context, "
        "state: 'I cannot find the answer in our internal knowledge base.'"
    )
    
    user_prompt = f"Context Excerpts:\n{context_block}\n\nUser Question: {user_query}"
    
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_prompt}
        ],
        temperature=0.0
    )
    
    print("[+] Synthesized RAG Answer:")
    print(response.choices[0].message.content)

if __name__ == "__main__":
    run_rag_pipeline("What are the API rate limits for Enterprise customers?")
Execution Output: [*] User Query: "What are the API rate limits for Enterprise customers?" [*] Retrieved Context Chunks: - CloudScale API rate limits are set to 10,000 requests per minute for Enterprise tier customers. - To reset your CloudScale database password, navigate to Dashboard > Security > Reset Master Credentials. [+] Synthesized RAG Answer: Based on our internal documentation, CloudScale API rate limits are set to 10,000 requests per minute for Enterprise tier customers.
4. Best Practices for Production RAG Pipelines
Software engineering standards for hybrid search, reranking, and evaluating retrieval accuracy.
RAG Best Practices Checklist
RAG PRODUCTION CHECKLIST:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ BEST PRACTICE          β”‚ IMPLEMENTATION & OBJECTIVE                                                    β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Implement Hybrid Searchβ”‚ Combine dense vector search with sparse keyword search (BM25) to ensure       β”‚
β”‚                        β”‚ precise retrieval of technical terms and IDs.                                 β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Use Cross-Encoder      β”‚ Pass retrieved chunks through a reranking model (e.g., Cohere Rerank) to      β”‚
β”‚ Reranking              β”‚ re-order excerpts by true relevance before prompt injection.                  β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Set Strict Fallbacks   β”‚ Instruct models to decline answering when retrieved context scores fall below β”‚
β”‚                        β”‚ a minimum similarity threshold.                                               β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Masterclass Rule: Combining vector similarity retrieval with cross-encoder reranking and strict fallback instructions ensures enterprise RAG pipelines deliver high-precision answers.
5. Masterclass Conclusion & Next Steps
Reviewing the OpenAI Masterclass curriculum journey and exploring advanced fine-tuning and production deployment.
Masterclass Curriculum Review
OPENAI MASTERCLASS SUMMARY:
1. Core Ecosystem & SDK Setup: Mastery of model tiers, authentication, and secure initialization (Chapters 1-2).
2. Chat Completions & Streaming: Building responsive SSE chat interfaces and optimizing token costs (Chapters 3-5).
3. Advanced Prompting & Structured Outputs: Few-shot CoT reasoning and Pydantic-validated JSON extraction (Chapters 6-9).
4. Tool Calling & RAG Pipelines: Connecting LLMs to local databases, REST APIs, vector search, and RAG (Chapters 10-16).
Masterclass Completion: Congratulations on completing the OpenAI Masterclass curriculum! You are now fully equipped to engineer robust, secure, and production-grade AI applications.