Sub topic 13
Grounding answers and citing sources
This chapter assumes you can read basic Python and know the agent loop from earlier chapters: the model calls search_docs, receives passages with ids, and decides when to answer. Here you make the final answer trustworthy.
What grounded means
A grounded answer is one where every factual claim is supported by a passage the agent retrieved in this run. An answer can sound right and still be ungrounded, because the model filled a gap from its training data. In an agent loop this is more likely than in classic RAG. Several searches produce a lot of text, and the model may blend retrieved facts with remembered ones.
Citations make grounding checkable. If each claim carries a passage id, a reader or a program can compare the claim with the passage.
Give the model something to cite
The search_docs tool already returns {"id": ..., "text": ...}. The ids are what make citation possible. Keep them short and stable, such as billing-04. Do not ask the model to cite page titles or URLs it might invent.
The system prompt should state the rules plainly:
- Use only facts found in tool results.
- Put the passage id in square brackets after each claim, like
[billing-04]. - If the passages do not answer the question, say so and name what is missing.
The last rule matters most. It connects to result grading: when evidence is missing, an honest "not found" is a correct answer.
Verify citations in code
Do not trust the model to cite correctly. Check that every cited id was actually returned during the run. The function below collects ids from tool results and flags any citation that does not match.
import json
import re
CITATION = re.compile(r"\[([A-Za-z0-9_.-]+)\]")
def retrieved_ids(messages):
ids = set()
for m in messages:
if m["role"] == "tool":
result = json.loads(m["content"])
if isinstance(result, list):
ids.update(item["id"] for item in result)
return ids
def check_citations(answer, messages):
cited = set(CITATION.findall(answer))
known = retrieved_ids(messages)
return {
"invalid": sorted(cited - known),
"uncited": len(cited) == 0,
}
messages = [
{"role": "tool", "tool_call_id": "1",
"content": json.dumps([{"id": "billing-04", "text": "Invoices are issued monthly."}])},
]
print(check_citations("Invoices are monthly [billing-04]. Refunds take 5 days [refund-9].", messages))This prints {'invalid': ['refund-9'], 'uncited': False}. The id refund-9 was never retrieved, so the claim attached to it is fabricated or came from memory. You can then retry, strip the claim, or flag the answer.
The grounding check flow
Common errors
| Error | Cause | Fix |
|---|---|---|
| Invented ids | Model guesses a plausible id | Validate ids against tool results |
| Citation on the wrong claim | Id attached to a loosely related sentence | Require one id per claim and check support |
| Confident answer with no evidence | Prompt lacks an "admit missing" rule | Add the rule and test with unanswerable questions |
| Old passages cited after context trimming | Trimmed messages removed the source | Keep passage ids and text for any cited passage |
Exercise
An answer cites [pricing-12], and your check finds that pricing-12 was returned by a tool call in this run. Does that prove the claim is grounded? What else would you check?
Show answer
No. It only proves the passage was retrieved. The passage might not say what the claim says. You also need to check that the cited text supports the claim, for example by comparing the claim with the passage using a second model call or a human review.