IIT Madras Zanzibar · Teaching

Module 10: Modern & AI Data Systems · Lecture 44 · Week 15

RAG Pipelines & LLM Integration

Retrieval-Augmented Generation: databases as the knowledge backbone for language models

Learning Objectives

RAG pipeline diagram
Figure 44.1: The RAG pipeline: documents are chunked, embedded, and stored in a vector database (offline); at query time, relevant chunks are retrieved and injected into the LLM prompt (online)

1. The Hallucination Problem

Large Language Models (LLMs) generate plausible-sounding text by predicting the next token given their training data. They are excellent at reasoning, summarization, and language tasks. However, they carry a well-known weakness: hallucination: generating confident but factually incorrect statements, especially for:

Retrieval-Augmented Generation (RAG)

RAG solves hallucination by grounding the LLM in retrieved facts. Instead of asking the model to recall from memory, we:
(1) Retrieve the relevant passages from a database at query time
(2) Inject those passages into the LLM prompt as context
(3) Generate an answer that is grounded in: and citable from: retrieved documents

The database acts as the model's external, up-to-date, domain-specific knowledge store.

2. The RAG Pipeline

Raw Documents
→
Chunking
→
Embedding Model
→
Vector Store
→
ANN Index

Offline (indexing phase: run once or on document update)

User Query
→
Embed Query
→
ANN Search
→
Top-k Chunks
→
LLM Prompt
→
Answer

Online (inference phase: runs per query)

3. Offline Phase: Indexing

3.1 Chunking

Documents must be split into chunks before embedding. Chunk size is an important design decision: it trades precision against context:

Chunk StrategySizeProsCons
Fixed-size (char)200–500 charsSimple; uniform sizeMay cut sentences mid-thought; context lost at boundary
Fixed-size (token)128–512 tokensMatches embedding model inputSplits at arbitrary points
Sentence-based1–5 sentencesSemantically coherent unitsVariable size; may be too short
Paragraph-based1 paragraphNatural document unitParagraphs vary widely in length
Semantic chunkingVariableGroups semantically similar sentencesRequires embedding pass on all sentences; expensive
Recursive characterVariableSplits on paragraphs, then sentences, then wordsComplex to implement

Overlap to Preserve Context

When chunking by fixed size, add an overlap of 10–20% between consecutive chunks. A sentence split across two chunks is present in both, so neither loses the context of the boundary sentence. Common choice: chunk_size=512 tokens, overlap=64 tokens.

3.2 Embedding and Storage

Offline indexing (Python pseudocode): from openai import OpenAI import psycopg2 client = OpenAI() # For each chunk in the document corpus: for chunk_text in all_chunks: # 1. Generate embedding response = client.embeddings.create( input=chunk_text, model="text-embedding-3-small" # 1536 dims ) embedding = response.data[0].embedding # list of 1536 floats # 2. Store chunk + embedding in PostgreSQL (with pgvector) cur.execute( "INSERT INTO chunks (doc_id, text, embedding) VALUES (%s, %s, %s)", (doc_id, chunk_text, embedding) ) conn.commit()

4. Online Phase: Retrieval and Generation

4.1 Query Embedding and Retrieval

def retrieve(query: str, k: int = 5) -> list[str]: # Embed the query using the same model q_emb = client.embeddings.create(input=query, model="text-embedding-3-small") .data[0].embedding # Vector similarity search (cosine distance via pgvector) cur.execute(""" SELECT text FROM chunks ORDER BY embedding <=> %s::vector LIMIT %s """, (q_emb, k)) return [row[0] for row in cur.fetchall()]

4.2 Prompt Construction

def build_prompt(query: str, contexts: list[str]) -> str: context_block = "\n\n---\n\n".join(contexts) return f"""You are a helpful database assistant. Answer the question using ONLY the context below. If the answer is not in the context, say "I don't know." CONTEXT: {context_block} QUESTION: {query} ANSWER:"""

4.3 Generation

def rag_query(query: str) -> str: contexts = retrieve(query, k=5) prompt = build_prompt(query, contexts) response = client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": prompt}], temperature=0.2 # low temperature → more factual ) return response.choices[0].message.content # Usage answer = rag_query("What is the fan-out of a B+ tree of order 4?")

5. Advanced RAG Techniques

5.1 Hybrid Search

Pure vector search can miss keyword-specific queries (e.g., searching for "ARIES" retrieves semantically related documents but may miss the exact algorithm name). Hybrid search combines:

Scores are fused using Reciprocal Rank Fusion (RRF): rank each result set separately, then sum 1/(k+rank) across both rankers. Documents that appear high in both lists get the highest combined score.

5.2 Re-Ranking

After retrieving top-k candidates, apply a cross-encoder re-ranker (a model that jointly encodes query+passage to produce a relevance score). Cross-encoders are more accurate than bi-encoders (used for initial retrieval) but too slow to run over all documents. Apply only to the top 20–50 retrieved candidates.

5.3 Metadata Filtering

-- Retrieve only chunks from documents tagged as "module_8" SELECT text FROM chunks WHERE metadata->>'module' = 'module_8' ORDER BY embedding <=> %s::vector LIMIT 5;

5.4 Parent-Child Chunking

Store small child chunks (for precise retrieval) but return their parent chunk (larger context window) to the LLM. The child chunk's high specificity improves recall; the parent's broader context improves generation quality.

6. RAG vs. Fine-Tuning

RAGFine-Tuning
Knowledge updateAdd documents to vector store: instantRetrain model: expensive (hours/days)
CostLow: vector store + embedding APIHigh: GPU training time + compute
HallucinationGrounded in retrieved documentsModel may still hallucinate
Reasoning styleKeeps base model reasoning; grounded answersModel adopts new style/behavior
Best forPrivate documents, frequently changing knowledgeDomain-specific language, tone, formatting

RAG Failure Modes

Bad chunks: chunks too small lose context; chunks too large dilute relevance signals.
Retrieval miss: the relevant passage is not retrieved (poor recall): increase k or use hybrid search.
Faithfulness failure: the LLM ignores the retrieved context and hallucinates anyway: lower temperature, use strict prompting, check with a faithfulness evaluator.
Irrelevant context: retrieved passages confuse rather than help: improve retrieval quality, add metadata filters, use a re-ranker.

7. The Database Engineer's Role in AI Systems

RAG makes database skills more important, not less, in the age of AI:

8. Summary