Sub topic 11
Verifying Quoted Text Against Sources
This chapter assumes you can write basic Python and call a language model through an API. It also assumes you know how a retrieval-augmented generation (RAG) pipeline hands numbered sources to a model, and that you have already built the numbered context and the marker validation from earlier chapters. Here you add a stronger check: confirming that a quote the model attributes to a source really appears in that source.
Why check quotes
Marker validation tells you that [2] points to a source that exists. It does not tell you that source 2 says anything related to the claim. A model can cite a real source number next to a sentence the source never made.
Quote verification closes part of that gap. You ask the model to attach a short verbatim excerpt to each claim, then your code looks for that excerpt in the cited source. A string search is cheap, deterministic and needs no second model call. If the excerpt is not there, you know the model either invented it or attributed it to the wrong source.
Asking for quotes in structured output
Quotes work best in a structured format, because each quote is tied to a specific claim and specific source ids. Here is the shape used in this tutorial:
{
"answer": "The service retries failed requests up to three times.",
"claims": [
{
"text": "The service retries failed requests up to three times.",
"source_ids": [2],
"quote": "failed requests are retried up to three times"
}
]
}Your prompt should say three things about the quote field:
- It must be copied exactly from the cited source, not paraphrased.
- It should be short, usually one clause or one sentence.
- If no exact passage supports the claim, the model should not make the claim.
Short quotes matter. A long quote is more likely to contain a small copying error, such as a changed word or dropped punctuation, and your check will then reject a claim that was in fact supported.
The basic check
The check normalizes both strings and tests whether one contains the other:
def normalize(text):
return " ".join(text.lower().split())
def quote_is_supported(quote, source_text):
"""True if the quote appears verbatim in the source, ignoring case and whitespace."""
return normalize(quote) in normalize(source_text)split() with no arguments splits on any run of whitespace, so line breaks, tabs and double spaces all collapse to single spaces. This matters because retrieved chunks often come from PDFs or HTML with line breaks in the middle of sentences. The model sees those line breaks too, but it often "cleans" them when it quotes.
source = "Reliability notes:\nFailed requests are retried\nup to three times."
print(quote_is_supported("failed requests are retried up to three times", source)) # True
print(quote_is_supported("failed requests are retried up to five times", source)) # FalseWhere exact matching breaks
Verbatim matching is strict on purpose, but some differences are not fabrication. The most common ones are typographic:
| Difference | Source text | Model's quote |
|---|---|---|
| Curly vs. straight quotes | `don’t` | `don't` |
| Dash variants | `3–5 seconds` | `3-5 seconds` |
| Non-breaking space | `10 MB` (with U+00A0) | `10 MB` (ordinary space) |
| Ligatures | `file` | `file` |
str.split() already treats U+00A0 as whitespace, so that case is handled. The others need a stronger normalizer. Unicode NFKC normalization folds ligatures and compatibility characters, and a translation table handles quotes and dashes:
import unicodedata
_PUNCT_MAP = str.maketrans({
"\u2018": "'", "\u2019": "'",
"\u201c": '"', "\u201d": '"',
"\u2013": "-", "\u2014": "-",
})
def normalize(text):
text = unicodedata.normalize("NFKC", text)
text = text.translate(_PUNCT_MAP)
return " ".join(text.lower().split())Apply the same function to both the quote and the source. Normalizing only one side creates false mismatches.
Keep the normalizer small. Every rule you add makes the check more forgiving. Fold only differences that cannot change meaning. Do not strip digits, negations or units, and do not collapse words like "not" or "no".
Checking a whole response
A claim is verified only if three things hold: it lists at least one source id, every id is in range, and its quote appears in at least one of the cited sources. The function below returns a list of problems, so you can log them and decide what to do.
def validate_claims(claims, sources, min_quote_chars=15):
"""claims: list of dicts with 'source_ids' and 'quote'.
sources: list of dicts with 'text'. Source ids start at 1.
Returns a list of (claim_index, problem) tuples."""
problems = []
for idx, claim in enumerate(claims):
ids = claim.get("source_ids", [])
quote = claim.get("quote", "")
if not ids:
problems.append((idx, "no source ids"))
continue
bad = [n for n in ids if not 1 <= n <= len(sources)]
if bad:
problems.append((idx, f"unknown source ids: {bad}"))
continue
if len(normalize(quote)) < min_quote_chars:
problems.append((idx, "quote missing or too short to be meaningful"))
continue
if not any(quote_is_supported(quote, sources[n - 1]["text"]) for n in ids):
problems.append((idx, "quote not found in cited sources"))
return problemsHere is a run with one good claim and one misattributed claim:
sources = [
{"url": "https://example.com/a", "text": "Timeouts default to 30 seconds."},
{"url": "https://example.com/b", "text": "Failed requests are retried up to three times."},
]
claims = [
{"text": "Requests are retried three times.", "source_ids": [2],
"quote": "failed requests are retried up to three times"},
{"text": "The default timeout is 30 seconds.", "source_ids": [2],
"quote": "timeouts default to 30 seconds"},
]
print(validate_claims(claims, sources))
# [(1, 'quote not found in cited sources')]The second claim is true, and its quote exists, but it appears in source 1 and the model cited source 2. The check catches that misattribution. That is the main benefit over marker validation alone.
Edge cases
Very short quotes. A quote like "three times" will match many passages by chance. The min_quote_chars threshold rejects them. Fifteen characters is a starting point. Tune it on your own data.
Quotes that span chunks. If a passage was split across two chunks, a quote from the join will not appear in either one. Either keep chunk overlap large enough that important sentences are whole in at least one chunk, or tell the model to quote from within a single source.
Ellipses. Models sometimes write "retried ... three times". Split the quote on ... or the Unicode ellipsis and require each fragment to appear, in order. Without that rule, a quote with an ellipsis fails every time.
Paraphrase instead of quote. If the model rewrites the passage, the match fails even though the claim might be fine. Treat this as a prompt problem first. Repeat that the quote must be copied, and show an example in the prompt.
Fuzzy matching. You can relax the check with an edit-distance or similarity threshold. This reduces false rejections but also lets near-miss fabrications through, such as "four times" versus "three times". If you add fuzzy matching, route those cases to a "needs review" bucket instead of accepting them.
What a passing quote does not prove
A quote that is in the source shows only that the words exist there. It does not show that the claim follows from them. The model can quote a sentence about version 1 and use it to support a statement about version 2. It can quote a sentence that is negated two lines later, or one that describes a proposal rather than a fact.
Another subtle gap is that the check trusts the source text. If a retrieved document contains injected instructions, a model that obeys them can still quote the document faithfully. The prompt's instruction to treat sources as data is the defense for that, not this check.
Deciding what to do on failure
When validate_claims returns problems, you have three reasonable options:
- Drop the failing claims. Show only verified claims. This is safe, but the answer may become incomplete or incoherent.
- Retry once. Send the model the specific failures ("the quote for claim 2 was not found in source 2") and ask it to correct them. Limit this to one or two retries.
- Fall back to abstention. If most claims fail, return the "could not find this in the provided sources" reply instead of a partly verified answer.
Whichever you choose, log the failures along with the question, the source ids and the model's output. These logs are the raw material for the evaluation work later in the tutorial.
Exercise
A model returns a claim with sourceids [3] and the quote "the cache expires after 60 seconds". The quote appears word for word in source 1 but not in source 3. What does validateclaims report, and what does this result tell you about the model's output? Would the same result guarantee the claim is correct if the quote had been found in source 3?
Show answer
validateclaims reports "quote not found in cited sources" for that claim, because it only searches the sources named in sourceids (here, source 3). The result indicates a misattribution: the text is real, but the model pointed to the wrong source. If the quote had been found in source 3, the claim would pass, but that would still not guarantee correctness. The check confirms only that the words exist in the cited source. The sentence might be negated, outdated, or about a different subject than the claim, so a separate faithfulness check is needed.