Moving Beyond Toy LLM Demonstrations
Large Language Models possess impressive general reasoning capabilities, but they suffer from two critical enterprise limitations: knowledge cut-offs and factual hallucinations when queried about private corporate data. Simply passing an entire 500-page PDF manual into an LLM context window is financially prohibitive, slows response latency, and triggers the “Lost in the Middle” attention degradation problem.
Retrieval-Augmented Generation (RAG) solves this by converting internal documents into mathematical vector embeddings, storing them in an indexed vector database (ChromaDB), and dynamically injecting only the top most relevant context chunks into the LLM prompt at query time.
In this engineering guide, we architect a complete end-to-end RAG system in Python featuring document parsing, recursive character chunking with overlap, semantic similarity search, and source-attributed responses.
RAG Architectural Pipeline
Production Retrieval-Augmented Generation Pipeline:
Indexing Stage:
Raw Enterprise PDFs ──► Document Parser ──► Recursive Chunking (500 tokens, 10% overlap)
│
Embedding Model (text-embedding-3-small)
│
▼
ChromaDB Vector Store
Query Stage:
User Query ──► Vector Embed ──► Similarity Search (Cosine Top-k) ──► Re-Ranker
│
Augmented Prompt (Context + Question) ──┘
│
▼
LLM (Claude / GPT-4o) ──► Factual Verified Response1. Intelligent Chunking & Vector Ingestion
# ingest.py
import os
from langchain_community.document_loaders import PyPDFLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_openai import OpenAIEmbeddings
from langchain_chroma import Chroma
CHROMA_PATH = "./chroma_db"
def ingest_enterprise_documents(pdf_directory: str):
print("Loading internal documents...")
documents = []
for file in os.listdir(pdf_directory):
if file.endswith(".pdf"):
loader = PyPDFLoader(os.path.join(pdf_directory, file))
documents.extend(loader.load())
# Recursive chunking keeps sentences and paragraphs intact
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=600,
chunk_overlap=100,
length_function=len,
separators=["\n\n", "\n", " ", ""]
)
chunks = text_splitter.split_documents(documents)
print(f"Generated {len(chunks)} contextual chunks.")
# Initialize embeddings and persist to ChromaDB
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
vector_store = Chroma.from_documents(
documents=chunks,
embedding=embeddings,
persist_directory=CHROMA_PATH
)
print("Vector database successfully populated!")
if __name__ == "__main__":
ingest_enterprise_documents("./docs")2. Production Query Pipeline with Context Attribution
# query_engine.py
from langchain_chroma import Chroma
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_core.output_parsers import StrOutputParser
CHROMA_PATH = "./chroma_db"
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
vector_store = Chroma(persist_directory=CHROMA_PATH, embedding_function=embeddings)
retriever = vector_store.as_retriever(
search_type="similarity_score_threshold",
search_kwargs={"k": 4, "score_threshold": 0.5}
)
RAG_PROMPT_TEMPLATE = """
You are a senior technical enterprise assistant. Answer the user's question using ONLY the provided context below.
If the answer cannot be found in the context, explicitly state: "I do not have sufficient information in the verified documentation to answer this."
Never guess or hallucinate facts.
Context:
{context}
Question:
{question}
Answer with source citations:
"""
prompt = ChatPromptTemplate.from_template(RAG_PROMPT_TEMPLATE)
llm = ChatOpenAI(model="gpt-4o", temperature=0.0)
def format_docs(docs):
return "\n\n".join([f"[Source: {d.metadata.get('source', 'Unknown')}]: {d.page_content}" for d in docs])
rag_chain = (
{"context": retriever | format_docs, "question": RunnablePassthrough()}
| prompt
| llm
| StrOutputParser()
)
def ask(query: str):
response = rag_chain.invoke(query)
print(f"\nQ: {query}\n\nA: {response}")
if __name__ == "__main__":
ask("What is our disaster recovery RPO for Postgres clusters?")Frequently Asked Questions (FAQ)
What is the difference between HyDE and standard vector retrieval?
Hypothetical Document Embeddings (HyDE) uses the LLM to generate a hypothetical answer to the user’s query first, and then embeds that answer to search the vector database. Because answers look more like indexed document passages than short questions do, HyDE significantly boosts retrieval accuracy for ambiguous user queries.
Related Architectural Deep Dives
Continue expanding your technical depth with our related engineering guides:
- Related Resource: Deep dive into our guide on Building an AI Coding Assistant: Practical Developer Guide.
- High-Throughput REST APIs with FastAPI & Asyncpg: Asynchronous Python architecture achieving 10k+ RPS with connection pooling. Explore the complete guide: High-Throughput REST APIs with FastAPI & Asyncpg.
- Python Asyncio Architecture: Mastering event loops, coroutines, tasks, and structured concurrency with TaskGroup. Explore the complete guide: Python Asyncio Architecture.
Published by Mohit Kumar under Applied AI & Engineering. Explore our guide on Agentic AI Architecture & Autonomous Systems.




