The Fundamental Problem of LLMs: Hallucination & Knowledge Cutoffs
Large Language Models (LLMs) such as GPT-4o and Claude 3.5 Sonnet exhibit remarkable reasoning capabilities, yet they are constrained by static training cutoff dates and a propensity for stochastic hallucination. When an enterprise queries an LLM regarding internal proprietary documentation, real-time database records, or specialized domain guidelines, standard zero-shot prompting either fails entirely or produces plausible but incorrect statements.
Retrieval-Augmented Generation (RAG) solves this architectural limitation. Rather than relying solely on the parametric memory stored within LLM weights, RAG decouples information storage from inference. The system retrieves verified, semantically relevant documents from an external vector index and injects them directly into the context window of the LLM prompt, forcing the model to generate factual, ground-truth-anchored responses.
The End-to-End RAG Pipeline Architecture
A production-grade RAG pipeline consists of five decoupled stages:
- Document Ingestion & Semantic Chunking: Raw text extracted from PDFs, Markdown, SQL tables, and APIs is segmented using recursive character chunking (500–800 tokens) with 10–15% overlap to preserve semantic continuity across boundaries.
- Vector Embedding Generation: Each text chunk is mapped into high-dimensional vector space using embedding models (e.g.,
text-embedding-3-smallat 1536 dimensions orbge-large-en-v1.5at 1024 dimensions). - Vector Indexing with PostgreSQL & pgvector: Vector embeddings are indexed in relational PostgreSQL storage using Hierarchical Navigable Small World (HNSW) graphs with cosine distance (
vector_cosine_ops), enabling sub-50ms nearest-neighbor retrieval. - Hybrid Search (Dense + Sparse): Queries are executed concurrently against the dense vector index and sparse PostgreSQL full-text search (BM25 with
tsvector), combined via Reciprocal Rank Fusion (RRF). - Cross-Encoder Re-Ranking: The top 20 candidate documents are passed through a cross-encoder model (e.g., Cohere Rerank v3) to evaluate deep semantic relevance, pruning the context down to the top 3–5 most authoritative chunks before generation.
Production SQL: PostgreSQL pgvector Hybrid Similarity Query
The following SQL snippet demonstrates an optimized hybrid retrieval query executing over both semantic vector embeddings and lexical keywords:
-- Enable pgvector extension
CREATE EXTENSION IF NOT EXISTS vector;
-- Query combining cosine vector distance with text search weighting
WITH semantic_search AS (
SELECT id, document_id, content,
1 - (embedding <=> $1::vector) AS semantic_score
FROM document_embeddings
ORDER BY embedding <=> $1::vector ASC
LIMIT 20
),
keyword_search AS (
SELECT id, document_id, content,
ts_rank_cd(to_tsvector('english', content), plainto_tsquery('english', $2)) AS keyword_score
FROM document_embeddings
WHERE to_tsvector('english', content) @@ plainto_tsquery('english', $2)
LIMIT 20
)
SELECT COALESCE(s.id, k.id) AS chunk_id,
COALESCE(s.content, k.content) AS chunk_content,
COALESCE(s.semantic_score, 0) * 0.7 + COALESCE(k.keyword_score, 0) * 0.3 AS combined_rank
FROM semantic_search s
FULL OUTER JOIN keyword_search k ON s.id = k.id
ORDER BY combined_rank DESC
LIMIT 5;
Advanced RAG Patterns: Agentic Retrieval & Hypothetical Document Embeddings (HyDE)
Standard naive RAG breaks down when user questions are ambiguous or require multi-hop reasoning across multiple documents. Advanced production implementations utilize Agentic RAG, where an orchestration agent (built with LangGraph or LlamaIndex) decides dynamically whether to retrieve context, decompose complex questions into sub-queries, or re-write user prompts using Hypothetical Document Embeddings (HyDE).
Under HyDE, the LLM first generates a hypothetical answer to the user's query. The vector embedding of that synthetic answer is then used to query the vector database, bridging the semantic gap between question phrasing and document phrasing.
Evaluating RAG Accuracy: The RAG Triad Metrics
Quantifying retrieval quality requires automated continuous evaluation using the RAG Triad framework:
- Context Relevance: Measures whether the retrieved chunks are pertinent to the user's original query, eliminating context-window bloat.
- Groundedness (Faithfulness): Verifies that every assertion made in the model's generated response can be directly cited from the retrieved context.
- Answer Relevance: Ensures the final response directly and concisely answers the user's inquiry without extraneous digressions.
Enterprise RAG Engineering with Nexivtech
Nexivtech architects bespoke, high-performance RAG and AI search pipelines for organizations with sensitive enterprise data. Explore our dedicated RAG Development Services and our Enterprise AI Solutions.
