When I need an answer backed by the exact paper and passage
A literature assistant that answers from your shelf — and shows its sources — instead of inventing plausible-sounding references.
Make AI answer from your own files — with citations
Retrieval-Augmented Generation (RAG): instead of relying on the model's memory, give it your own documents to answer from. Taught as a weak → strong pipeline — chunk & embed, retrieve & rank (hybrid search + reranking), then ground every answer in sources with citations and measure retrieval quality. With a vector-store cheat sheet, persona examples, and primary-sourced FAQs and videos.
In this chapter you will learn how to build AI assistants that answer questions strictly from your own documents, always providing verifiable citations. You will be able to create chatbots for literature review, customer support, policy guidance, financial reporting, and internal procedures that retrieve exact passages, verify sources, and flag missing evidence, while measuring and reducing hallucinations.
It’s a pipeline that feeds the model your own documents—by chunking, embedding, retrieving, ranking, and then grounding each answer in those sources with citations.
You split files into chunks, embed them, run a hybrid search to retrieve candidates, and optionally rerank them for higher relevance before using them to answer.
Citations let you verify that each response is directly supported by the retrieved documents, letting you measure retrieval quality and maintain trust in the output.
Turn documents into findable pieces
Split every 1,000 characters, cutting sentences and tables mid-thought.
Split on the document's own structure — headings, paragraphs, sections — and let chunks overlap by ~10–20% so a thought is never orphaned across a boundary.
Use one chunk size for both retrieval and the answer — big enough to answer means imprecise search; small enough to search means too little context.
Embed small, precise chunks (~100–400 tokens) for retrieval, but when one hits, return its parent section so the model has enough context to actually answer.
Embed each chunk in isolation: "it grew 3% this quarter" — what grew? which quarter? which company?
Before indexing, prepend a short LLM-written explanation that situates the chunk in its document (e.g. "This is from Acme's Q2 2026 report; revenue grew 3% vs Q1"), then embed that.
Find the few chunks that matter
Paste all your documents into the prompt every time and let the model sift.
Embed every chunk once into a vector store, then at query time embed the question and retrieve only the top-k most similar chunks.
Use semantic (vector) search only — it misses exact codes, IDs, error strings, and product names that share no "meaning" with the query.
Run vector search and keyword search (BM25) together, then fuse the two rankings into one list.
Feed the top-k straight from the vector store into the model and hope the order is right.
Over-retrieve a wide candidate set (top 20–100), pass it through a reranker (a cross-encoder that scores each chunk against the query), and keep only the best 5–10 for the prompt.
Place the most relevant chunk in the middle of a long list of retrieved passages.
Keep the retrieved list short, and place the strongest chunks at the very start and very end of it.
Answer from sources, then prove it
Prompt "answer the question" over the retrieved text and trust whatever comes back.
Instruct the model to answer ONLY from the provided sources, cite the specific chunk for each claim, and say "not in the sources" when the answer isn't there.
Eyeball a few final answers and decide the system "seems fine".
On a labelled query set, score context precision (were the retrieved chunks relevant, and ranked high?) and context recall (did you retrieve everything needed to answer?).
Assume any answer that includes citations is actually grounded in them.
Compute faithfulness = (claims supported by the retrieved context) / (total claims), using an LLM judge to check each claim against the sources.
Conclude "it's wrong, let's use a bigger model" whenever an answer is bad.
Triage the stage: a stale index, bad chunking, a retrieval miss (low precision/recall), lost-in-the-middle ordering, or ungrounded generation (low faithfulness) — and fix the stage that actually failed.
Adobe Acrobat’s online AI‑powered PDF chat tool that lets you ask questions about uploaded documents.
You will be able to upload a PDF, ask a question, and receive an answer with numbered source links that highlight the original text.
A vector store that holds overlapping sections from your PDF documents.
Create an indexed vector store where each chunk is linked to its source file and heading
A retrieval‑augmented generation pipeline that selects the most relevant chunks before prompting the model.
Produce a response that either cites the relevant PDF passages or clearly states that no answer is found in the documents
Azure OpenAI On Your Data, a service that chunks, embeds, and indexes uploaded files for retrieval‑augmented generation.
You will upload a PDF to Azure’s portal, let it be indexed, and retrieve relevant text using a natural‑language prompt.
A side‑by‑side evaluation of how two platforms surface source citations for the same document.
You will identify differences in citation style, clickability, and traceability between Adobe’s numbered links and Azure’s chunk references.
An evaluation routine that compares each claim in an answer against the retrieved source chunks.
Produce a report that quantifies how many statements are backed by retrieved evidence
A short markdown document that evaluates answer faithfulness by checking each cited passage against the source.
You will produce a report that lists every citation, shows the extracted source text, and marks whether the AI’s claim is fully supported.
quality_report.md.34 outcomes in all — one per recipe below.
When I need an answer backed by the exact paper and passage
A literature assistant that answers from your shelf — and shows its sources — instead of inventing plausible-sounding references.
A measured hallucination rate for your research bot, so you fix grounding before a colleague trusts a made-up finding.
Every candidate annotation arrives with the marker list and the source behind it, so you argue with the evidence instead of with a model’s recollection of what CD14 means.
Need a summary with every sentence backed by a source
A summary where every line is traceable to a real source — no confident sentences floating free of the evidence.
Need an investor update with only real numbers
Draft updates where every figure is pulled from your real numbers — no rounded-up guesses sneaking into investor comms.
Need exact policy answers
Staff get correct, citable answers about leave, expenses and conduct without pinging you — and the bot won't invent a policy.
Citations point to unseen sources
Citations you can trust, because every one is verified against what was actually retrieved.
Consistent, citable policy answers for the team — with honest gaps instead of confident improvisation.
Employees ask about benefits
Employees get fast, correct, sourced answers about benefits and policy without an HR ticket each time.
New hire asks onboarding questions
New starters get reliable, sourced onboarding answers and a clear "ask a human" signal for the gaps.
Need exact answers for diligence
You can interrogate hundreds of documents in natural language and trace every answer back to its exact source before it goes into your IC memo.
A fast, citable starting point for a guideline or formulary lookup — every answer traces to the primary source, which the clinician checks before it informs a decision. Not a diagnostic tool.
Customers want source for every reply
A support chatbot customers (and you) can trust, because every answer points back to a real article.
Repetitive support tickets need answers
A self-serve bot that resolves the easy, repeated questions correctly and with a source — freeing agents for the hard ones.
Getting lots of noisy support articles
Sharper answers from the same knowledge base, because the model only sees the chunks that actually matter.
You avoid building a RAG pipeline you don't need yet — and know exactly when you will.
Fast, sourced answers about your own contracts — without scrolling 40-page PDFs or guessing at terms.
Bot can’t find obvious info in docs
Retrieval that actually surfaces the right passage, fixed at the chunking stage rather than by swapping models.
Need exact steps from our runbooks
Tribal knowledge becomes a searchable assistant that answers from the actual SOP, not from someone's memory.
When SOPs change, answers stay outdated
Answers always reflect the current document, not last quarter's — no silent drift as procedures change.
HR bot blends unrelated policies into replies
Cleaner context means clearer answers; you stop the bot from blending three unrelated policies into one wrong reply.
Want all change‑of‑control, assignment, termination and drag‑along clauses with sources
A structured clause matrix in minutes instead of days of manual review, with every entry traceable to the original contract page.
Can’t find the right SOP step
Fast, sourced answers to routine protocol questions, freeing staff from hunting through binders — with every answer traceable to the actual SOP, not a memory of it.
You see which topics the retriever silently misses, instead of blaming the model for answers it never had the context to give.
Sourced answers about specific numbers in long filings — with the exact table cited, not a paraphrase.
Need variance commentary that only uses figures
Variance notes where each figure traces to the actual report — no transcription errors or invented deltas.
Hard to spot emerging themes across holdings
A searchable view across your whole portfolio so emerging themes surface before they become surprises, with every signal traced to its source report.
Defensible salary ranges backed by your own data, not a number the model guessed from training — every figure cites the comparable placements it came from.
Reps need quick, on‑message answers from product docs
Reps get fast, on-message answers grounded in approved collateral — not a hallucinated feature claim in front of a prospect.
Need an RFP fast but only using vetted answers
Faster RFPs assembled from vetted answers, with a citation trail back to the approved source for each one.
Need accurate account briefing without guesswork
Reps walk into calls briefed from real account history, with each fact traceable to a note — no made-up context about the customer.
Finding exact‑match candidates in a massive CV pool
You surface relevant candidates in seconds from a corpus too large to browse manually, with each suggestion backed by the actual profile text.
Need a draft candidate shortlist that matches my job description
A ranked draft shortlist grounded in actual profile text, ready for the recruiter to review and refine — not a black-box score.
Want to lift bits from my old posts
New drafts that sound like you and reuse your real prior facts, with each borrowed point traceable to the original post.
When a text chunk loses its document context
A chunk ripped out of its document loses what it was about. Tell each chunk what it is before you index it. Anthropic measured that this "contextual embeddings" step cuts the rate of top-20 retrieval failures by 35% — a large gain from a cheap preprocessing pass, because each chunk now carries the context that makes it findable.
Precise search gives tiny hit but no context
The best size for finding a passage is not the best size for answering from it. Decouple them. Small chunks make retrieval precise (the matching passage stands out); returning the parent section gives the model the surrounding context it needs to write a grounded answer. You get precise retrieval AND enough context.
Document splits cut sentences in half
How you split a document decides what can ever be retrieved. Slice on its natural boundaries, not an arbitrary character budget that cuts mid-thought. Bad chunking dooms retrieval no matter how good the embeddings are: if the answer is split across two chunks, neither one looks relevant. Splitting on structure with ~10–20% overlap keeps each chunk a coherent, self-contained unit.
Can't tell if answers are made up
An answer is only trustworthy if you can trace each claim to a source. Make the model cite — and make a missing citation visible. When every claim must carry a citation, a missing or wrong one becomes a visible failure you can catch — instead of a silent hallucination that reads just as confidently as a grounded answer.
RAG breaks in specific, nameable places. Triage which stage failed instead of reaching for a bigger model. RAG failures are stage-specific, and naming the stage tells you what to fix. A bigger model does nothing for a stale index or a retrieval miss; the cure for each failure mode is different.
Answers look cited but still make up facts
A cited-looking answer can still invent claims the sources never made. Check, claim by claim, that the answer is supported. Faithfulness (a standard Ragas metric) catches the confident claims the retrieved sources never actually supported — the hallucinations that slip past a glance at the citations. (The Evals chapter teaches the general judge-validation loop this builds on.)
Can't see why answers are wrong
If the right chunk never got retrieved, no amount of prompt-tuning saves the answer. Score the retriever directly. The answer cannot be right if retrieval failed — so you measure the retriever on its own. Low precision means noisy context; low recall means the evidence never arrived. Either one caps how good the answer can be.
IDs or error codes get missed by meaning‑only search
Semantic search understands meaning but fumbles exact tokens. Run both kinds of search and fuse them. Dense (vector) retrieval catches meaning; sparse (keyword/BM25) retrieval catches exact tokens like SKUs and error codes. Anthropic's contextual embeddings + contextual BM25 together cut top-20 retrieval failures by 49% — further than embeddings alone.
Key evidence gets stuck in the middle of a long list
Where a chunk sits in the prompt changes how well the model uses it. Put your best evidence where the model looks hardest. Liu et al. ("Lost in the Middle", arXiv 2307.03172) showed models attend best to the beginning and end of their context and degrade when key information sits in the middle — true even for long-context models. A short list, best chunks at the edges, sidesteps the dip.
A fast first pass gets you a rough shortlist; a slower, sharper model picks the real winners from it. Anthropic measured that adding a reranking step cut retrieval failures by 67% — their best result. Over-retrieve cheaply, then let an accurate reranker pick the handful that actually go to the model.
Dumping the whole corpus into the prompt
The point of RAG is to bring only the relevant passages into the window — not to dump the whole corpus and hope. Retrieving the top-k most similar passages means only the relevant material reaches the context window — cheaper, faster, and less distracting for the model than a corpus dump that buries the answer in noise.
The same set on /recipes, filtered by tool and role.
A clear, vendor-neutral explainer of what RAG is and why it grounds answers in your own data. Start here for the mental model.
A hands-on, code-along build of a full RAG pipeline in Python, taught by a LangChain engineer — chunking, embedding, retrieval, generation.
Building a reliable, fully local RAG agent — routing, grading retrieved docs, and checking groundedness — the evaluation-minded end of the lab.
RAG (Retrieval-Augmented Generation) retrieves the few relevant passages from your own documents and puts them in the prompt, so the model answers from your sources instead of its training memory. Anthropic's own guidance: for a knowledge base under ~200k tokens, you can just include all of it in the prompt — no RAG needed. Above that, retrieval is what keeps you from blowing past the window (and paying for tokens the answer never needs).
When your whole knowledge base comfortably fits the window. Anthropic's rule of thumb is roughly: under ~200k tokens (about 500 pages), just put the documents in the prompt — it is simpler and avoids a retrieval pipeline entirely. RAG earns its keep once the corpus is too big to fit, changes often, or is large enough that paying to send all of it on every call is wasteful.
Split on the document's own structure (headings, paragraphs, sections) rather than a fixed character count, and let chunks overlap by ~10–20% so a thought is never cut across a boundary. A strong pattern is to embed small, precise chunks for retrieval but return the larger parent section to the model so it has enough context to answer. Good chunking is upstream of everything — bad chunks cap how good retrieval can ever be.
Hybrid search runs semantic (vector) retrieval and keyword (BM25) retrieval together and fuses the results. Vectors catch meaning but miss exact tokens — product codes, IDs, error strings, names — while keyword search nails those exact matches. Anthropic found that contextual embeddings combined with contextual BM25 cut top-20 retrieval failures by 49%, more than embeddings alone.
Reranking over-retrieves a wide candidate set (say top 20–100), then passes it through a more accurate model — a cross-encoder reranker that scores each chunk against the query — and keeps only the best 5–10 for the prompt. Anthropic measured that adding reranking cut retrieval failures by 67%, the best result in their study. The first pass is cheap and wide; the reranker is the precision step.
A common cause is "lost in the middle": Liu et al. showed that language models use information best when it appears at the start or end of the input, and degrade when the relevant passage sits in the middle of a long context — even for long-context models. Keep the retrieved list short and put your strongest chunks at the beginning and end. (Other causes: a stale index, bad chunking, or a retrieval miss — triage the stage.)
Measure the retriever and the answer separately. Context precision asks whether the retrieved chunks were relevant and ranked high; context recall asks whether you retrieved everything needed to answer. Faithfulness scores the generation: it is the fraction of the answer's claims that are actually supported by the retrieved context, so it catches confident statements the sources never made. These are standard Ragas metrics on a labelled query set.
If you already run Postgres, start with pgvector — it adds vector similarity search to the database you already have, with no new service to operate. Reach for a dedicated store when scale or features justify it: Chroma for the simplest local prototyping, Qdrant for cheap self-hosted scale, Pinecone for a fully managed (paid) option, or Weaviate for open-source with built-in vectorization and hybrid search.
Chunk overlapContextual retrievalTop-kDense vs sparse retrievalBM25Hybrid searchReciprocal Rank Fusion (RRF)Reranker / rerankingCross-encoderContext precisionContext recallFaithfulnessAsk, share, or report — over on the Heidelberg AI community forum.