Front Matter
- Preface
- How to Read This Book
- Read This First: RAG Vocabulary at a Glance
- About the Author
Part I — Foundations
- Choosing RAG for the Right Problem
- What Production-Grade Means in This Book
- What an LLM Is, and Why Parametric Memory Hallucinates
- Five Building Blocks: LLMs, Retrieval, RAG, Agents, and Workflows
- The Honest Comparison: RAG, Long Context, Fine-Tuning, and Direct Tools
- Cost Is a Calculation, Not a Ratio
- When Not to Use RAG
- The Evolution Arc: From the 2020 Paper to Graphs and Agents
- MCP, RAG, and Agent Skills: Three Different Boundaries
- Two Phases and One Evidence Trail
- Your First RAG in Ten Minutes
- What Counts as a Successful First Run
- The .NET Toolkit and Reproducible Environments
- The cohort this book is built on
- The two abstractions the code is built on
- Ollama: use OllamaSharp, not Microsoft.Extensions.AI.Ollama
- AddSmartDocsCore unpacked
- Resilience has to reach the transport
- Configuration: appsettings.json and user-secrets
- Migrating from Semantic Kernel to MAF
- TokenCounter, the utility you'll use everywhere
- The companion solution layout
- A reproducible environment
- The package map: what to add, and when
- Local development: native services, not cloud-by-default
- Your First Measured RAG Baseline
- What a baseline is, and what it isn't
- Pin the gold set before you look at an answer
- Run the composition you mean to measure
- One record per case, failures included
- Four outcomes, not one score
- Measure retrieval at one consistent unit
- Run the first measured baseline
- Compare runs case by case
- Replacing the stand-ins with real models
- A passing gate is not a good system
Part II — The RAG Pipeline
- Embeddings and Retrieval Benchmarks
- What an embedding actually is
- Token limits and silent truncation
- Cosine, dot product, Euclidean: which one to use
- Asymmetric embeddings: query vs document
- The 2026 embedding leaderboard
- Domain adaptation: when default embeddings aren't enough
- The EmbeddingService domain port
- Batching and rate-limit handling
- Multilingual: one model or query translation
- Matryoshka representations and dimension trimming
- Benchmarking embeddings on your own corpus
- Document Contracts and Reliable Ingestion
- Where the naive re-ingest path breaks
- Name the identities before naming the tables
- Primary evidence and derived representations
- The registry: one record per document
- Prepare, validate, publish, collect
- Running the lifecycle end to end
- Making the registry durable
- Events that arrive late, twice, or not at all
- Deletion is its own operation
- One lifecycle, two scopes
- Freshness is a measurable promise
- Testing the contract
- Chunking and Contextual Retrieval
- Why chunking is the highest-leverage tuning knob
- The four classic strategies
- The chunk-size question
- Characters versus tokens: sizing chunks the model's way
- Where every classic strategy breaks: the context problem
- Anthropic's Contextual Retrieval
- The numbers Anthropic reported
- Measuring the ladder on SmartDocs
- The cost question, and prompt caching
- When the document is code: Roslyn-aware chunking
- Wiring chunking into the SmartDocs pipeline
- When contextual retrieval isn't worth it
- A cheaper cousin: Late Chunking
- The ChunkingPlayground sample
- Multimodal Evidence from Documents
- What multimodal embedding models do
- Three architectural patterns
- One space, one dimension: the constraint everyone forgets
- PDF processing: the silent killer
- A visual answer needs a visual locator
- Tables: the in-between case
- Wiring multimodal into SmartDocs
- Grounding an answer in the image itself
- Test missing and contradictory modalities
- When pure text wins
- Vector Indexes and Storage Decisions
- What HNSW actually does
- Tuning HNSW: the three knobs that move recall
- How much RAM will this need?
- The .NET landscape in late 2026
- IVectorStore: the abstraction SmartDocs actually uses
- Storage keys, and why upsert is idempotent
- Payload co-location: keep the text next to the vector
- Creating a collection: the pitfalls
- Filtering: where the predicate runs
- One contract, three stores: adapter conformance tests
- Quantization: the memory lever
- The index format is part of the contract
- Measuring it: recall@k and latency percentiles
- The comparison sample
- Hybrid stores (forward reference)
- Choosing the right backend
- Indexing Representations and Parent Evidence
- Strategy 1: full-chunk indexing (the default)
- Strategy 2: summary indexing
- Strategy 3: sub-chunk (small-to-big) indexing
- Strategy 4: hypothetical-question (query) indexing
- One identity per representation
- Resolving hits to parent evidence
- What the strategies actually score
- Choosing per use case
- The cost surface
- Wiring into SmartDocs
- Keeping the index fresh: updates, deletes, and re-embedding
- Dense, Lexical, and Hybrid Retrieval
- Dense retrieval (vector search)
- Lexical retrieval (BM25 and friends)
- Hybrid retrieval: dense and lexical together
- Reciprocal Rank Fusion: the math
- Measuring hybrid on the SmartDocs gold set
- Tuning hybrid: the constant, weights, and oversampling
- Fusion inside the store
- Late interaction (briefly)
- Choosing K
- Diversity: trimming redundant results
- Score thresholding and abstention
- The retriever contract
- Wiring into SmartDocs
- Reranking and Evidence Selection
- What a cross-encoder does differently
- Choosing a reranker
- The IReranker interface
- The headline numbers, and the measurement trap
- LLM-as-reranker
- A self-hosted cross-encoder (ONNX BGE)
- Latency budget for rerank
- When NOT to rerank
- Thresholding after rerank
- Authorize the candidate pool before an external reranker
- Wiring into the SmartDocs pipeline
- Context Assembly, Citations, and Streaming
- Context engineering: a budget for every token
- The pipeline shape
- The augmentation step
- Generation: streaming with IChatClient
- Sources in context versus sources cited
- The API endpoint: SSE
- Error handling and partial responses
- The Blazor consumer
- The same context through an agent
- Cost of a query: the prompt budget
- Putting it together: the trace of one query
Part III — Access and Query Intelligence
- Authorization Across the RAG Pipeline
- Where evidence crosses a boundary
- Scope comes from the authenticated request
- One guard, one rule
- Boundary one: the vector store exit
- Boundary two: before text leaves the process
- Boundary three: caches
- Boundary four: replayed answers and citations
- Revocation is a normal path, with a number
- Watching every boundary in one run
- Tools, agents, graphs and sessions
- Testing the composed path
- Metadata Filters and Query Construction
- The two filtering positions
- Designing the metadata schema
- Filter expressions: MetadataFilter
- The tenant contract
- Query construction: from natural language to filter
- The filter-then-search pipeline
- Self-Query: a special case worth knowing
- When the filter is too tight: relaxation
- Operators beyond equality
- Validating extracted values against the vocabulary
- Security filters are auth-derived, never extracted
- A few more filtering concerns
- When NOT to construct queries
- Filter caching
- Wiring into SmartDocs
- Routing and Conversational Retrieval
- Why route at all
- The IQueryRouter interface
- Three routing strategies, plus a cascade
- The cheap-to-expensive cascade
- Confidence, fallback, and the refuse path
- Structured-output robustness
- Conversational queries: the rewrite problem
- Query rewriting with ConversationalQueryRewriter
- When the rewrite should be a question
- Managing conversation history beyond a magic number
- A rewrite inherits subjects, never permissions
- Wiring it all together
- Fan-out and fusion: when a query hits more than one silo
- The router and rewriter are an injection surface
- Cost economics of routing and rewriting
- Routing telemetry: cost and errors per route
Part IV — Graph and Hybrid Storage
- Graph Data and Entity Resolution
- What a graph database stores that a vector store doesn't
- Neo4j with Neo4j.Driver 6.5.1
- Building the entity graph at ingest time
- Entity resolution: from extracted names to one node
- Provenance: every node remembers where it came from
- Cypher in 60 seconds
- The graph retriever interface
- Bounded traversal under an authorization scope
- Route to one, or run both and fuse
- Vector + graph: GraphRAG (forward reference)
- When NOT to reach for a graph
- Wiring into SmartDocs
- Testing graph code without a live Neo4j
- Hybrid Backends in Practice
- The single-store options in late 2026
- Postgres + pgvector + tsvector: the practical default
- Qdrant native hybrid
- Azure AI Search: hosted hybrid and the semantic ranker
- A recipe for SQL Server and Azure SQL
- The Microsoft Agent Framework pattern over Azure AI Search
- Choosing among the three
- One base filter, three dialects
- Keeping three engines honest: the conformance cases
- When two stores still win
- Wiring into SmartDocs
Part V — RAG Design Patterns
- Measured RAG Enhancements
- Measure before you enhance
- HyDE: Hypothetical Document Embeddings
- RAPTOR: Recursive Abstractive Processing for Tree-Organized Retrieval
- RAG-Fusion: query expansion with RRF
- Step-back prompting: retrieve the principles first
- Self-RAG: when to retrieve at all
- CRAG: Corrective RAG
- Lost in the middle: ordering chunks in the prompt
- Contextual compression: trimming chunks before generation
- Chunk pre-injection: loading context before the first turn
- Composing patterns
- What we're not covering
- Wiring into SmartDocs
- Structural and Vectorless Retrieval
- The kind of corpus this works on
- Building the structural index
- Retrieval over the structural index
- Getting from a question to an identifier
- When structural beats vector cleanly
- Folding structural into your stack
- Authorizing the structural leg
- Lexical retrieval: the other embedding-free pillar
- Choosing a vectorless retriever
- Normalizing the identifier before you look it up
- Identity across versions, documents and parsers
- From retrieved nodes to a cited answer
- Things that bite at scale
- Measuring it: the VectorlessRetrieval sample
- GraphRAG and Deferred Graph Retrieval
- The global-question problem
- GraphRAG: the eager indexing pipeline
- GraphRAG by the numbers
- When graphs actually help
- The three query methods
- LazyGraphRAG: the cost-shifting trick
- The cost picture
- When to choose eager
- One graph, two modes
- Implementation in SmartDocs
- What GraphRAG can't do
- MCP Contracts and Secure Boundaries
- What MCP actually is
- The two standard transports
- The .NET MCP SDK
- Authorization at the boundary: one context, one guard
- When the server needs something from the caller: multi-round-trip requests
- The client side: calling MCP tools from a MAF agent
- Notifications and subscriptions
- The MCP-vs-A2A-vs-OpenAPI decision tree
- Security: the part the spec leaves to you
- Tool granularity: the design decision that decides UX
- Composing MCP servers
- Observability and deployment
- Testing MCP servers
- The two SmartDocs servers
- Bounded Agents, Workflows, and Memory
- From single-agent RAG to multi-agent workflows
- Bounding the run: budgets the code enforces
- The Workflow graph: conditional and parallel edges
- Agentic memory: semantic, episodic, procedural
- Agent Skills: procedural memory you can version
- CodeAct (a.k.a. Code Mode): one generated program instead of N tool calls
- From demo to production: the concerns the prototype skips
- Tool design for agents (vs APIs for humans)
- Putting it together: the SmartDocs production agent
- The MultiAgentOrchestration sample
Part VI — Production Concerns
- Evaluation and Release Decisions
- Why eval is the unsexy multiplier
- The five metrics that matter
- Grade the answer you shipped, not the answer you wrote
- The .NET-native eval library: Microsoft.Extensions.AI.Evaluation
- RAGAS and DeepEval: when to leave .NET
- LLM-as-judge: how it actually works (and where it fails)
- Building the seed dataset
- The release gate
- Controlled baseline promotion
- A regression gate is not a quality bar
- Latency and cost as eval metrics
- Ground-truth evaluation, the framework-native way (Agent Framework 1.28.0)
- The eval-driven development loop
- Evaluating for safety, not just quality
- Online versus offline evaluation
- What the eval can't tell you
- Latency, Cost, Caching, and Backpressure
- A cost model you can recompute
- The cache stack
- The other half of cost: send fewer tokens
- The latency budget per pipeline stage
- .NET-specific performance levers
- Resilience: one retry layer
- Backpressure: refusing work early and honestly
- Provisioned throughput and spillover
- Observability: traces, metrics, cost
- Avoid the premature optimizations
- Freshness, Generations, and Model Migration
- Freshness as a first-class metric
- Three ingest strategies
- Orphan chunks and re-chunking on update
- Index generations: publishing a whole index
- Embedding drift: the silent killer
- The Drift-Adapter pattern
- Cache invalidation under document churn
- GDPR Article 17 and the right to erasure
- Schema migrations
- Backfill scheduling
- Security Testing and Incident Response
- The threat model
- Layer 1: input layer
- Layer 2: embedding layer
- Layer 3: retrieval layer
- Layer 4: output layer
- Audit logs
- Secret scanning at ingest
- Supply-chain security
- MCP-server trust hierarchy
- Keyless authentication and infrastructure
- Agentic-action security: least privilege and human approval
- Testing the security boundaries
- Incident response
- Governance and Evidence of Compliance
- Start with intended use and owners
- Impact assessments before deployment: DPIA and FRIA
- Provider vs deployer: who owes what
- The shape of the EU AI Act obligations
- Conformity assessment, CE marking, and EU-database registration
- The data-flow inventory
- Citations as traceability evidence
- Audit logs as action evidence
- Consent and transparency
- Lawful basis is not consent
- Data residency, sovereignty, and cross-border transfers
- Faithfulness as a contractual quality bar
- Bias, fairness, and non-discrimination
- Model cards and technical documentation
- Annex IV technical documentation is not the model card
- Human oversight
- Post-market monitoring and serious incidents
- Right to explanation
- Copyright, corpus licensing, and output IP
- The compliance dashboard
- The right to erasure meets the embedding
- The TrustByDesign sample, end to end
- Production Failure Labs
- Evidence before edits
- How the labs are built
- Lab 1: the small tenant that gets nothing
- Lab 2: the new generation nobody reads
- Lab 3: tenant B reads tenant A's cached answer
- Lab 4: deleted, but still answering
- Lab 5: it compiles, then it fails
- Turning a test red
- Three incidents without a lab
- Writing the incident record
Part VII — Capstone Project
- The Reproducible Production Capstone
- Start from a named composition
- The reference topology
- Bicep: the resource graph as code
- A pipeline that fails for the right reason
- NuGet packaging for the public surface
- Secret management
- Smoke tests after deploy
- Production hardening
- Day-2 operations
- The pre-flight checklist
- The release dossier
- Known limits of the reference deployment
- Capacity planning
- The day after launch
- An alternative shape: vertical slices
- Where this book ends and your work begins
- Closing
Appendices
- Appendix A — Solutions
- Appendix B — Design Patterns
- Appendix C — Backend Comparison Workbook
- Appendix D — Embedding Experiment Protocol
- Appendix E — Python to .NET Rosetta
- Appendix F — Companion Repository Guide
- Appendix G — Debugging Checklist
- Appendix H — Prompt Engineering Patterns
- Appendix I — The Math Behind RAG
- References and Further Reading
- Other Books You’ll Enjoy
- Index
