Sub topic 8
Grounding findings in retrieved sources
This chapter assumes you have read the earlier chapters on language model limits and marketing data sources. It also assumes you can read basic Python and JSON. Grounding means the agent writes each finding from material it retrieved in the current run, instead of from what the model remembers. You will build a small retrieval step, a citation format, and a check that rejects claims the sources do not support.
Why grounding matters
A language model produces fluent text whether or not it knows the facts. Asked for last month's cost per click, it can invent a plausible figure. Grounding limits what the model may say to what you gave it, and it lets a reader trace each claim to a source.
Grounding has three parts:
- Retrieve. Fetch the records or documents relevant to the question.
- Constrain. Tell the model to use only those records and to cite them.
- Check. Test the output against the same records before anyone reads it.
Most teams skip the third part. Without it, "use only the sources" is a request the model may not follow.
What counts as a source
Marketing agents use two kinds of source, and they need different retrieval.
| Kind | Examples | Retrieval method |
|---|---|---|
| Structured | Ad platform exports, analytics reports, CRM tables | A tool call with exact parameters such as date range and campaign ID |
| Unstructured | Competitor pages, industry reports, call notes, briefs | Search by keywords or embeddings, then return passages |
For structured data, do not search by similarity. Call a tool that returns the exact rows, as covered in the tool-use chapter. Similarity search can return last year's report when you wanted this month's. For unstructured text, retrieve short passages, because a whole document buries the relevant sentence and uses context space.
Every retrieved item needs three fields: a stable id, the text, and ideally metadata such as retrieved_at and origin. The id is what the model cites. The metadata lets you reject stale items.
The grounding pipeline
The diagram shows the order of steps. The check sits between the draft and the reader.
A working example
The code below is a minimal version of the pipeline. Retrieval is keyword overlap, which is crude but easy to follow. In production you would swap in a database query or a vector search. The structure stays the same.
import re
SOURCES = [
{"id": "ads-2026-10",
"text": "October search campaign: 10,000 impressions, 200 clicks, spend 150.00 USD."},
{"id": "crm-2026-10",
"text": "October CRM export: 10 conversions attributed to the search campaign."},
{"id": "web-acme",
"text": "Competitor Acme launched a free trial in September 2026, according to its public pricing page."},
]
STOPWORDS = {"the", "a", "to", "in", "did", "how", "of", "its"}
NUMBER = re.compile(r"\d+(?:,\d{3})*(?:\.\d+)?")
def tokens(text):
return set(re.findall(r"[a-z0-9]+", text.lower())) - STOPWORDS
def numbers_in(text):
return {float(n.replace(",", "")) for n in NUMBER.findall(text)}
def retrieve(question, sources, k=2):
q = tokens(question)
scored = [(len(q & tokens(s["text"])), s) for s in sources]
scored = [p for p in scored if p[0] > 0]
scored.sort(key=lambda p: -p[0])
return [s for _, s in scored[:k]]
def build_prompt(question, retrieved):
lines = ["Answer using ONLY the sources below.",
"Return JSON: a list of {\"text\": ..., \"source_ids\": [...]}.",
"If the sources do not contain the answer, return an empty list.",
"", "Sources:"]
lines += [f"[{s['id']}] {s['text']}" for s in retrieved]
lines += ["", "Question: " + question]
return "\n".join(lines)
def check_claims(claims, retrieved):
by_id = {s["id"]: s for s in retrieved}
problems = []
for claim in claims:
ids = claim.get("source_ids", [])
if not ids:
problems.append((claim["text"], "no citation"))
continue
unknown = [i for i in ids if i not in by_id]
if unknown:
problems.append((claim["text"], "unknown source: " + ", ".join(unknown)))
continue
cited = " ".join(by_id[i]["text"] for i in ids)
missing = numbers_in(claim["text"]) - numbers_in(cited)
if missing:
shown = ", ".join(f"{n:g}" for n in sorted(missing))
problems.append((claim["text"], "numbers not in cited sources: " + shown))
return problems
question = "How did the October search campaign perform?"
retrieved = retrieve(question, SOURCES)
print([s["id"] for s in retrieved])
print(build_prompt(question, retrieved))
# Stand-in for a model reply, with three deliberate faults.
claims = [
{"text": "The campaign had 200 clicks from 10,000 impressions.",
"source_ids": ["ads-2026-10"]},
{"text": "It produced 12 conversions.", "source_ids": ["crm-2026-10"]},
{"text": "Click-through rate beat the industry average.", "source_ids": []},
{"text": "Spend was 150 USD.", "source_ids": ["ads-2026-11"]},
]
for text, reason in check_claims(claims, retrieved):
print(reason, "|", text)The retrieval step returns ['ads-2026-10', 'crm-2026-10']. The competitor page scores zero and is dropped. The check then reports three problems:
- The claim of 12 conversions cites a source that says 10.
- The click-through claim has no citation.
- The spend claim cites an ID that was never retrieved.
The first claim passes. Each fault is a different failure, which is why the check tests each one separately.
Failure modes
Retrieval misses. If the right record is not retrieved, the model either says nothing or fills the gap from memory. Keep the instruction "return an empty list if the sources lack the answer," and treat an empty list as a result to show the reader, not as an error to retry silently.
Citing without supporting. A model can attach a real ID to a claim the source does not make. The number check above catches wrong figures but not wrong meaning. "Conversions rose" cited to a source that only lists totals passes the number check and fails in substance. For claims with no numbers, use a reviewer or a second model call that asks only "does this passage support this sentence?" Treat the second model's answer as a screening step, not as proof.
Stale sources. A correct citation of an outdated figure is still wrong. Filter by retrieved_at or by the report period before building the prompt. Put the date range in the tool call for structured data.
Conflicting sources. The ad platform and the CRM often disagree on conversions because they attribute differently. Do not let the model choose silently. Retrieve both, label each with its origin, and instruct the model to report the difference.
Unit and format drift. The check compares numbers after parsing, so "10,000" matches "10000". It does not know that 150 means dollars in one source and cents in another. Put units in the source text.
Instructions inside retrieved text. A web page can contain sentences such as "ignore previous instructions." Retrieved text is data. Wrap it in labeled blocks, tell the model that text inside the blocks is not instructions, and keep the agent's tool permissions narrow so that an injected instruction has little to act on.
Decision criteria
- Use a tool call, not search, when the answer is a number in a table. Exact queries return exact rows.
- Use passage retrieval for qualitative claims, such as competitor positioning, and keep the passage short enough to read in a few seconds.
- Retrieve fewer, better items. A larger
kraises recall but adds noise that the model may cite. Start with 3 to 5 passages and measure. - Store sources with the report. The reader should be able to open every cited ID. If the ID cannot be resolved later, the citation is decoration.
The next chapters use these cited claims as input for drafting the report and for the wider verification step.
Exercise
In the example, the check flags "It produced 12 conversions." cited to crm-2026-10. Suppose a model instead wrote "It produced 10 conversions, a strong result." cited to the same source. Does check_claims flag it, and what would catch the problem?
Show answer
It does not flag it. The number 10 appears in the cited source, there is a citation, and the ID is known. The phrase "a strong result" is a judgment the source does not support, and the check only compares numbers. A reviewer, or a separate support-check call that asks whether the passage supports the whole sentence, would catch it. A stricter prompt that forbids evaluative language unless a benchmark source is retrieved would also reduce it.
Exercise
The agent retrieved an ad platform report and a CRM export that give different conversion counts for the same month. Describe how you would handle this in the prompt and in the report.
Show answer
Retrieve both sources with their origins in the labels, and instruct the model to report each figure with its source instead of choosing one. In the report, state both numbers and note that the systems attribute conversions differently. If a decision depends on the figure, send the discrepancy to a reviewer.