Sub topic 13
Grounding Answers and Citing Sources
What you need first
This chapter assumes you have read the earlier chapters of this tutorial. You should know the agent loop, the search_docs tool that returns {"id", "text"} passages, and the step budget. You also need basic Python and regular expressions.
What grounding means
A grounded answer is one where every factual claim can be traced to a passage the agent actually retrieved. Grounding is not the same as being correct. A grounded answer can be wrong if the source is wrong or out of date. An ungrounded answer can happen to be right, because the model remembered it from training. You still cannot check it, so you cannot trust it.
Citations are the visible side of grounding. A citation is a marker in the answer, such as [billing-12], that points to a passage id. A reader or a program can follow the marker and check the claim against the text.
Why agents make grounding harder
In classic RAG there is one retrieval and one prompt. Every passage in the context is a candidate source, and the ids sit right next to the question.
An agent adds three problems:
- Many rounds. Passages arrive across several tool calls. The answer may draw on the first round and ignore the third.
- Noise. The agent may retrieve passages that turned out to be irrelevant. It should not cite those.
- Trimmed context. If you shorten old tool results to save space (see the context management chapter), the text behind an id may no longer be visible to the model when it writes the answer.
So you need a plan for ids, a prompt that requires citations, and a check in code that does not depend on the model's good behavior.
Step 1: give every passage a stable id
The model can only cite what it can name. Follow these rules:
- Ids come from your index, not from the model. Use a document id plus a chunk number, such as
limits-3. - An id means the same passage for the whole run. Do not renumber results per call (
1, 2, 3each time), because[2]would then be ambiguous. - Ids are short and have no spaces or brackets, so they are easy to match with a regular expression.
The search_docs function from the earlier chapter already returns this shape. The next step is to record what it returned.
Step 2: record every retrieved passage
Wrap each tool so that every result is stored in a dictionary keyed by id. This dictionary is the evidence ledger. It lets you verify citations later, even if you trimmed old messages from the conversation.
def make_recording_tool(tool, ledger):
"""Wrap a retrieval tool so each returned passage is saved by id."""
def wrapped(**arguments):
results = tool(**arguments)
for passage in results:
ledger[passage["id"]] = passage["text"]
return results
return wrappedPass the wrapped tool in tools_by_name when you call run_agent. After the run, ledger holds every passage the agent saw. The agent loop code does not change.
Step 3: instruct the model to cite and to abstain
The system prompt should state the rules plainly:
- Put the passage id in square brackets after each claim it supports, for example
[limits-3]. - Cite only ids that appeared in tool results.
- If the passages do not answer the question, say what is missing instead of guessing.
- If a question needs no documentation (a greeting, for example), answer directly without citations.
The last rule matters because of the earlier chapter on skipping retrieval. A check that demands a citation on every sentence would otherwise punish correct behavior.
Step 4: verify citations in code
A prompt is a request, not a guarantee. Models sometimes invent ids that look plausible, or they cite a real id for a claim it does not support. A cheap check in code catches the first failure, and it flags sentences that carry no citation.
import re
CITATION = re.compile(r"\[([A-Za-z0-9_.:-]+)\]")
SENTENCE_END = re.compile(r"(?<=[.!?])\s+")
def check_citations(answer, ledger):
cited = set(CITATION.findall(answer))
unknown = sorted(cited - set(ledger))
uncited = [
s for s in SENTENCE_END.split(answer.strip())
if len(s.split()) > 4 and not CITATION.search(s)
]
return {"cited": sorted(cited & set(ledger)), "unknown": unknown, "uncited": uncited}
ledger = {"limits-3": "The free plan allows 5 projects.", "billing-1": "Invoices are sent monthly."}
answer = "The free plan allows 5 projects [limits-3]. Teams can have unlimited seats [plans-9]. Good luck."
print(check_citations(answer, ledger))Running this prints:
{'cited': ['limits-3'], 'unknown': ['plans-9'], 'uncited': []}The second sentence cites plans-9, which the agent never retrieved, so it lands in unknown. The sentence "Good luck." is too short to count. You can change the length threshold to suit your answers.
What to do with a failed check depends on your product:
- Ask the model once to repair the answer, passing the list of bad ids.
- Remove the unsupported sentences.
- Return the answer with a warning.
Avoid a repair loop without a limit. It adds to the step budget problem you already solved.
Checking support, not just existence
The code check proves an id exists. It does not prove the passage says what the sentence claims. Three options, in rising order of cost:
| Check | What it catches | Cost |
|---|---|---|
| Id exists in ledger | Invented ids | Almost none |
| Keyword or number overlap between claim and cited passage | Wrong numbers, wrong names | Low |
| A second model call that judges whether the passage supports the claim | Subtle misreadings | One call per claim or per answer |
A practical rule is to run the first check always, run the second on numbers and named limits, and use the third in offline evaluation (covered in the next chapter) instead of on every request.
Handling missing evidence
The grading step from the previous chapter can end with "the evidence is not there." Grounding is where that outcome becomes visible to the user. A good abstention names what was searched and what is missing:
"The documentation I searched covers plan limits [limits-3] but does not state the limit for API requests."
This is better than a refusal, because the user learns what was found. It is also better than a guess, because the user does not act on a made-up number. Partial answers are normal in agentic RAG. A question with three parts may be answered for two parts, with the third marked as missing.
Common errors
- Citing the document, not the passage.
[handbook]cannot be checked. Cite the chunk. - Citing the last result only. The model attributes a claim to the most recent tool output even though an earlier one supported it. Stable ids across rounds prevent most of this.
- Trusting the text of the id. An id in a retrieved passage's own text, such as "see [admin-1]", is document content, not a source you retrieved. Your checker uses the ledger, which only holds ids returned by the tool.
- Citations on guesses. The model attaches a real id to a claim from memory. Only the support checks above catch it.
- Silent truncation.
search_docscuts text to 1200 characters. A claim based on the cut part cannot be verified, so truncate on sentence boundaries if you can.
Summary of the design
- Index ids are stable and short.
- A wrapper records every passage into a ledger.
- The prompt requires citations and allows abstention.
- Code checks that cited ids exist and flags uncited factual sentences.
- Support checks run where the risk justifies the cost.
Exercise
An agent's answer cites [pricing-7], and check_citations reports no unknown ids. A reviewer finds that pricing-7 says nothing about the refund period the sentence claims. Which failure is this, which of your checks missed it, and what is one way to catch it?
Show answer
The cited id is real but does not support the claim. The existence check passes because the id is in the ledger. A keyword or number overlap check between the sentence and the passage text would catch a wrong figure like a refund period, and a second model call that judges whether the passage supports the claim would catch subtler cases. Both belong in evaluation, and the cheaper one can run per request.
Exercise
Why should the ledger be filled by a wrapper around the tool and not by parsing the model's messages afterward?
Show answer
The wrapper records exactly what the retrieval function returned, so the ledger cannot contain ids the model made up. It also keeps full passage text after you trim old tool messages from the conversation, so you can still verify citations at the end.