π 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.
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. β
ββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββ
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}"
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?")
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. β
ββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
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).