RAG Pipelines
This chapter treats retrieval as an information-retrieval system with chunking, metadata, embeddings, lexical search, fusion, reranking, citation assembly, offline evaluation, and production telemetry.
- Explain Chunking & embedding strategies by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Hybrid search (BM25 + semantic) by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Re-ranking & evaluation by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Vector store & embedding choices by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Trace the chapter's complete execution path and identify where memory, I/O, concurrency, persistence, or rendering cost accumulates.
How to use this chapter
For RAG Pipelines, read the explanations first and predict every example before running it. Keep a learning repository containing code, tests, command output, and the short written submission. The roadmap checklist at the end audits coverage; the chapter itself follows the architecture learning arc appropriate to this subject.
The problem this chapter solves
This chapter treats retrieval as an information-retrieval system with chunking, metadata, embeddings, lexical search, fusion, reranking, citation assembly, offline evaluation, and production telemetry.
A model alone has limited freshness, reliability, context, and agency. Engineering layers constrain outputs, ground claims in data, and make decisions inspectable and recoverable.
Learning outcomes
- Explain Chunking & embedding strategies by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Hybrid search (BM25 + semantic) by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Re-ranking & evaluation by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Vector store & embedding choices by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Trace the chapter's complete execution path and identify where memory, I/O, concurrency, persistence, or rendering cost accumulates.
- Build the worked example, make one failure visible, and defend the design in a review.
Chapter progression
The order below is intentional: later sections depend on guarantees established earlier.
Runtime or system overview
Text is tokenized and processed autoregressively: each output token is sampled from a conditional distribution. Retrieval adds selected external context; tool calling asks normal code to perform actions; agent graphs persist explicit state and routes. None of these mechanisms guarantee truth, so evaluation and validation remain mandatory. In RAG Pipelines, use that execution model to decide where the chapter's validation, state ownership, cleanup, and evidence belong.
Execution trace
- Deterministic code validates the request, identity, tenant, budgets, schemas, and permitted tools before assembling model context.
- Retrieval or memory selection chooses bounded, provenance-bearing evidence; tokenization converts the assembled messages into the model's input sequence.
- The provider generates or streams tokens, or proposes typed tool arguments; application code validates every output and executes only authorized bounded actions.
- Parsers and business rules accept, repair once under policy, route, or reject the result; citations and state transitions are persisted with model, prompt, index, and dataset versions.
- Offline evaluation and production telemetry measure retrieval, faithfulness, latency, token cost, tool errors, safety outcomes, and regressions by cohort.
Memory and performance lens
Context windows hold tokens, not durable memory. Conversation memory is application-managed storage that is selected and inserted into later prompts. Embedding indexes store vectors plus metadata; agent checkpoints store state transitions. Token budgets, cache policy, and data retention must be designed explicitly. For RAG Pipelines, connect those costs to the concrete operations in the topic sections rather than assuming the friendly surface syntax is cheap.
When tuning RAG Pipelines, measure capacity per critical path, tail latency, availability/error budget, consistency lag, recovery objectives, cost per outcome, and evaluation quality rather than optimizing from source-code appearance.
1. Chunking & embedding strategies
The Chunking & embedding strategies unit begins with fixed-size vs semantic vs recursive chunking: Fixed-size chunking uses a token/character window; recursive chunking prefers increasingly smaller structural separators; semantic chunking splits where meaning shifts. Begin with a measurable recursive baseline, preserve section metadata, and tune size/overlap on real questions. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
Requirements, ownership, and trade-offs: Chunking & embedding strategies
| Concept | Meaning | Engineering decision |
|---|---|---|
| fixed-size vs semantic vs recursive chunking | Fixed-size chunking uses a token/character window; recursive chunking prefers increasingly smaller structural separators; semantic chunking splits where meaning shifts. | Begin with a measurable recursive baseline, preserve section metadata, and tune size/overlap on real questions. |
| document-specific: markdown headers/HTML/code | Document-aware splitting preserves natural structure such as Markdown headings, HTML elements, pages, clauses, functions, or classes. | Use format-specific parsing when structure carries meaning or citations must identify a stable section. |
| OpenAI text-embedding-3-small/large dimensions+cost | Hosted embedding models trade price, latency, dimensions, multilingual/domain quality, and operational simplicity; model selection must follow evaluation rather than size alone. | Record model, dimensions, normalization, distance, and index version; compare quality and cost on the same corpus. |
| BGE-M3 and E5-large open source alternatives | Open embedding models offer self-hosting, data control, and domain fine-tuning at the cost of serving, scaling, batching, and upgrade responsibility. | Choose self-hosting when privacy, predictable volume, custom tuning, or provider independence justifies operational work. |
| batching embeddings efficiently | Embedding batching combines texts into bounded requests or tensor batches to improve throughput and accelerator/network utilization. | Batch by both item count and token budget, use strict identity/order checks, and checkpoint progress for restartable ingestion. |
Critical path and failure behavior: Chunking & embedding strategies
fixed-size vs semantic vs recursive chunking. A splitter produces overlapping retrieval units. Smaller chunks improve targeting but lose surrounding context; larger chunks preserve context but dilute similarity and consume more prompt tokens.
document-specific: markdown headers/HTML/code. A parser builds structural nodes before chunks are assembled; metadata retains the hierarchy so retrieval filters and citations can reconstruct where evidence came from.
OpenAI text-embedding-3-small/large dimensions+cost. The provider converts each text into a fixed-dimensional vector. The index dimension and distance metric must match the model configuration used for both stored documents and queries.
BGE-M3 and E5-large open source alternatives. A tokenizer and encoder run on CPU/GPU to create vectors; pooling and normalization must follow the model's instructions, and query/document prefixes may be required.
batching embeddings efficiently. The client groups items under provider token/request limits, preserves identity across the returned vector order, retries transient failures, and upserts only validated results.
Read these as one system: fixed-size vs semantic vs recursive chunking establishes the starting contract, document-specific: markdown headers/HTML/code changes how that contract is executed or represented, and batching embeddings efficiently exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A concrete design decision: Chunking & embedding strategies
1def chunks(tokens: list[str], size: int = 400, overlap: int = 60):2 if not 0 <= overlap < size:3 raise ValueError("overlap must be smaller than size")4 step = size - overlap5 for start in range(0, len(tokens), step):6 yield tokens[start:start + size]This Chunking & embedding strategies slice makes fixed-size vs semantic vs recursive chunking observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward batching embeddings efficiently, predict its behavior for empty, invalid, repeated, and large input.
Designs that fail under real load: Chunking & embedding strategies
| Risk | Why it matters |
|---|---|
| fixed-size vs semantic vs recursive chunking | Choosing chunk size by intuition alone can improve one demonstration while reducing retrieval recall across the evaluation set. |
| document-specific: markdown headers/HTML/code | Stripping all structure into plain text can join unrelated sections, split code mid-symbol, and produce unusable citations. |
| OpenAI text-embedding-3-small/large dimensions+cost | Changing the model or dimensions without building a new index silently makes query and stored vectors incompatible. |
| BGE-M3 and E5-large open source alternatives | Using the wrong prompt prefix, pooling, normalization, or precision can severely reduce retrieval quality while still returning valid vectors. |
| batching embeddings efficiently | One oversized batch can exceed memory or API limits; retrying a partially stored batch without stable IDs can duplicate or mismatch records. |
Design review exercise: Chunking & embedding strategies
- Foundation: implement or demonstrate fixed-size vs semantic vs recursive chunking with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine fixed-size vs semantic vs recursive chunking with document-specific: markdown headers/HTML/code. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for batching embeddings efficiently. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
2. Hybrid search (BM25 + semantic)
The Hybrid search (BM25 + semantic) unit begins with BM25 keyword search (TF-IDF): Lexical retrieval ranks exact and related terms using an inverted index; BM25 rewards term evidence while controlling for document length and common terms. Keep lexical search for names, codes, quotations, rare terminology, and exact legal language that embeddings may blur. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
Requirements, ownership, and trade-offs: Hybrid search (BM25 + semantic)
| Concept | Meaning | Engineering decision |
|---|---|---|
| BM25 keyword search (TF-IDF) | Lexical retrieval ranks exact and related terms using an inverted index; BM25 rewards term evidence while controlling for document length and common terms. | Keep lexical search for names, codes, quotations, rare terminology, and exact legal language that embeddings may blur. |
| Reciprocal Rank Fusion (RRF) for score merging | Lexical retrieval ranks exact and related terms using an inverted index; BM25 rewards term evidence while controlling for document length and common terms. | Keep lexical search for names, codes, quotations, rare terminology, and exact legal language that embeddings may blur. |
| weighted hybrid: α×semantic + (1-α)×BM25 | Lexical retrieval ranks exact and related terms using an inverted index; BM25 rewards term evidence while controlling for document length and common terms. | Keep lexical search for names, codes, quotations, rare terminology, and exact legal language that embeddings may blur. |
| PostgreSQL ts_vector + pgvector combined | Lexical retrieval ranks exact and related terms using an inverted index; BM25 rewards term evidence while controlling for document length and common terms. | Keep lexical search for names, codes, quotations, rare terminology, and exact legal language that embeddings may blur. |
Critical path and failure behavior: Hybrid search (BM25 + semantic)
BM25 keyword search (TF-IDF). The engine analyzes text into tokens, stores postings, and calculates a score from term frequency, inverse document frequency, and length normalization.
Reciprocal Rank Fusion (RRF) for score merging. The engine analyzes text into tokens, stores postings, and calculates a score from term frequency, inverse document frequency, and length normalization.
weighted hybrid: α×semantic + (1-α)×BM25. The engine analyzes text into tokens, stores postings, and calculates a score from term frequency, inverse document frequency, and length normalization.
PostgreSQL ts_vector + pgvector combined. The engine analyzes text into tokens, stores postings, and calculates a score from term frequency, inverse document frequency, and length normalization.
Read these as one system: BM25 keyword search (TF-IDF) establishes the starting contract, Reciprocal Rank Fusion (RRF) for score merging changes how that contract is executed or represented, and PostgreSQL ts_vector + pgvector combined exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A concrete design decision: Hybrid search (BM25 + semantic)
1def rrf(rankings: list[list[str]], k: int = 60) -> dict[str, float]:2 scores: dict[str, float] = {}3 for ranking in rankings:4 for rank, document_id in enumerate(ranking, start=1):5 scores[document_id] = scores.get(document_id, 0.0) + 1 / (k + rank)6 return scoresThis Hybrid search (BM25 + semantic) slice makes BM25 keyword search (TF-IDF) observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward PostgreSQL ts_vector + pgvector combined, predict its behavior for empty, invalid, repeated, and large input.
Designs that fail under real load: Hybrid search (BM25 + semantic)
| Risk | Why it matters |
|---|---|
| BM25 keyword search (TF-IDF) | Applying inconsistent analyzers to indexed text and queries or using stop-word rules blindly can remove the only discriminating evidence. |
| Reciprocal Rank Fusion (RRF) for score merging | Applying inconsistent analyzers to indexed text and queries or using stop-word rules blindly can remove the only discriminating evidence. |
| weighted hybrid: α×semantic + (1-α)×BM25 | Applying inconsistent analyzers to indexed text and queries or using stop-word rules blindly can remove the only discriminating evidence. |
| PostgreSQL ts_vector + pgvector combined | Applying inconsistent analyzers to indexed text and queries or using stop-word rules blindly can remove the only discriminating evidence. |
Design review exercise: Hybrid search (BM25 + semantic)
- Foundation: implement or demonstrate BM25 keyword search (TF-IDF) with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine BM25 keyword search (TF-IDF) with Reciprocal Rank Fusion (RRF) for score merging. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for PostgreSQL ts_vector + pgvector combined. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
3. Re-ranking & evaluation
The Re-ranking & evaluation unit begins with cross-encoder rerankers: Cohere Rerank/BGE-Reranker: A re-ranker scores the query and each candidate together, usually improving top-result precision at higher per-candidate cost. Retrieve broadly and re-rank a bounded set when answer quality depends on the best few passages. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
Requirements, ownership, and trade-offs: Re-ranking & evaluation
| Concept | Meaning | Engineering decision |
|---|---|---|
| cross-encoder rerankers: Cohere Rerank/BGE-Reranker | A re-ranker scores the query and each candidate together, usually improving top-result precision at higher per-candidate cost. | Retrieve broadly and re-rank a bounded set when answer quality depends on the best few passages. |
| two-stage: retrieve 50 → rerank → top 5 | RAG reranking applies a more expensive query-document relevance model to a small candidate set, while evaluation measures retrieval coverage, citation support, answer relevance, and faithfulness on a versioned dataset. | Evaluate retrieval separately from generation, retain per-question evidence, and gate prompt/model/index changes against baselines and latency budgets. |
| RAGAS metrics: faithfulness/answer relevancy/context precision/recall | Answer evaluation separates whether a response addresses the question, whether its claims are supported by supplied evidence, and whether retrieved context is relevant. | Use a frozen regression set, judge calibration, thresholded release gates, and periodic human audit. |
| LLM-as-judge for answer quality | RAG reranking applies a more expensive query-document relevance model to a small candidate set, while evaluation measures retrieval coverage, citation support, answer relevance, and faithfulness on a versioned dataset. | Evaluate retrieval separately from generation, retain per-question evidence, and gate prompt/model/index changes against baselines and latency budgets. |
Critical path and failure behavior: Re-ranking & evaluation
cross-encoder rerankers: Cohere Rerank/BGE-Reranker. Unlike independent embeddings, a cross-encoder attends jointly to query and passage. It runs only on a limited candidate set and returns a new ordering.
two-stage: retrieve 50 → rerank → top 5. The pipeline retrieves broad candidates, reranks them, builds grounded context, generates an answer, and records retrieval and answer metrics such as context precision/recall and faithfulness.
RAGAS metrics: faithfulness/answer relevancy/context precision/recall. A combination of deterministic checks, human labels, and calibrated model-based judges scores versioned outputs. Citations connect claims back to retrievable source spans.
LLM-as-judge for answer quality. The pipeline retrieves broad candidates, reranks them, builds grounded context, generates an answer, and records retrieval and answer metrics such as context precision/recall and faithfulness.
Read these as one system: cross-encoder rerankers: Cohere Rerank/BGE-Reranker establishes the starting contract, two-stage: retrieve 50 → rerank → top 5 changes how that contract is executed or represented, and LLM-as-judge for answer quality exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A concrete design decision: Re-ranking & evaluation
1candidates = hybrid_retrieve(query, limit=50)2ranked = reranker.rank(query=query, documents=[item.text for item in candidates])3context = [candidates[item.index] for item in ranked[:8]]This Re-ranking & evaluation slice makes cross-encoder rerankers: Cohere Rerank/BGE-Reranker observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward LLM-as-judge for answer quality, predict its behavior for empty, invalid, repeated, and large input.
Designs that fail under real load: Re-ranking & evaluation
| Risk | Why it matters |
|---|---|
| cross-encoder rerankers: Cohere Rerank/BGE-Reranker | Re-ranking too many long passages increases latency and cost; re-ranking cannot recover a relevant document that retrieval never returned. |
| two-stage: retrieve 50 → rerank → top 5 | The term evaluation does not mean Redis EVAL; one aggregate score can hide regressions on rare or safety-critical question groups. |
| RAGAS metrics: faithfulness/answer relevancy/context precision/recall | An LLM judge can share the generator's biases; a high fluency score does not prove factual support or correct citation. |
| LLM-as-judge for answer quality | The term evaluation does not mean Redis EVAL; one aggregate score can hide regressions on rare or safety-critical question groups. |
Design review exercise: Re-ranking & evaluation
- Foundation: implement or demonstrate cross-encoder rerankers: Cohere Rerank/BGE-Reranker with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine cross-encoder rerankers: Cohere Rerank/BGE-Reranker with two-stage: retrieve 50 → rerank → top 5. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for LLM-as-judge for answer quality. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
4. Vector store & embedding choices
The Vector store & embedding choices unit begins with pgvector vs Pinecone vs Chroma vs Weaviate: Vector-store choice combines operational ownership, filtering, scale, consistency, cost, and index lifecycle; Matryoshka-trained embeddings can retain useful ranking quality when deliberately truncated to supported dimensions. Benchmark recall and filtered latency with tenant-realistic data and plan blue-green re-embedding when the model changes. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
Requirements, ownership, and trade-offs: Vector store & embedding choices
| Concept | Meaning | Engineering decision |
|---|---|---|
| pgvector vs Pinecone vs Chroma vs Weaviate | Vector-store choice combines operational ownership, filtering, scale, consistency, cost, and index lifecycle; Matryoshka-trained embeddings can retain useful ranking quality when deliberately truncated to supported dimensions. | Benchmark recall and filtered latency with tenant-realistic data and plan blue-green re-embedding when the model changes. |
| Matryoshka representation learning and dimension truncation | Vector-store choice combines operational ownership, filtering, scale, consistency, cost, and index lifecycle; Matryoshka-trained embeddings can retain useful ranking quality when deliberately truncated to supported dimensions. | Benchmark recall and filtered latency with tenant-realistic data and plan blue-green re-embedding when the model changes. |
| metadata filtering and tenant isolation | Vector-store choice combines operational ownership, filtering, scale, consistency, cost, and index lifecycle; Matryoshka-trained embeddings can retain useful ranking quality when deliberately truncated to supported dimensions. | Benchmark recall and filtered latency with tenant-realistic data and plan blue-green re-embedding when the model changes. |
| index build/update/delete and re-embedding cost | Vector-store choice combines operational ownership, filtering, scale, consistency, cost, and index lifecycle; Matryoshka-trained embeddings can retain useful ranking quality when deliberately truncated to supported dimensions. | Benchmark recall and filtered latency with tenant-realistic data and plan blue-green re-embedding when the model changes. |
Critical path and failure behavior: Vector store & embedding choices
pgvector vs Pinecone vs Chroma vs Weaviate. Managed stores own distribution and index operations; pgvector shares PostgreSQL transactions and filters; local stores simplify prototypes. Every embedding belongs to a model/version/dimension namespace.
Matryoshka representation learning and dimension truncation. Managed stores own distribution and index operations; pgvector shares PostgreSQL transactions and filters; local stores simplify prototypes. Every embedding belongs to a model/version/dimension namespace.
metadata filtering and tenant isolation. Managed stores own distribution and index operations; pgvector shares PostgreSQL transactions and filters; local stores simplify prototypes. Every embedding belongs to a model/version/dimension namespace.
index build/update/delete and re-embedding cost. Managed stores own distribution and index operations; pgvector shares PostgreSQL transactions and filters; local stores simplify prototypes. Every embedding belongs to a model/version/dimension namespace.
Read these as one system: pgvector vs Pinecone vs Chroma vs Weaviate establishes the starting contract, Matryoshka representation learning and dimension truncation changes how that contract is executed or represented, and index build/update/delete and re-embedding cost exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A concrete design decision: Vector store & embedding choices
1ORDER BY embedding <=> :query_vector LIMIT 20This Vector store & embedding choices slice makes pgvector vs Pinecone vs Chroma vs Weaviate observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward index build/update/delete and re-embedding cost, predict its behavior for empty, invalid, repeated, and large input.
Designs that fail under real load: Vector store & embedding choices
| Risk | Why it matters |
|---|---|
| pgvector vs Pinecone vs Chroma vs Weaviate | Mixing vector versions or applying tenant filters after retrieval can return incorrect or unauthorized results. |
| Matryoshka representation learning and dimension truncation | Mixing vector versions or applying tenant filters after retrieval can return incorrect or unauthorized results. |
| metadata filtering and tenant isolation | Mixing vector versions or applying tenant filters after retrieval can return incorrect or unauthorized results. |
| index build/update/delete and re-embedding cost | Mixing vector versions or applying tenant filters after retrieval can return incorrect or unauthorized results. |
Design review exercise: Vector store & embedding choices
- Foundation: implement or demonstrate pgvector vs Pinecone vs Chroma vs Weaviate with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine pgvector vs Pinecone vs Chroma vs Weaviate with Matryoshka representation learning and dimension truncation. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for index build/update/delete and re-embedding cost. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
Complete worked example
This example integrates the chapter rather than demonstrating an isolated method.
1WITH semantic AS (2 SELECT id, ROW_NUMBER() OVER (ORDER BY embedding <=> :query) AS rank3 FROM chunks WHERE tenant_id = :tenant_id LIMIT 504), lexical AS (5 SELECT id, ROW_NUMBER() OVER (ORDER BY ts_rank_cd(search_vector, websearch_to_tsquery(:text)) DESC) AS rank6 FROM chunks7 WHERE tenant_id = :tenant_id AND search_vector @@ websearch_to_tsquery(:text)8 LIMIT 509)10SELECT id, SUM(score) AS rrf_score11FROM (12 SELECT id, 1.0 / (60 + rank) AS score FROM semantic13 UNION ALL14 SELECT id, 1.0 / (60 + rank) AS score FROM lexical15) candidates16GROUP BY id ORDER BY rrf_score DESC LIMIT 20;Expected result
1Returns tenant-filtered candidates ranked by reciprocal contributions from semantic and lexical retrieval.Line-by-line reading
| Line | Code | Explanation |
|---|---|---|
| 1 | WITH semantic AS ( | Begins a declarative database or protocol operation; subsequent lines refine its contract. |
| 2 | SELECT id, ROW_NUMBER() OVER (ORDER BY embedding <=> :query) AS rank | Begins a declarative database or protocol operation; subsequent lines refine its contract. |
| 3 | FROM chunks WHERE tenant_id = :tenant_id LIMIT 50 | Adds a relational selection, combination, ordering, bound, or returned-value rule to the statement. |
| 4 | ), lexical AS ( | Implements the next sql statement in the example's data flow. |
| 5 | SELECT id, ROW_NUMBER() OVER (ORDER BY ts_rank_cd(search_vector, websearch_to_tsquery(:text)) DESC) AS rank | Begins a declarative database or protocol operation; subsequent lines refine its contract. |
| 6 | FROM chunks | Adds a relational selection, combination, ordering, bound, or returned-value rule to the statement. |
| 7 | WHERE tenant_id = :tenant_id AND search_vector @@ websearch_to_tsquery(:text) | Adds a relational selection, combination, ordering, bound, or returned-value rule to the statement. |
| 8 | LIMIT 50 | Adds a relational selection, combination, ordering, bound, or returned-value rule to the statement. |
| 9 | ) | Implements the next sql statement in the example's data flow. |
| 10 | SELECT id, SUM(score) AS rrf_score | Begins a declarative database or protocol operation; subsequent lines refine its contract. |
| 11 | FROM ( | Adds a relational selection, combination, ordering, bound, or returned-value rule to the statement. |
| 12 | SELECT id, 1.0 / (60 + rank) AS score FROM semantic | Begins a declarative database or protocol operation; subsequent lines refine its contract. |
| 13 | UNION ALL | Implements the next sql statement in the example's data flow. |
| 14 | SELECT id, 1.0 / (60 + rank) AS score FROM lexical | Begins a declarative database or protocol operation; subsequent lines refine its contract. |
| 15 | ) candidates | Implements the next sql statement in the example's data flow. |
| 16 | GROUP BY id ORDER BY rrf_score DESC LIMIT 20; | Adds a relational selection, combination, ordering, bound, or returned-value rule to the statement. |
Step-by-step execution
- Deterministic code validates the request, identity, tenant, budgets, schemas, and permitted tools before assembling model context.
- Retrieval or memory selection chooses bounded, provenance-bearing evidence; tokenization converts the assembled messages into the model's input sequence.
- The provider generates or streams tokens, or proposes typed tool arguments; application code validates every output and executes only authorized bounded actions.
- Parsers and business rules accept, repair once under policy, route, or reject the result; citations and state transitions are persisted with model, prompt, index, and dataset versions.
- Offline evaluation and production telemetry measure retrieval, faithfulness, latency, token cost, tool errors, safety outcomes, and regressions by cohort.
Common mistakes and professional corrections
| Area | Common failure | Better engineering choice |
|---|---|---|
| Chunking & embedding strategies | Choosing chunk size by intuition alone can improve one demonstration while reducing retrieval recall across the evaluation set. | Begin with a measurable recursive baseline, preserve section metadata, and tune size/overlap on real questions. |
| Hybrid search (BM25 + semantic) | Applying inconsistent analyzers to indexed text and queries or using stop-word rules blindly can remove the only discriminating evidence. | Keep lexical search for names, codes, quotations, rare terminology, and exact legal language that embeddings may blur. |
| Re-ranking & evaluation | Re-ranking too many long passages increases latency and cost; re-ranking cannot recover a relevant document that retrieval never returned. | Retrieve broadly and re-rank a bounded set when answer quality depends on the best few passages. |
| Vector store & embedding choices | Mixing vector versions or applying tenant filters after retrieval can return incorrect or unauthorized results. | Benchmark recall and filtered latency with tenant-realistic data and plan blue-green re-embedding when the model changes. |
Interview and review notes
- Define the central abstraction without naming a library function.
- Trace one request, call, query, message, render, or state transition from input to observable result.
- Compare two alternatives from this chapter by guarantee, cost, and failure behavior.
- Explain the most likely production bug and the test or metric that reveals it.
- State what remains authoritative after process loss, retry, reconnect, or deployment.
Practice set
Easy
- Define every bold term in the concept tables in one precise sentence.
- Reproduce the focused examples and annotate the value or state after each important line.
- Explain the chapter progression diagram aloud in two minutes.
Medium
- Replace one convenient default with an explicit policy for validation, timeout, ordering, pagination, cleanup, or error handling.
- Write a negative test for each topic group.
- Compare the measured behavior before and after one justified change.
Hard
- Combine all topic groups into one thin vertical slice.
- Inject a realistic failure at the most important external boundary and prove recovery.
- Write a one-page design note covering ownership, trade-offs, security, observability, and rollback.
Chapter submission
Submit:
- source code or reproducible commands;
- automated tests plus one deliberately failing-before-fix test;
- captured output, query plan, trace, screenshot, or metric;
- a 300–500 word explanation of the execution flow and one rejected alternative;
- a short README with setup, versions, limitations, and cleanup steps.
- Continue with the Legal Document Q&A (RAG) project workshop.
Self-review rubric
| Dimension | Beginning | Competent | Professional |
|---|---|---|---|
| Explanation | Names APIs | Explains behavior | Connects guarantees, internals, and trade-offs |
| Implementation | Happy path only | Validated and tested | Clear ownership, failure recovery, and cleanup |
| Evidence | Manual claim | Repeatable output | Tests plus meaningful measurement or inspection |
| Communication | Steps missing | Reproducible README | Decisions, limits, and alternatives are explicit |
Roadmap coverage checklist
- To do: Chunking & embedding strategies: fixed-size vs semantic vs recursive chunking
- To do: Chunking & embedding strategies: document-specific: markdown headers/HTML/code
- To do: Chunking & embedding strategies: OpenAI text-embedding-3-small/large dimensions+cost
- To do: Chunking & embedding strategies: BGE-M3 and E5-large open source alternatives
- To do: Chunking & embedding strategies: batching embeddings efficiently
- To do: Hybrid search (BM25 + semantic): BM25 keyword search (TF-IDF)
- To do: Hybrid search (BM25 + semantic): Reciprocal Rank Fusion (RRF) for score merging
- To do: Hybrid search (BM25 + semantic): weighted hybrid: α×semantic + (1-α)×BM25
- To do: Hybrid search (BM25 + semantic): PostgreSQL ts_vector + pgvector combined
- To do: Re-ranking & evaluation: cross-encoder rerankers: Cohere Rerank/BGE-Reranker
- To do: Re-ranking & evaluation: two-stage: retrieve 50 → rerank → top 5
- To do: Re-ranking & evaluation: RAGAS metrics: faithfulness/answer relevancy/context precision/recall
- To do: Re-ranking & evaluation: LLM-as-judge for answer quality
- To do: Vector store & embedding choices: pgvector vs Pinecone vs Chroma vs Weaviate
- To do: Vector store & embedding choices: Matryoshka representation learning and dimension truncation
- To do: Vector store & embedding choices: metadata filtering and tenant isolation
- To do: Vector store & embedding choices: index build/update/delete and re-embedding cost
Quick revision
- Chunking & embedding strategies: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Hybrid search (BM25 + semantic): connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Re-ranking & evaluation: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Vector store & embedding choices: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Re-read the worked-example execution trace instead of memorizing isolated syntax.
- If you cannot name the owner of state and cleanup, the design is not yet complete.
Mastery check
How well can you recall this?
Finished this lesson?