RAG pipeline and citation IDs
What retrieval adds to generation
Retrieval-augmented generation (RAG) retrieves evidence at request time and supplies it to a generative model alongside the question. Unlike changing model weights through training, updating an authorized index can change the evidence available for later answers. A support bot can use a current handbook rather than relying on model memory. RAG does not guarantee truth: documents can be stale, irrelevant, incomplete or incorrect, and a model can misread correct evidence. This chapter uses a fictional handbook with three versioned passages, no personal data, and a local lexical baseline. The example returns H2-r1 for a query about receipt requirements and an empty list for a refund deadline, which the corpus never specifies. An empty result is a signal to abstain or improve search, not proof that no answer exists anywhere.
import re
def retrieve(query, passages, k): # Already authorized, current passages with unique string IDs. if type(k) is not int or k < 1: raise ValueError("positive k required") def terms(text): return set(re.findall(r"[a-z0-9]+", text.lower())) q = terms(query) scores = [(len(q & terms(text)), key) for key, text in passages] return [key for score, key in sorted(scores, key=lambda x: (-x[0], x[1]))[:k] if score > 0]
handbook = [("H1-r1", "Support hours: 09:00 to 17:00."), ("H2-r1", "Returns require a receipt."), ("H3-r1", "Shipping takes five days.")]print(retrieve("returns receipt", handbook, 2))print(retrieve("refund deadline", handbook, 2))Ingest, parse, chunk and index
Ingestion starts by authorizing the source, recording its provenance, revision and access policy, and checking data quality. Parsing extracts content and preserves structure such as headings, lists and page numbers. Chunking divides the text into passages that preserve enough context to be useful; too short can detach a condition from a rule, too long can bury evidence or consume context. Overlap can retain a sentence crossing a boundary but creates duplicate hits. Assign each chunk a stable version-qualified ID, such as H2-r1, with source document and location metadata. Index text for keyword search and, where useful, embeddings for semantic retrieval. Store embedding model revision and dimension, and use matching query encoding (see previous chapters). The toy input is already parsed and chunked, and the ASCII token-set scorer ignores term frequency and synonyms. It is not a multilingual tokenizer or a vector database.
Retrieve and assemble within a budget
Filter by the authenticated tenant, permissions and current document revision before ranking. Recheck candidate IDs against the authoritative current state before materializing passages. Do not send unauthorized content to a model even if the answer will be filtered afterward. Rank the eligible chunks, deduplicate results, and allocate a context budget after reserving capacity for system instructions, question, history and output. This function consumes an already authorized mapping. It scans ranked IDs, skips duplicates and missing IDs, and admits whole passages that fit, even if a higher-ranked one was too large. A passage ID counts as one whitespace-separated unit in this fixture. Real systems need the actual tokenizer and all formatting overhead; word counts are not token counts. The printed result fits the five-unit budget exactly. Skipping may remove essential evidence, so evaluate after context assembly as well as retrieval.
def assemble(ranked, passages, budget): # Simplified word units; charge the ID as well as passage text. if type(budget) is not int or budget < 0: raise ValueError("nonnegative budget required") selected, seen = [], set() for key in ranked: if key in seen or key not in passages: continue seen.add(key) text = passages[key] cost = len((key + " " + text).split()) if cost <= budget: selected.append((key, text)) budget -= cost return selected
print(assemble(["H2-r1", "H3-r1", "H2-r1"], {"H2-r1": "Returns require a receipt.", "H3-r1": "Shipping takes five days."}, 5))Generate, cite and evaluate
The generator receives the question and selected evidence, not the entire index. Define an answer contract: use only the selected evidence, associate each material claim with a passage ID and report insufficient evidence rather than guess. Preserve a server-side mapping from citation IDs to document revision and location. Validate citation IDs against the actual supplied context and check whether each claim is supported, not just whether the ID exists. Retrieved prose is data, never a new system instruction or tool permission. Delimiters can help separate fields but do not solve prompt injection; use least privilege, restricted tools, reviewed ingestion and output checks. A RAG system can be useful without any tool execution. Evaluate retrieval with relevance labels independently from answer support, answer completeness and correct abstention. A high retrieval score cannot certify generation quality.
Practice: trace a missing fact
Write a query for shipping duration, then trace its IDs through retrieval and assembly with budgets 0, 4 and 5. At five units H3-r1 fits; at four it does not. Add a superseded H3-r0 only to a separate stale-candidate test, and ensure the authoritative mapping excludes it. Try a synonym such as delivery duration and explain why the lexical scorer may miss a relevant passage. Add a harmless instruction-like string to a separate passage; do not execute it or reinterpret it as permission. Record query, eligible candidate IDs, selected IDs, document revisions and whether an answer can be supported, avoiding sensitive text in real logs. Microsoft RAG and OWASP references are listed in source-evidence.json. The next lesson tests grounding and abstention with manually annotated facts.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
RAG pipeline and citation IDs quiz
Apply RAG evidence and grounding contracts.
What distinguishes RAG from model fine-tuning?
Why retain a version-qualified chunk ID?
Which content may enter model context?
What happens if a required passage exceeds the context budget?
What authority does an instruction inside retrieved text have?