Generation & Grounding
Prompting a model to answer only from retrieved context — citations, refusals, structured output, streaming, and hallucination control
Generation & Grounding
TL;DR
The final stage: the model reads your retrieved context and writes an answer. Grounding means constraining it to use only that context. This is achieved through explicit instructions, attribution markers, an easy path to saying "I don't know", and verification of the output. Get this wrong and all your retrieval work is spent on an answer the model half-ignores.
| Property | Value |
|---|---|
| Level | Intermediate |
| Reading time | ~20 minutes |
| Prerequisites | Reranking & Context Assembly |
| You will understand | Grounded prompting, citations, refusal design, and output verification |
The Job of This Stage
The model has two sources of knowledge in front of it:
- Your retrieved context — trustworthy, current, citable
- Its own training data — broad, possibly outdated, uncitable, and sometimes wrong
Grounding means making the first the source of truth and the second off-limits. Left unconstrained, models blend the two, producing answers where you cannot tell which parts came from your documents. That blend is the thing to prevent.
The Anatomy of a Grounded Prompt
┌─ ROLE ────────────────────────────────────────────────────┐
│ You are a clinical information assistant for staff at │
│ Northgate Clinic. │
├─ GROUNDING RULES ─────────────────────────────────────────┤
│ - Answer using ONLY the context below. │
│ - If the context does not contain the answer, reply │
│ exactly: "I don't have that information in my sources." │
│ - Do not use knowledge from your training data. │
│ - Cite the source number in brackets after each claim. │
│ - If sources disagree, say so and present both. │
├─ CONTEXT ─────────────────────────────────────────────────┤
│ [1] (anticoagulation-protocol.pdf, p.3) │
│ Patients on warfarin should consult their prescriber │
│ before starting any NSAID. │
│ │
│ [2] (drug-interactions.pdf, p.14) │
│ NSAIDs including ibuprofen increase bleeding risk when │
│ taken with warfarin. │
├─ QUESTION ────────────────────────────────────────────────┤
│ Can a patient on warfarin take ibuprofen? │
└────────────────────────────────────────────────────────────┘Every block earns its place:
| Block | Purpose | If omitted |
|---|---|---|
| Role | Sets audience and tone | Wrong tone; wrong assumed expertise |
| Grounding rules | Constrains the source of truth | Model blends training knowledge with context |
| The "I don't know" instruction | Gives an acceptable exit | Model invents rather than admit a gap |
| Context with markers | The facts, individually addressable | No citations possible; references get fabricated |
| Question last | High-attention position | Competes with context for attention |
Making "I Don't Know" Achievable
This is the most under-appreciated part of grounded generation. A model asked a question will strongly tend to produce an answer — that is what it was trained to do. Unless refusing is made explicitly acceptable and concrete, it will fill the gap with plausible invention.
What works:
| Technique | Why it helps |
|---|---|
| Give the exact refusal wording | "Reply exactly: 'I don't have that information in my sources.'" — a specific string is far easier to produce than an abstract permission |
| State it is the correct answer | "Saying you don't know is a correct and expected response, not a failure." |
| Show one example | A single demonstration of a refusal in the prompt raises compliance substantially |
| Ask for partial answers explicitly | "If the context answers part of the question, answer that part and state what is missing." |
| Never punish refusals in evaluation | If your metrics reward answering, you have trained your own pipeline to hallucinate |
Citations
Citations are the mechanism that makes a RAG answer checkable. They convert "trust me" into "verify me."
| Style | Example | Best for |
|---|---|---|
| Inline numeric | "Ibuprofen raises bleeding risk [2]." | Most systems — compact and clear |
| Per-sentence | Every sentence carries a marker | High-stakes domains; auditability |
| Footnoted | Claims marked, sources listed below | Long-form answers |
| Span-linked | Citation points to exact characters in the source | Best user experience; most implementation work |
Verify citations programmatically. Models sometimes cite [3] when the claim came from [1], or cite a source number that does not exist. Since you control the context, you can check every emitted marker against the actual chunk list — and you should. A wrong citation is worse than no citation, because it manufactures unearned confidence.
Generation Parameters
| Parameter | What it does | For RAG |
|---|---|---|
| Temperature | Randomness in token choice | 0 to 0.3. You want faithful reproduction of context, not creativity |
| Top-p | Restricts sampling to the most probable tokens | 0.9 or leave default; temperature is the more useful dial |
| Max tokens | Output length cap | Set it — prevents runaway generation costs |
| Stop sequences | Ends generation at a marker | Useful for structured formats |
| Seed | Reproducibility, where supported | Valuable for evaluation runs |
Temperature 0 is the right default for RAG and surprises people who expect it to make answers "robotic". It does not — the model still writes fluent prose. It simply picks the most likely wording rather than sampling among alternatives, which is exactly what you want when the content must mirror the source.
Structured Output
For downstream processing, request a schema rather than prose:
{
"answer": "Ibuprofen increases bleeding risk when taken with warfarin.",
"confidence": "high",
"sources": [1, 2],
"caveats": ["Individual dosing decisions require prescriber review."],
"answered_from_context": true
}The answered_from_context flag is particularly valuable: it gives you a machine-readable signal of whether the model believes it was grounded, which you can log, alert on, and evaluate against.
Streaming
Generation dominates latency, so streaming tokens as they are produced is the single largest perceived-performance improvement available.
| Consideration | Detail |
|---|---|
| Perceived latency | First token in ~300 ms feels far faster than a complete answer in 2,000 ms |
| Citations | Markers stream mid-sentence; resolve them into links progressively or on completion |
| Verification | Post-generation checks cannot run until generation ends — decide whether to stream first and correct after, or verify then display |
| Errors | A failure mid-stream leaves a partial answer on screen; handle it explicitly |
If you run output verification — citation checks, safety filters, groundedness scoring — streaming creates a genuine tension: you have shown the user text you have not yet validated. In high-stakes domains, verify before displaying and accept the slower first token.
Reducing Hallucination at This Stage
Retrieval quality matters most, but generation-stage techniques help.
| Technique | How it works | Cost |
|---|---|---|
| Explicit grounding instructions | Tell the model the context is the only allowed source | Free |
| Attribution requirement | Forcing per-claim citation makes ungrounded claims awkward to produce | Free |
| Groundedness check | A second pass verifies each claim is supported by the context | One extra call |
| Self-consistency | Generate several times; disagreement signals uncertainty | N× cost |
| Claim-level verification | Split the answer into claims, check each against the context | Expensive, most thorough |
| Refusal calibration | Make "I don't know" easy and rewarded | Free |
The honest limit
None of these eliminate hallucination — they reduce its rate and make it detectable. A production system in a high-stakes domain should assume some answers will be wrong and design for that. Show sources prominently, make checking easy, and keep a human in the loop where the cost of being wrong is high.
Common Prompting Mistakes
What goes wrong in the prompt
No explicit grounding instruction
Without "use only the context", the model treats retrieved text as a hint and freely blends training knowledge. The answer looks fine and is partly unsourced — the worst combination, because it is undetectable by reading.
No refusal path
The model has no acceptable way to fail, so it invents. Always provide the exact wording for "I don't know".
Context without markers
Citation becomes impossible, so the model produces plausible-looking references that correspond to nothing.
Question buried before a huge context
Puts the question in a low-attention position and lets the context dominate. Question last.
Temperature left at 1.0
Introduces variation in a task where you want faithful reproduction. It also makes evaluation noisy, because the same input produces different outputs run to run.
No handling of contradictory sources
When two retrieved chunks disagree — an old policy and its replacement — an unbriefed model silently picks one or averages them. Instruct it to surface the conflict, and use recency metadata to disambiguate.
Concept Checks
Check yourself
Why does giving exact refusal wording work better than saying 'admit when you don't know'?
Because it converts an abstract judgement into a concrete, low-effort output. "Admit uncertainty" requires the model to evaluate its own knowledge state and then invent a phrasing, competing against a strong learned pull toward producing a substantive answer. A specific string is a simple, unambiguous target that is easy to emit.
Two retrieved chunks give different refund windows. What should the system do?
Surface the conflict rather than resolve it silently. Instruct the model to state that sources disagree and present both with their citations, and use recency or version metadata to indicate which supersedes. Silently picking one produces a confident answer that may be based on a superseded document, with no signal to the user that a choice was made at all.
Why verify citations programmatically when the model produced them?
Because you have the ground truth and the model does not need to be trusted here. You assembled the context, so you know exactly what chunk [2] contains — checking that emitted markers exist and that the cited chunk actually supports the claim is cheap and deterministic. Models do misattribute, and a confidently wrong citation is more damaging than none because it invites trust it has not earned.
Your evaluation scores answers on helpfulness only. What behaviour does that create?
It trains the pipeline toward hallucination. A correct refusal scores badly under a helpfulness-only metric while a fluent invention scores well, so every tuning decision you make will push away from appropriate refusals. Evaluation must reward correct "I don't know" responses, or your metrics actively work against grounding.
Key Concepts Recap
| Concept | One-line summary |
|---|---|
| Grounding | Making retrieved context the only allowed source |
| Blending | The default failure — training knowledge mixed with context, undetectably |
| Refusal path | Give exact wording; make "I don't know" easy and correct |
| Attribution markers | [1], [2] in context; without them citations get invented |
| Citation verification | Check emitted markers against the real chunk list |
| Temperature 0–0.3 | Faithfulness over creativity |
| Structured output | Schemas give machine-readable grounding signals |
| Streaming | Biggest perceived-latency win; conflicts with pre-display verification |
| Contradictions | Surface them; do not let the model resolve them silently |
| The honest limit | Hallucination is reduced and made detectable, never eliminated |
Next
You now know the whole basic pipeline — for a single question asked once. Real users chat, so that assumption breaks next: Conversational RAG.
Reranking & Context Assembly
Cross-encoders, ColBERT, and LLM rerankers — plus context ordering, the lost-in-the-middle effect, deduplication, and compression
Conversational RAG
Making RAG work across many turns — rewriting follow-up questions, managing chat history, resolving references, and handling topic changes