Sub topic 14
Generating Grounded Answers with Citations
This chapter covers the step after the prompt is built: calling the model, getting an answer that stays inside the retrieved context, and checking that the citations are real. It assumes you can write basic Python, know how LLM prompts are structured, and have read the previous chapter on building the augmented prompt. The build_prompt function from that chapter is reused here.
What "grounded" means
A grounded answer is one where every claim can be traced to a passage the system retrieved. Grounding is a property you check, not one the model guarantees. A model that is told to use only the context can still:
- Add facts from its training data that sound right but are not in the passages.
- Cite a passage number that does not support the claim next to it.
- Answer confidently when the retrieved passages are off topic.
Each of these is a different failure, and each needs a different check. The rest of the chapter works through them in order.
The prompt contract
The prompt from the previous chapter sets three rules: use only the context, cite passages like [1], and say you don't know when the context is insufficient. Here is the function again.
def build_prompt(question, passages):
context = "\n\n".join(f"[{i}] {p}" for i, p in enumerate(passages, start=1))
return (
"Answer using only the context below. "
"Cite passages like [1]. "
"If the context does not contain the answer, say you don't know.\n\n"
f"Context:\n{context}\n\n"
f"Question: {question}\nAnswer:"
)Numbering passages gives the model a short, unambiguous label to copy. Long titles or URLs as labels are easier to garble. You map the number back to the real source (file, page, URL) in your own code, after generation.
Settings that help
- Low temperature. Use 0 or close to it. Grounded answering is extraction and summarizing, not creative writing, and sampling randomness mostly adds drift.
- Put the instructions where your model follows them best. Many chat models follow rules in a system message more reliably than rules buried in the user turn. Test both on your model.
- Keep the passage count modest. Passages in the middle of a very long context are used less reliably than those at the start or end. If you retrieve many passages, rerank and pass fewer.
Calling the model
The call itself depends on your provider. This sketch uses a placeholder call_llm function so the logic stays visible. Replace its body with your provider's chat API.
def call_llm(prompt, temperature=0.0):
# Replace with a real API call. This stub returns a fixed answer
# so the rest of the code can be run as shown.
return "Refunds are issued within 14 days [1]. Shipping is free over $50 [2]."
passages = [
"Refunds are issued within 14 days of receiving the returned item.",
"Orders over $50 qualify for free standard shipping.",
]
question = "What is the refund window and when is shipping free?"
answer = call_llm(build_prompt(question, passages))
print(answer)Parsing and validating citations
Treat the model's output as untrusted text. Before showing it to a user, extract the citation markers and check them against the passages you supplied.
import re
def extract_citations(answer):
return [int(n) for n in re.findall(r"\[(\d+)\]", answer)]
def validate_citations(answer, num_passages):
cited = extract_citations(answer)
invalid = [n for n in cited if not 1 <= n <= num_passages]
return {
"cited": sorted(set(cited)),
"invalid": sorted(set(invalid)),
"has_citation": bool(cited),
}
report = validate_citations(answer, len(passages))
print(report)With the stub answer above, this prints {'cited': [1, 2], 'invalid': [], 'has_citation': True}.
This check catches two cheap problems: an answer with no citations at all, and citations that point to a passage number that does not exist. It does not tell you whether [1] actually supports the sentence it follows.
Mapping citations back to sources
Keep a parallel list of metadata for the passages, in the same order. After validation, turn numbers into source references.
def resolve_sources(cited_numbers, metadata):
# metadata[i-1] describes passage [i]
return [metadata[n - 1] for n in cited_numbers if 1 <= n <= len(metadata)]
metadata = [
{"source": "returns-policy.md", "section": "Refunds"},
{"source": "shipping.md", "section": "Free shipping"},
]
print(resolve_sources(report["cited"], metadata))The user then sees real file names or links, and your system never relies on the model to write them.
The three layers of checking
- Format check. The regex validation above. It is fast and deterministic.
- Support check. Does the cited passage actually back the claim? This usually needs a second model call acting as a judge, or a natural language inference model. You split the answer into sentences, pair each with its cited passages, and ask whether the passages entail the sentence.
- Refusal check. Did the model answer when the context could not support an answer, or refuse when it could? This is tested with evaluation questions, covered in the evaluation chapter.
Run layer 1 on every request. Run layer 2 on every request only if the cost and latency are acceptable. Otherwise sample a fraction of traffic and monitor the rate.
Teaching the model to refuse
"I don't know" is a correct answer when retrieval failed. Two practices make it dependable.
First, make the refusal wording explicit so you can detect it. For example, instruct the model to reply with exactly INSUFFICIENT_CONTEXT when it cannot answer. Your code can then branch on that string instead of guessing from free text.
def is_refusal(answer):
return answer.strip().startswith("INSUFFICIENT_CONTEXT")Second, add a retrieval-side guard. If the best similarity score is below a threshold you tuned on your own data, skip generation and return a fixed message. The model cannot misuse context it never receives.
def answer_or_refuse(question, scored_passages, min_score=0.3):
# scored_passages is a list of (score, text), best first
if not scored_passages or scored_passages[0][0] < min_score:
return "I couldn't find this in the available documents."
texts = [text for _, text in scored_passages]
return call_llm(build_prompt(question, texts))The value 0.3 is a placeholder. Score distributions differ between embedding models, so pick the threshold from a labeled set of answerable and unanswerable questions.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Answer includes facts not in any passage | Instruction too weak, or the model's prior knowledge is strong | Restate the rule, lower temperature, add a support check |
| Citation numbers outside the range | Model invented a label | Validate and retry, or drop the invalid marker |
| Every sentence cites `[1]` | Passage order puts a generic passage first | Rerank before building the prompt |
| Confident answer on an unrelated question | Retrieval returned weak matches and no guard exists | Add a score threshold and a refusal string |
| Correct claim, wrong citation | Model matched the right fact to the wrong label | Support check per sentence, shorter passages |
| Citations stripped from the output | Output reformatted by a downstream template | Parse citations before any formatting step |
A note on quoting
Some systems ask the model to include a short verbatim quote with each citation. You can then check the quote with a plain substring test against the passage. This is cheap and catches many fabricated citations, though a model can quote real text that still does not support its claim.
def quote_in_passage(quote, passage):
normalize = lambda s: " ".join(s.lower().split())
return normalize(quote) in normalize(passage)Retry and fallback policy
When validation fails, you have three options. Retry once with the validation error appended to the prompt. Fall back to returning the top passages themselves with no generated summary. Or return a refusal message. Pick one per failure type, and cap retries so a bad query cannot loop and run up cost.
Exercises
Exercise
A model answers "Warranty lasts two years [3]." You supplied only two passages. Which check catches this, and what should the system do?
Show answer
The citation format check catches it, because 3 is outside the range 1 to 2. The system should not show the answer as is. It should retry once with the error noted, then fall back to a refusal or to returning the top passages.
Exercise
Every citation in an answer is a valid number, yet a reviewer finds one sentence that its cited passage does not support. Name a check that finds this and say why the regex check cannot.
Show answer
A support check, using a judge model or an entailment model on each sentence and its cited passage. The regex check only looks at the number's format and range. It has no access to the meaning of the passage or the claim.
Exercise
Why is a similarity-score threshold before generation useful even when the prompt already tells the model to say "I don't know"?
Show answer
The model may ignore the instruction and produce a plausible answer from weak or irrelevant context. Skipping generation when the best score is low means the model never gets the chance. It also saves the cost of a model call.