Deep-Research Agents

Michael BrenndoerferDecember 1, 202651 min read

Build deep-research agents that plan multi-step investigations, verify citations, count independent evidence, and abstain when sources are thin.

Language AI HandbookAll chapters
Part 49 of 67Long-Horizon Agents and Interoperability
Chapter 375Deep-Research Agents
Reading the full chapter · 17 sections · 51 min17 sections · 51 min

All 17 sections · 51 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Deep-Research Agents

A widely scoped research question usually needs more than one retrieval pass. One search may surface a primary source and several articles summarizing it. Reading that batch can tell you which term to search next, where an apparent consensus comes from, and which claims still lack support. A single-shot RAG pipeline provides one batch of retrieved passages. An iterative research system can use that first batch to choose its next search.

A deep-research agent is a language-model-driven system that answers an open-ended information need by planning a multi-step investigation, issuing many searches, reading and filtering sources, deciding when evidence is sufficient, synthesizing an answer, and attaching citations that let a human check every claim. The output is not just prose. It is a research trace, a reproducible, auditable record of what was queried, what was retrieved, what was kept, and what was asserted on the basis of what. The agent behaves less like a search box and more like a careful human analyst working under a deadline. It forms a plan, follows leads, discards weak material, and is honest about the gaps it could not close.

We will distinguish planning, retrieval, evidence extraction, citation checking, and deciding when to withhold a claim. The runnable example starts after planning. It holds candidate retrieval fixed, compares two ways of counting candidate support, and checks a small fictional corpus before rendering an answer.

Building on the tool-use and ReAct foundations from ReAct Pattern: Interleaving Reasoning and Action for LLM Agents and Agent Architectures: Control Loops, State & Planning, and on the retrieval machinery from Dense Retrieval: Semantic Search & Bi-Encoder Implementation and Reranking: Cross-Encoders for Precise Information Retrieval, we now zoom in on the research-specific layer that turns a general agent loop into something a fact-checker could trust. The general loop already tells us how an agent reasons and acts. What is missing is the discipline that makes those actions accountable. That discipline decides which sources count, how much each counts for, and what the agent is allowed to say when the evidence runs out.

Why deep research is not just RAG

A vanilla RAG system answers the question "What is the boiling point of tungsten?" well. The query has one intent, one or two relevant documents suffice, and a single retrieval call returns them. The retrieved passage probably contains the number, so the generator copies it. A deep-research question looks different: "How have different jurisdictions regulated automated decision-making in hiring over the past five years, and where is the evidence still thin?" That question has multiple sub-questions (which jurisdictions, what counts as automated decision-making, what time window), the evidence is scattered across regulatory filings, law-firm summaries, academic papers, and news, the sources disagree, and the honest answer may end with "the evidence is thin for these specific countries." No single retrieval call can return the answer, because the answer is not a passage that exists somewhere; it is a synthesis assembled from many partial passages, some of which conflict.

Four structural differences separate deep research from single-shot RAG.

Search is a loop, not a function call. The agent issues a query, reads results, learns vocabulary (statute names, agency acronyms, technical terms), reformulates, and searches again. Early searches are exploratory, meant to map the territory. Later searches are targeted, meant to close specific gaps. The key point is that the later queries could not have been written up front: the agent only knows to search for "Audit Rule 14 penalties" after reading that Audit Rule 14 exists. This dependency between what you learn and what you ask next is exactly what a single-pass pipeline cannot represent. This is the ReAct loop from earlier, specialized to information retrieval: reason about what you still need, act by searching, observe what came back, and decide whether you are done.

Source selection is a decision, not a ranking. A retriever returns a ranked list; the agent must decide which sources to trust. A marketing blog and a regulatory filing are both "relevant" to a query about AI hiring laws, but only one is authoritative. Relevance answers "does this document talk about the topic?" Trustworthiness answers "should I believe what it says?" The two are different questions, and a relevance score cannot stand in for the second. Source quality has several dimensions: publisher authority, recency, methodological transparency, and, perhaps most subtly, independence from other sources in the evidence set.

Evidence must be extracted and verified, not just concatenated. Dropping six full documents into the context window and asking for a synthesis invites subtle misattribution. A long context gives the model many sentences to draw from and no way to track which sentence supported which part of its output. The agent needs to isolate the specific verifying sentence for each claim, preserve its exact boundaries, and check that the claim is entailed by that sentence. This claim-to-evidence ledger is the backbone of citation integrity.

The answer needs an uncertainty story. When the evidence for a claim is thin, contradictory, or absent, the correct behavior is often to abstain on that claim (or on the whole question) rather than to confabulate. Abstention is a first-class feature, not a failure mode. A confident wrong answer and a hedged correct answer look the same to a fluency-based evaluation. That is why the uncertainty story must be explicit in the trace rather than implicit in the prose tone.

The retrieval and generation metrics discussed in RAG Evaluation: Metrics for Retrieval and Generation Quality can be evaluated alongside trace-level measurements. One retrieval pass and a fixed context cannot show which follow-up searches the system chose. Deep-research quality is a property of a whole trace: the queries, the sources, the extraction, the synthesis, the citations, and the abstentions. You cannot score it by looking at any one artifact in isolation. A trace is sound when every one of its stages did its job and the relationships between the stages are verifiable.

Deep-research agent

A language-model-driven system that answers an open-ended information need through an iterative loop of query planning, multi-source retrieval, source selection and quality assessment, evidence extraction with exact quote boundaries, claim-level synthesis with attached citations, and a rule for when to abstain, producing a reproducible research trace as output in addition to the answer.

The anatomy of a deep-research trace

Before writing a single line of code, it helps to name the artifacts a deep-research agent produces. Every design decision downstream depends on being able to inspect and audit these. Naming the artifacts first is a form of specification. Once we know exactly what a trace contains, the pipeline is just the machinery that fills in each artifact correctly.

  • Question: the user's information need, ideally normalized enough to be decomposable.
  • Sub-questions: the decomposition of the question into independently answerable pieces.
  • Search queries: every query issued, in order, with the timestamp and tool used.
  • Retrieved documents: the raw results of each search, with the rank and any snippets.
  • Selected sources: the subset of retrieved documents that were actually read, with a quality score and reason for inclusion.
  • Evidence spans: exact quoted passages from selected sources that bear on a claim, with character offsets into the source.
  • Claims: atomic factual assertions, each linked to one or more evidence spans.
  • Citation checks: whether each evidence span is verbatim in its source (existence), and whether the source actually supports the claim (support).
  • Abstentions: claims or sub-questions where evidence was insufficient, with a reason.
  • Answer: the final prose, with inline citation markers referring to evidence spans.

In an append-only trace, store a new revision while retaining the earlier actions and claims. Reproducing it also requires the archived source bytes, queries, and versioned retriever. This notebook keeps its intermediate objects in memory; a deployment would need an append-only store and access controls.

A quick word on terminology, since it overlaps with things we already know. In RAG Prompt Engineering: Context Placement & Citation Strategies we saw how to prompt a generator to cite context chunks. That technique produces inline citations like "[[3]]" that point into a provided context block. Deep-research citations are similar in form but stricter in semantics: each citation points to a specific evidence span with verified exact boundaries, and the system enforces that every factual claim carries at least one. The difference is the difference between a footnote a student adds to look diligent and a footnote a fact-checker can follow to a specific sentence on a specific page. The citation format is the trivial part. Verifying that each citation is warranted is where the design effort goes.

Planning: from question to sub-questions

The first intellectual act of a research agent is decomposition. "How have jurisdictions regulated automated decision-making in hiring?" is not directly answerable by a search. A single passage may cover just one jurisdiction or issue. But "What did Cedar City's fictional Audit Rule 14 require?" is answerable. There is likely a document, a statute, or an analysis that says so directly. The planner converts the user's question into a small set of sub-questions that are jointly sufficient to answer the main question and independently answerable by retrieval. "Jointly sufficient" means the union of the sub-answers addresses the whole question. "Independently answerable" means each sub-question, on its own, corresponds to a focused search.

Planning strategies range from fully manual (a human writes the sub-questions) through prompted decomposition (the LLM is asked to enumerate sub-questions) to dynamic planning (the agent generates sub-questions iteratively, letting early findings drive later ones). The first is reliable but expensive and does not scale. The second is cheap but static, and a static plan cannot adapt to what retrieval reveals. The third is the most capable and the most complex, because it requires the agent to reason about its own coverage gaps. For a handbook, the important insight is that decomposition determines the ceiling on what can be answered. If the planner never generates the sub-question "did any jurisdiction outside the US adopt similar rules?," no amount of thorough synthesis will produce a comparative answer. Retrieval can only find what the queries ask for.

A good sub-question for research has three properties:

  1. Atomic: it asks for exactly one fact or one tight cluster of facts. Atomicity is what makes a sub-question independently verifiable. A compound question cannot be cleanly judged supported or unsupported.
  2. Retrieval-conditioned: it is phrased in the vocabulary a source would use, not the vocabulary a human would use conversationally. (This is where the vocabulary mismatch problem we saw in subword vocabulary mismatch reappears at the agent level.) A user asks "do companies have to check their hiring AI for bias?" A regulation says "bias audit of automated employment decision tools." The second phrasing retrieves; the first does not.
  3. Falsifiable: there exists evidence that could, in principle, answer it. "Is AI hiring law good?" is not a research sub-question. "What penalties does Audit Rule 14 impose on violators?" is. A question with no possible evidence anchor can never be closed, and it will burn budget indefinitely.

We can formalize planning as choosing a set of sub-questions Q={q1,…,qn}Q = \{q_1, \dots, q_n\} that maximize expected coverage of the intended information need I\mathcal{I} minus a budget penalty:

Q∗=arg⁡max⁡Q  E[ Coverage(Q,I) ]⏟answer value−λ⋅Cost(Q)⏟searches×tokens−μ⋅Redundancy(Q)⏟overlap between sub-questionsQ^* = \arg\max_{Q} \; \underbrace{\mathbb{E}\big[\,\text{Coverage}(Q, \mathcal{I})\,\big]}_{\text{answer value}} - \lambda \cdot \underbrace{\text{Cost}(Q)}_{\text{searches} \times \text{tokens}} - \mu \cdot \underbrace{\text{Redundancy}(Q)}_{\text{overlap between sub-questions}}

where:

  • QQ: the candidate set of sub-questions being scored
  • Coverage(Q,I)\text{Coverage}(Q, \mathcal{I}): how much of the intended information need I\mathcal{I} the sub-questions jointly cover
  • Cost(Q)\text{Cost}(Q): the search and token budget consumed by issuing the sub-questions
  • Redundancy(Q)\text{Redundancy}(Q): overlap between sub-questions that wastes budget without adding information
  • λ\lambda: weight on search cost
  • μ\mu: weight on redundancy
  • Q∗Q^*: the sub-question set that maximizes the objective, i.e., the selected plan

Raising the cost weight favors lower total cost among candidate optima, with the other terms fixed. Lower total cost can come from cheaper retrieval or fewer tokens as well as fewer questions.

In practice we do not solve this exactly. Coverage is not directly observable before we search, so we use heuristics. Ask the planner for 3 to 7 sub-questions, deduplicate near-identical ones, and rely on iterative re-planning as evidence accumulates. If the plan did not anticipate something, the synthesis step notices and triggers additional sub-questions. The Redundancy term matters because LLM-written planners love to generate high-overlap sub-questions ("what does Audit Rule 14 require?" and "what are the obligations under Cedar City's fictional hiring rule?") that consume budget without adding information. Deduplication catches the obvious cases; the subtler cases surface at retrieval time as repeated results, which then trigger a re-plan.

Source selection: quality, relevance, and independence

Once the agent has a sub-question and a set of retrieved documents, it must decide which documents to actually read. This is a distinct step from retrieval. Retrieval returns everything that might be relevant; selection chooses what to trust. The distinction matters because a naïve retriever, given the query "AI hiring regulation," will return a vendor's marketing page, an SEO content farm, and the actual regulatory filing with roughly equal relevance scores. Relevance measures topical match. Trust measures whether the content is a reliable basis for an assertion.

We score each candidate source on four axes.

  • Authority: is the publisher credentialed for this claim? Regulatory filings, peer-reviewed papers, and official statistics score high; marketing pages and content-farm summaries score low.
  • Recency: is the document fresh enough for the claim's update frequency? A legal analysis from 2019 may be stale for a 2025 question. Freshness requirements are claim-dependent, not universal. An article on the text of a statute enacted in 2021 stays current, while an article on enforcement activity in the same statute does not.
  • Methodological transparency: does the source show its work? Empirical claims with stated sample and method beat top-of-head assertions.
  • Independence: is this source distinct evidence from other sources, or does it derive from the same underlying origin? Two articles citing the same press release are one source, not two.

The independence dimension is the one most research agents get wrong, and it is the one we will spend the most time on because it directly affects the apparent support for a claim. If three sources all assert claim cc, naïve counting says "three pieces of evidence." But if all three sources trace to the same primary press release, the evidence is a single observation. Treating dependent sources as independent is a form of double counting, and it is one of the most common ways confident-sounding research reports turn out to be wrong. The mechanism is easy to miss because the raw count looks impressive. "Three independent outlets report" is a phrase that sounds like corroboration but may describe one observation reported three times.

Evidence independence

Two evidence sources are independent for a claim if a mistake in one would not mechanically propagate to the other. Two articles citing the same press release are not independent. A primary filing and an independent audit of that filing are.

Independence is a claim-level property, not a source-level property: two sources may be independent on claim c1c_1 and dependent on claim c2c_2.

To formalize the count, for a claim cc with evidence set Ec={e1,…,em}E_c = \{e_1, \dots, e_m\} where each eie_i comes from a document d(ei)d(e_i), we build an independence partition. This is a partition of EcE_c into groups such that sources within a group share an upstream origin and are counted once. The effective evidence count is the number of groups, not the number of documents:

∣Ec∣indep=∣{group:group∈Partition(Ec)}∣|E_c|_{\text{indep}} = \Big| \{ \text{group} : \text{group} \in \text{Partition}(E_c) \} \Big|

where:

  • EcE_c: the evidence set for claim cc
  • Partition(Ec)\text{Partition}(E_c): the partition of EcE_c into groups that share an upstream origin
  • ∣Ec∣indep|E_c|_{\text{indep}}: the number of such groups, counting each upstream origin once

Counting recorded roots helps avoid double counting. The claim and exact quotes still need semantic review, and uncertainty can remain about provenance and source quality. Three roots do not automatically outweigh one decisive source.

Evidence extraction: exact quote boundaries

Once a document is selected, the agent must isolate the specific passage that bears on the claim. This is harder than it sounds because there is a strong temptation to paraphrase the source into a crisp evidence sentence that matches what we want it to say. This is exactly the mechanism by which a citation can look correct and be wrong. The paraphrase is faithful in gist but omits the qualifier ("in three of five jurisdictions studied") that flips the claim's meaning. The paraphrase then gets quoted as if it were the source, and the qualifier is gone from every downstream artifact.

The right discipline is to keep evidence spans verbatim. An evidence span ss is a contiguous substring of a source document dd, identified by character offsets [a,b)[a, b) such that the substring of dd from aa (inclusive) to bb (exclusive) equals ss:

d[a:b]=sd[a{:}b] = s

where:

  • ss: the quoted evidence substring
  • dd: the source document text
  • aa: the start character offset of the span
  • bb: the end character offset of the span (exclusive)

Every claim points into evidence, not to a paraphrase. The offset discipline gives us two useful checks:

  1. Existence: is the span actually present in dd at offsets [a,b)[a, b)? This catches hallucinated quotes.
  2. Sufficiency: does ss entail the claim? This is a semantic check, done either by a separate verifier model or by a human reviewer.

Existence is an exact quote check against the chosen snapshot. Comparing local offsets alone cannot detect an edit outside the quote. The code below also compares a digest of the document body. A separate semantic review asks whether the quote, in context, supports the claim.

A third check appears at synthesis time: citation attribution. Given the final answer text and each claim's associated evidence span, does the paragraph actually use that evidence? An LLM can produce a paragraph that cites a span while discussing something else the span does not cover. This is harder to automate than existence and is often where a human-in-the-loop step (from the Human Approval and Control Boundaries chapter, arriving shortly) is warranted for high-stakes reports. The three checks form a rough hierarchy of cost. Existence checks the source digest, the character bounds, and the text at those bounds. Sufficiency needs a model or a person, and attribution needs reading the answer in context. Spending the expensive checks only where they matter is what keeps the pipeline affordable.

Synthesis with enforced citations

Synthesis is where the model writes prose. The critical requirement is that every factual claim carries a citation, and every citation refers to a real evidence span. A common failure mode is citation laundering. The model writes fluent prose and then sprinkles citation markers at sentence ends without actually mapping each claim to any specific evidence. The output looks cited, but the citations are decorative. This failure is common because it is easy for a language model. Citing is a token-level behavior that can be pattern-completed without any link to the underlying evidence.

There are two ways to enforce citation integrity during synthesis:

  • Post-hoc verification. Let the model write freely, then run a verifier that parses the output, extracts each claim, matches it to evidence spans, and rejects the answer if any claim lacks support. Rejected answers are re-synthesized with stricter instruction, or a human is called in.
  • Constrained decoding. Constrain the decoder (see Constrained Decoding: Structured LLM Output) to emit citation markers at structurally required positions. This is more complex and not typically necessary if the post-hoc path is robust.

For the demonstration, we start with a prepared list of atomic claims and audit the candidate evidence before rendering. It is simpler to reason about, simpler to audit, and it degrades more gracefully. Instead of enforcing an unnatural generation grammar, the prepared claims stand in for the draft. The verifier output becomes part of the trace, so any downstream reader can see which claims were accepted, which were discarded, and why. A rejected answer is not a wasted run; it is a trace artifact that tells the next attempt what not to say.

The example begins with a fixed list of claims. It locates candidate spans, checks their exact text and recorded document snapshot, then filters them against a hand-reviewed quote map before rendering. An application with arbitrary generated prose would also need to extract claims and verify their attribution.

Uncertainty and abstention

The hardest question in deep research is when is it time to stop? An agent that keeps searching indefinitely burns budget. An agent that stops early returns an under-evidenced answer. The conservative move, and the one this chapter advocates, is to make abstention a first-class output state. Abstention means the agent explicitly reports that it could not establish a claim at the required confidence, rather than silently omitting it or substituting a guess.

Abstention

To measure confidence calibration, collect labeled claims and compare confidence with the observed frequency of correctness among claims at that confidence. Coverage is the fraction of claims accepted. Selective risk is the error rate among those accepted. Those quantities are distinct from calibration: a predictor can accept only high-accuracy cases and still attach low or high confidence values. Here, the abstention rule uses a heuristic score and explicit gates.

No located evidence, conflicting evidence, and weak evidence call for different handling. Report a missing observation as missing. When credible sources conflict, a human-reviewed answer can present both positions with citations. The toy renderer withholds a claim flagged by its simple wording heuristic and does not synthesize a balanced account.

The wording heuristic scans lexical matches for a mix of spans with and without negation markers. It can miss a substantive conflict or flag an unrelated negation. Treat it as a prompt to inspect the quotes.

Confusing "absent evidence" with "evidence of absence" is one of the most damaging errors a research agent can make. If no source discusses Argentina's hiring rules, that is compatible with the rules being nonexistent and with the corpus simply not covering Argentine regulation. The claim "Argentina has no AI hiring rules" requires evidence of the absence (e.g., a survey article explicitly stating so), not just silence. The distinction is logically strict. Absence of evidence is evidence of absence only when the evidence should have appeared if it existed. In a small or biased corpus, it often would not have appeared.

A worked example corpus

To make all of this concrete we need a small, inspectable corpus we control. We will not use real documents, because we want to be able to inject carefully crafted dependencies (a press release and two derived articles) and observe that the agent correctly treats them as one source. Everything below uses a synthetic corpus, set in a fictional city. Each document has an id, a publisher, a title, a body, and a derives_from field that names the document this one is downstream of (empty for primary sources).

The corpus version for this revision is cedar_city_synthetic_v2. Each span stores a SHA-256 digest of the complete UTF-8 document body, and the quote checker recomputes it when checking the range. If the body changes outside the range, the same offsets alone still match but the old span fails this combined check. Preserve the stored digest in an independently protected record when using this to detect edits.

Implementation

We will build the pipeline as a sequence of small, inspectable stages. The setup imports standard libraries for text handling, retrieval, and plotting. We use scikit-learn for TF-IDF (recall TF-IDF), numpy for scoring, and a small helper to make evidence extraction exact.

PythonIn [2]
CollapseExpand
import re
from dataclasses import dataclass, field
from hashlib import sha256
from typing import Optional

import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

The dataclasses below give us a strict shape for every trace artifact. Treating these as rigid schemas (not dicts) is important for reproducibility. A dict with mutated keys cannot be diffed reliably against future runs. A rigid schema also makes the audit step mechanical. A verifier can walk fixed fields instead of probing for whatever keys happened to be present.

PythonIn [3]
CollapseExpand
@dataclass
class Document:
    doc_id: str
    publisher: str
    title: str
    body: str
    # empty state 'primary'; otherwise the doc id of the upstream document
    derives_from: Optional[str] = None
    authority: float = 0.5  # 0..1 heuristic quality signal


@dataclass
class Source:
    doc_id: str
    score: float
    bank: str  # 'primary', 'secondary', 'derived'


@dataclass
class EvidenceSpan:
    doc_id: str
    span: str
    start: int
    end: int
    source_sha256: str | None = None


@dataclass
class Claim:
    claim_id: str
    text: str
    evidence: list = field(default_factory=list)
    supported: bool = False
    independent_count: int = 0

These dataclasses declare fields, and Python type annotations do not validate arbitrary values. Each EvidenceSpan stores verbatim text, character offsets, and the digest of the body from which it was extracted.

Building the synthetic corpus

All six documents below are fictional. Cedar City, its rule, the publishers and the reported enforcement case are example data. The notice and its two descendants give us a known chain to compare with separate source records.

PythonIn [4]
CollapseExpand
CORPUS_VERSION = "cedar_city_synthetic_v2"

docs = [
    Document(
        doc_id="rule14-text",
        publisher="Cedar City Council",
        title="Cedar City Audit Rule 14",
        body=(
            "Cedar City Audit Rule 14 requires employers to conduct annual bias "
            "audits of automated employment decision tools. Employers must "
            "publish audit results and notify candidates "
            "residing in Cedar City at least ten business days before use. "
            "Violations are subject to civil penalties of up to $1,500 per "
            "occurrence, with a maximum of $3,000 for subsequent violations."
        ),
        derives_from=None,
        authority=0.95,
    ),
    Document(
        doc_id="rule14-notice",
        publisher="Cedar City Audit Office",
        title="Audit Office notice",
        body=(
            "The Cedar City Audit Office adopted rules "
            "implementing Audit Rule 14 in 2023. The rules clarify that bias "
            "audits must be performed by an independent auditor and that "
            "audit results must be published. The rules do not address small "
            "employers exempt under state law."
        ),
        derives_from=None,
        authority=0.92,
    ),
    Document(
        doc_id="news-a",
        publisher="City Policy News",
        title="Cedar City finalizes AI hiring rules",
        body=(
            "Cedar City has finalized its rules on AI in hiring. According "
            "to the Cedar City Audit Office, employers "
            "must publish audit results. Bias audits must be performed by an independent auditor. The "
            "rules clarify existing obligations under Audit Rule 14."
        ),
        derives_from="rule14-notice",
        authority=0.55,
    ),
    Document(
        doc_id="blog-b",
        publisher="HR Tech Insights",
        title="What the Cedar City rules mean",
        body=(
            "Employers in Cedar City now face a clear audit obligation. "
            "Reports from City Policy News confirm that audit results must "
            "be published. Bias audits must be performed by an independent auditor. "
            "Small employers still exempt under state law are unaffected."
        ),
        derives_from="news-a",
        authority=0.30,
    ),
    Document(
        doc_id="analysis-c",
        publisher="Institute for Work Research",
        title="Comparative review of hiring law",
        body=(
            "An independent academic review of Audit Rule 14 found that "
            "published audit summaries provide a useful public record. The "
            "review noted the ten business day candidate notice requirement "
            "as a distinctive feature with no direct analogue in EU "
            "framework."
        ),
        derives_from=None,
        authority=0.85,
    ),
    Document(
        doc_id="filing-d",
        publisher="Cedar City Review Board",
        title="Enforcement docket excerpt",
        body=(
            "In Matter of North Pier Staffing, a fictional employer, the tribunal imposed civil penalties "
            "under Audit Rule 14. The tribunal's opinion reasoned that "
            "publication of audit summaries is a core duty of the law and "
            "rejected arguments that the auditor independence provision is "
            "guidance rather than rule."
        ),
        derives_from=None,
        authority=0.88,
    ),
]

We can inspect the corpus quickly to confirm the pattern of dependencies. Three documents (rule14-notice, news-a, blog-b) chain off each other, all ultimately descended from the primary regulatory record.

PythonIn [5]
CollapseExpand
docs_df = pd.DataFrame(
    [
        {
            "doc_id": d.doc_id,
            "publisher": d.publisher,
            "authority": d.authority,
            "derives_from": d.derives_from or "-",
        }
        for d in docs
    ]
)
ConsoleOut [6]
CollapseExpand
Corpus version: cedar_city_synthetic_v2
Documents: 6

       doc_id                   publisher  authority  derives_from
  rule14-text          Cedar City Council       0.95             -
rule14-notice     Cedar City Audit Office       0.92             -
       news-a            City Policy News       0.55 rule14-notice
       blog-b            HR Tech Insights       0.30        news-a
   analysis-c Institute for Work Research       0.85             -
     filing-d     Cedar City Review Board       0.88             -

Six documents, three of them on a single dependency chain. If we later counted "three sources confirm independent auditor rule" as three independent observations, we would be triple-counting a single press release.

The chart groups the three documents that share the recorded origin rule14-notice. The corpus records above give the order of the parent links. The visualization reads the precomputed origin for each document.

PythonIn [7]
CollapseExpand
# Resolve each document's transitive origin (root of its derivation chain).
# Tie-breaking: chains are followed to their unique root; no ties possible.
docs_by_id = {d.doc_id: d for d in docs}


def resolve_origin(doc_id: str) -> str:
    seen = set()
    cur = docs_by_id[doc_id]
    while cur.derives_from is not None:
        if cur.doc_id in seen:
            raise ValueError("cycle")
        seen.add(cur.doc_id)
        cur = docs_by_id[cur.derives_from]
    return cur.doc_id


provenance_df = pd.DataFrame(
    [
        {
            "doc_id": d.doc_id,
            "origin": resolve_origin(d.doc_id),
            "authority": d.authority,
            "is_primary": d.derives_from is None and d.authority >= 0.8,
        }
        for d in docs
    ]
)
VisualizationOut [9]
CollapseExpand
Six labeled documents in four origin rows, with the news and blog articles in the same row as the Audit Office notice.
Documents grouped by their recorded transitive origin. The Audit Office notice and its two derivative articles (news-a and blog-b) share the same origin row, showing a shared root without ordering intermediate parents, while the rule text, academic review, and enforcement filing each form their own origin.

A retrieval baseline

Retrieval is not the star of this chapter, but we need a working retriever so we can focus on what comes after. We use a TF-IDF retriever with cosine similarity because it is deterministic, inspectable, and free of neural network variance. Determinism matters here: it means that any difference between two traces comes from the strategy, not from retrieval noise. A larger corpus may instead use the dense retriever described in Dense Retrieval: Semantic Search & Bi-Encoder Implementation. Either retriever can return records with source IDs and scores.

PythonIn [10]
CollapseExpand
vectorizer = TfidfVectorizer(stop_words="english", ngram_range=(1, 2))
doc_matrix = vectorizer.fit_transform([d.body for d in docs])


def retrieve(query: str, k: int = 4) -> list:
    """Return top-k doc_ids with their cosine scores."""
    q = vectorizer.transform([query])
    scores = cosine_similarity(q, doc_matrix).ravel()
    order = np.argsort(-scores, kind="stable")[: max(0, k)]
    return [(docs[i].doc_id, float(scores[i])) for i in order]


# smoke test
for doc_id, score in retrieve(
    "independent auditor bias audit publication", k=4
):
    print(f"{score:.3f}  {doc_id}")

The retriever returns a ranked list sorted by cosine similarity. The next step annotates those same top-k candidates with a metadata bucket without reranking or discarding them according to authority.

Source selection with a bank classifier

The bucket uses the fixture metadata. A document with an upstream pointer is labeled derived. Among roots, those with assigned authority at least 0.8 are labeled primary and the others secondary. These labels express the toy rule and should not be read as determinations of scholarly provenance.

The classifier is not perfectly accurate on real corpora. But because it operates by explicit rule, its decisions are visible in the trace, and errors are debuggable. Compare this to a neural classifier whose failure cases are opaque. A rule-based classifier can also be overridden by a human reviewer without retraining anything.

PythonIn [11]
CollapseExpand
def classify_bank(doc: Document) -> str:
    if doc.derives_from is None:
        return "primary" if doc.authority >= 0.8 else "secondary"
    return "derived"


def transitive_origin(doc_id: str) -> str:
    """Follow a stable document ID, and reject a cyclic origin path."""
    by_id = {doc.doc_id: doc for doc in docs}
    seen = set()
    current = doc_id
    while by_id[current].derives_from is not None:
        if current in seen:
            raise ValueError(f"cycle in derivation chain at {current}")
        seen.add(current)
        current = by_id[current].derives_from
    return current


def select_sources(query: str, k: int = 5) -> list:
    """Retrieve, score, and classify candidate sources."""
    selected = []
    for doc_id, score in retrieve(query, k=k):
        doc = next(d for d in docs if d.doc_id == doc_id)
        bank = classify_bank(doc)
        selected.append(Source(doc_id=doc_id, score=score, bank=bank))
    return selected
ConsoleOut [12]
CollapseExpand
       doc_id  score    bank
rule14-notice  0.315 primary
       news-a  0.248 derived
     filing-d  0.214 primary
       blog-b  0.145 derived
   analysis-c  0.143 primary

The source rows preserve retrieval order. The news article and blog trace to the Audit Office notice in the fixture; the rule text is a separate root. The origin chart groups documents by their root and does not show intermediate parent order.

Evidence extraction with exact offsets

Evidence extraction is where we insist on exact quote boundaries. Given a selected document and a claim-like query, we locate the sentence(s) that best match, retain their exact character offsets, and refuse to paraphrase. The offsets give us an existence check doc.body[start:end] == span that is exact and cheap.

PythonIn [13]
CollapseExpand
SENT_PATTERN = re.compile(r"(?<=[.!?])\s+")


def split_sentences_with_offsets(text: str) -> list:
    """Split on sentence boundaries, tracking character offsets."""
    offsets = []
    cursor = 0
    for m in SENT_PATTERN.finditer(text):
        end = m.start()
        offsets.append((cursor, end))
        cursor = m.end()
    if cursor < len(text):
        offsets.append((cursor, len(text)))
    return [(text[a:b], a, b) for a, b in offsets if text[a:b].strip()]


def extract_evidence(query: str, doc: Document, top_n: int = 1) -> list:
    """Best matching sentence(s), verbatim, with offsets."""
    sents = split_sentences_with_offsets(doc.body)
    if not sents:
        return []
    sent_vecs = vectorizer.transform([s for s, _, _ in sents])
    q_vec = vectorizer.transform([query])
    scores = cosine_similarity(q_vec, sent_vecs).ravel()
    order = [i for i in np.argsort(-scores, kind="stable") if scores[i] > 0][
        : max(0, top_n)
    ]
    spans = []
    snapshot = sha256(doc.body.encode("utf-8")).hexdigest()
    for i in order:
        s, a, b = sents[i]
        spans.append(
            EvidenceSpan(
                doc_id=doc.doc_id,
                span=s,
                start=a,
                end=b,
                source_sha256=snapshot,
            )
        )
    return spans
ConsoleOut [14]
CollapseExpand
[ 78,198)  'The rules clarify that bias audits must be performed by an independent auditor and that audit results must be published.'
[  0, 77)  'The Cedar City Audit Office adopted rules implementing Audit Rule 14 in 2023.'

The assertion verifies that the returned text matches its stored half-open range. A range may be internally consistent while selecting the wrong sentence, so review the selected boundaries and semantic context separately.

Claim-to-evidence ledger

The candidate ledger stores exact quotes that clear the lexical overlap filter and counts their recorded roots. A later allow-list supplies semantic approval for this fixture.

We define support as a simple bag-of-content-words overlap for the demonstration, but in production you would replace this with an NLI cross-encoder (recall Sentence Meaning and Natural Language Inference). The independence computation, on the other hand, is not something we swap out: it is a structural property of the corpus, and the transitive-closure algorithm below is the right one.

PythonIn [15]
CollapseExpand
STOP = set(vectorizer.get_stop_words() or set())
LEXICAL_THRESHOLD = 0.60


def content_tokens(s: str) -> set:
    return {t for t in re.findall(r"[a-z0-9]+", s.lower()) if t not in STOP}


def lexical_match(
    span: str, claim: str, threshold: float = LEXICAL_THRESHOLD
) -> bool:
    """Candidate filter by fraction of claim tokens present in the span."""
    claim_tokens = content_tokens(claim)
    if not claim_tokens:
        return False
    span_tokens = content_tokens(span)
    overlap = len(claim_tokens & span_tokens) / len(claim_tokens)
    return overlap >= threshold


def span_exists(span: EvidenceSpan) -> bool:
    doc = next((doc for doc in docs if doc.doc_id == span.doc_id), None)
    return (
        doc is not None
        and span.source_sha256 == sha256(doc.body.encode("utf-8")).hexdigest()
        and 0 <= span.start < span.end <= len(doc.body)
        and doc.body[span.start : span.end] == span.span
    )


def independent_count(spans: list) -> tuple:
    """Number of recorded provenance roots and their span ids."""
    origins = {}
    for sp in spans:
        origin = transitive_origin(sp.doc_id)
        origins.setdefault(origin, []).append(sp.doc_id)
    return len(origins), origins


def build_ledger(claim_text: str, candidate_spans: list) -> Claim:
    cid = sha256(claim_text.encode()).hexdigest()
    supported_spans = [
        sp
        for sp in candidate_spans
        if span_exists(sp) and lexical_match(sp.span, claim_text)
    ]
    n_indep, origins = independent_count(supported_spans)
    return Claim(
        claim_id=cid,
        text=claim_text,
        evidence=supported_spans,
        supported=n_indep >= 1,
        independent_count=n_indep,
    )

Now we can run a small demonstration end-to-end. We build five claims derived from the regulatory corpus, gather candidate spans from selected sources for each, and produce a ledger.

PythonIn [16]
CollapseExpand
claims_to_check = [
    "audits must be performed by an independent auditor",
    "audit results must be published",
    "candidates residing in Cedar City must be notified at least ten business days before use",
    "civil penalties apply to all AI hiring tools",
    "EU framework requires an equivalent audit obligation",
]

selected = select_sources(
    "Audit Rule 14 obligations independent audit publication candidate notice",
    k=6,
)

all_spans = []
for src in selected:
    doc = next(d for d in docs if d.doc_id == src.doc_id)
    all_spans.extend(
        extract_evidence(
            "independent auditor bias audits publication candidate notice",
            doc,
            top_n=2,
        )
    )

ledger = [build_ledger(c, all_spans) for c in claims_to_check]
ConsoleOut [17]
CollapseExpand
                                                  claim  has_candidate  n_spans  n_indep
     audits must be performed by an independent auditor           True        3        1
                        audit results must be published           True        2        2
candidates residing in Cedar City must be notified at l          False        0        0
           civil penalties apply to all AI hiring tools          False        0        0
   EU framework requires an equivalent audit obligation          False        0        0

Compare the matched spans and recorded roots on each row. A single root can account for several documents and for multiple spans within a document.

Let's make the independence accounting visible. We can tabulate, for each origin, which document ids contributed spans for the independent-auditor claim.

PythonIn [18]
CollapseExpand
def origin_table(claim: Claim) -> pd.DataFrame:
    _, origins = independent_count(claim.evidence)
    rows = []
    for origin, contribs in origins.items():
        for c in contribs:
            rows.append(
                {
                    "claim": claim.text[:40],
                    "contributing_doc": c,
                    "origin_doc": origin,
                }
            )
    return pd.DataFrame(rows)


audit_claim = ledger[0]
origin_df = origin_table(audit_claim)
ConsoleOut [19]
CollapseExpand
Claim: audits must be performed by an independent auditor

                                   claim contributing_doc    origin_doc
audits must be performed by an independe           news-a rule14-notice
audits must be performed by an independe    rule14-notice rule14-notice
audits must be performed by an independe           blog-b rule14-notice

The table prints one row per matched span for the independent-auditor claim. Notice how the notice and both derivative articles share the same source root.

The table printed above is textual; the bar chart here makes the gap between raw citations and independent witnesses quantitative. For every claim in the ledger we plot two bars: the number of evidence spans found, and the number of independent origins those spans reduce to.

PythonIn [20]
CollapseExpand
indep_gap_df = pd.DataFrame(
    [
        {
            "claim_short": f"C{ledger.index(c) + 1}",
            "n_raw": len(c.evidence),
            "n_indep": c.independent_count,
            "laundered": max(len(c.evidence) - c.independent_count, 0),
        }
        for c in ledger
    ]
)
VisualizationOut [21]
CollapseExpand
Grouped bars comparing raw span counts to independent origin counts per claim.
Raw evidence spans versus distinct recorded origins for each claim in the ledger. The bars show how many matching spans were found and how many independent origins they reduce to, revealing where raw citation counts overstate independent corroboration because the gap includes multiple matches within one document and matches across documents that share a root.

Citation integrity checks

The first audit checks exact quote existence and records whether the quote passed the lexical candidate filter. The semantic audit below is a separate step. It uses manually approved exact quotes in this closed fixture.

PythonIn [22]
CollapseExpand
def check_existence(claim: Claim) -> tuple:
    problems = []
    for sp in claim.evidence:
        if not span_exists(sp):
            problems.append((sp.doc_id, sp.start, sp.end))
    return len(problems) == 0, problems


def check_lexical_match(claim: Claim) -> bool:
    if not claim.evidence:
        return False
    return any(lexical_match(sp.span, claim.text) for sp in claim.evidence)


def audit_claims(claims: list) -> pd.DataFrame:
    rows = []
    for c in claims:
        exists, probs = check_existence(c)
        suff = check_lexical_match(c)
        rows.append(
            {
                "claim": c.text[:50],
                "exists": exists if c.evidence else None,
                "lexical_match": suff,
                "n_indep": c.independent_count,
                "verdict": (
                    "candidate"
                    if exists and suff
                    else "no match"
                    if exists and not suff
                    else "fail"
                ),
            }
        )
    return pd.DataFrame(rows)


audit_df = audit_claims(ledger)
ConsoleOut [23]
CollapseExpand
                                             claim exists  lexical_match  n_indep   verdict
audits must be performed by an independent auditor   True           True        1 candidate
                   audit results must be published   True           True        2 candidate
candidates residing in Cedar City must be notified   None          False        0  no match
      civil penalties apply to all AI hiring tools   None          False        0  no match
EU framework requires an equivalent audit obligati   None          False        0  no match

A present quote can fail the lexical candidate filter. If no span was stored, the existence column shows no check rather than a successful check. A lexical match alone cannot establish entailment. Negation, quantities, scope, and dates require a semantic check.

Comparing budgeted research strategies

Both policies see the same six candidate documents and at most two retrieved sentences per document. The document-count policy requires lexical matches from two distinct documents. The origin-count policy requires lexical matches from two distinct roots in the fixture provenance graph. Each scores a decision to report against the same hand-labeled claim set.

We define the evaluation with a small ground-truth table. For each claim, we specify whether the corpus supports it under a manual reading of the six documents. The strategies differ in what they report, not in what they retrieve.

PythonIn [24]
CollapseExpand
# Hand-labeled ground truth from reading the six documents above.
ground_truth = {
    "audits must be performed by an independent auditor": {
        "true_supported": True,
    },
    "audit results must be published": {
        "true_supported": True,
    },
    "candidates residing in Cedar City must be notified at least ten business days before use": {
        "true_supported": True,
    },
    "civil penalties apply to all AI hiring tools": {
        "true_supported": False,
    },
    "EU framework requires an equivalent audit obligation": {
        "true_supported": False,
    },
}
PythonIn [25]
CollapseExpand
def detect_conflicts(claim_text: str, spans: list) -> list:
    """Fixture probe: identify mixed negation markers among lexical matches."""
    neg_pattern = re.compile(r"\b(no|not|never)\b", re.I)
    matches = [span for span in spans if lexical_match(span.span, claim_text)]
    negative = [span for span in matches if neg_pattern.search(span.span)]
    return negative if 0 < len(negative) < len(matches) else []


def strategy_naive(claims: list) -> pd.DataFrame:
    rows = []
    for c in claims:
        report = len({span.doc_id for span in c.evidence}) >= 2
        rows.append(
            {
                "claim": c.text,
                "reported": report,
                "n_indep": c.independent_count,
            }
        )
    return pd.DataFrame(rows)


def strategy_independence_aware(claims: list) -> pd.DataFrame:
    rows = []
    for c in claims:
        conflicts = detect_conflicts(c.text, c.evidence)
        report = c.independent_count >= 2
        confidence = (
            "high"
            if c.independent_count >= 2
            else "low"
            if c.independent_count == 1
            else "none"
        )
        rows.append(
            {
                "claim": c.text,
                "reported": report,
                "n_indep": c.independent_count,
                "confidence": confidence,
                "conflicts": len(conflicts),
            }
        )
    return pd.DataFrame(rows)


naive_df = strategy_naive(ledger)
aware_df = strategy_independence_aware(ledger)
ConsoleOut [26]
CollapseExpand
Naive strategy:
                                                                                   claim  reported  n_indep
                                      audits must be performed by an independent auditor      True        1
                                                         audit results must be published      True        2
candidates residing in Cedar City must be notified at least ten business days before use     False        0
                                            civil penalties apply to all AI hiring tools     False        0
                                    EU framework requires an equivalent audit obligation     False        0

Independence-aware strategy:
                                                                                   claim  reported  n_indep confidence  conflicts
                                      audits must be performed by an independent auditor     False        1        low          0
                                                         audit results must be published      True        2       high          0
candidates residing in Cedar City must be notified at least ten business days before use     False        0       none          0
                                            civil penalties apply to all AI hiring tools     False        0       none          0
                                    EU framework requires an equivalent audit obligation     False        0       none          0

A policy can render a weaker report by recording where its evidence came from. The difference becomes visible whenever several matching documents share one recorded root.

We look up each candidate claim by its full text in the fixture annotations. An overclaim reports an unsupported claim; an underclaim withholds a supported claim.

PythonIn [27]
CollapseExpand
def nearest_gt(claim_text: str) -> dict:
    """Use the exact preregistered claim text as the fixture key."""
    return ground_truth[claim_text]


def score_strategy(strategy_df: pd.DataFrame) -> dict:
    correct = 0
    overclaims = 0
    underclaims = 0
    unreported_false = 0
    reported_false = 0
    for _, row in strategy_df.iterrows():
        gt = nearest_gt(row["claim"])
        if gt["true_supported"] is None:
            continue
        if gt["true_supported"] and row["reported"]:
            correct += 1
        elif (not gt["true_supported"]) and row["reported"]:
            overclaims += 1
            reported_false += 1
        elif gt["true_supported"] and not row["reported"]:
            underclaims += 1
        elif (not gt["true_supported"]) and (not row["reported"]):
            correct += 1
            unreported_false += 1
    return {
        "correct": correct,
        "overclaims": overclaims,
        "underclaims": underclaims,
        "reported_false": reported_false,
        "unreported_false": unreported_false,
    }


naive_score = score_strategy(naive_df)
aware_score = score_strategy(aware_df)
ConsoleOut [28]
CollapseExpand
          strategy  correct  overclaims  underclaims  reported_false  unreported_false
       naive-count        4           0            1               0                 2
independence-aware        3           0            2               0                 2

The two-document policy marks C1 as a lexical candidate because it has three matching documents. The two-origin policy withholds that candidate because all three share one root. Both comparison rules run before semantic approval. The final answer applies its own hedge rule to verified evidence.

The uncertainty-score decomposition is computed in the next section directly from the ledger, after claim_uncertainty is defined.

Visualizing the two strategies

Labels C1 to C5 follow the order of the five claims in the fixture table. Each claim has two reporting decisions drawn from the same candidate span set. The reference labels were recorded separately from either policy.

PythonIn [29]
CollapseExpand
plot_df = pd.DataFrame(
    [
        {
            "claim_short": f"C{index + 1}",
            "true_supported": annotation["true_supported"],
            "naive_reported": bool(
                naive_df.loc[naive_df["claim"] == claim, "reported"].iloc[0]
            ),
            "aware_reported": bool(
                aware_df.loc[aware_df["claim"] == claim, "reported"].iloc[0]
            ),
        }
        for index, (claim, annotation) in enumerate(ground_truth.items())
    ]
)
VisualizationOut [30]
CollapseExpand
Grouped bar chart comparing naive and independence-aware strategies across five claims with their true-support labels.
Comparison of the two-document policy (left bars) and the two-origin policy (right bars) across five claims. A height of one means the policy reports the claim as supported, and the annotations identify claims the fixture does not support.

These are reporting decisions on a fixed corpus. A zero bar means the policy withheld that claim. The reference annotation is shown independently, so a withheld supported claim stays visible.

Uncertainty scoring and abstention

The uncertainty rule first runs on lexical candidates for inspection. The answer runs it again after semantic approval. The score uses recorded origin count, assigned authority, and a flag from the negation-marker heuristic.

PythonIn [31]
CollapseExpand
EVIDENCE_WEIGHT = 0.4
AUTHORITY_WEIGHT = 0.4
CONFLICT_WEIGHT = 0.2
ASSERT_CUTOFF = 0.35


def max_authority(claim: Claim) -> float:
    if not claim.evidence:
        return 0.0
    return max(
        next(d for d in docs if d.doc_id == sp.doc_id).authority
        for sp in claim.evidence
    )


def claim_uncertainty(claim: Claim, has_conflict: bool) -> dict:
    n = claim.independent_count
    a = max_authority(claim)
    # Score in [0,1]; higher = more uncertain.
    n_score = 1.0 / (1.0 + n)
    a_score = 1.0 - a
    conflict_score = 1.0 if has_conflict else 0.0
    u = (
        EVIDENCE_WEIGHT * n_score
        + AUTHORITY_WEIGHT * a_score
        + CONFLICT_WEIGHT * conflict_score
    )
    if n == 0 or has_conflict:
        label = "abstain"
    elif n == 1:
        label = "hedge"
    elif u < ASSERT_CUTOFF:
        label = "assert"
    else:
        label = "hedge"
    return {
        "claim_id": claim.claim_id,
        "claim": claim.text[:50],
        "n_indep": n,
        "max_auth": round(a, 2),
        "conflict": has_conflict,
        "uncertainty": round(u, 3),
        "label": label,
    }


u_rows = [
    claim_uncertainty(c, bool(detect_conflicts(c.text, c.evidence)))
    for c in ledger
]
u_df = pd.DataFrame(u_rows)
ConsoleOut [32]
CollapseExpand
                                                        claim_id                                              claim  n_indep  max_auth  conflict  uncertainty   label
7c9fd6b4e2a52693397964b390bd1c575a130845aa1ea96a38b891a3c89137d1 audits must be performed by an independent auditor        1      0.92     False        0.232   hedge
35cae509a0a30076eb6ae2c9dfa445772222e9f5c89f8dbbfdbaf87595428206                    audit results must be published        2      0.92     False        0.165  assert
36703c089bd247f268690d3971081490ed209d6df7f9a58a5c5b2dc4912ac1bf candidates residing in Cedar City must be notified        0      0.00     False        0.800 abstain
b45eca72f8aaaa20b086c5b87463f61861d60383a32a66fa98be2b0f135658df       civil penalties apply to all AI hiring tools        0      0.00     False        0.800 abstain
c48564a69b2f573f8695196cfd1907b96cadd239933f35c80d51c9dd09461612 EU framework requires an equivalent audit obligati        0      0.00     False        0.800 abstain

The score is a weighted heuristic. For origin count n, maximum assigned authority a and conflict flag c, the three terms are 0.4/(1+n), 0.4(1−a) and 0.2c. Each unweighted input is in [0,1], so the weighted sum is too. The policy abstains with zero origins or a conflict and hedges with exactly one origin. When n is at least two and c is zero, it asserts if u < 0.35, equivalently if a > 1/8 + 1/(1+n). For n=2 this bound is 11/24. For n=3 it is 3/8. The weights and cutoff are illustrative. The decision uses the unrounded score. A score of 0.349933 can therefore yield an assertion while the printed score rounds to 0.350.

A zero-origin row reports that the pre-review candidate pass retained no spans with a known origin. A negation flag withholds the claim for review. The label describes the decision taken by this rule; the scores are not calibrated probabilities.

PythonIn [33]
CollapseExpand
unc_components_df = pd.DataFrame(
    [
        {
            "claim_short": f"C{ledger.index(c) + 1}",
            "n_indep": c.independent_count,
            "n_score": 1.0 / (1.0 + c.independent_count),
            "a_score": 1.0 - max_authority(c),
            "c_score": 1.0 if detect_conflicts(c.text, c.evidence) else 0.0,
            "label": claim_uncertainty(
                c, bool(detect_conflicts(c.text, c.evidence))
            )["label"],
        }
        for c in ledger
    ]
)
unc_components_df["w_n"] = EVIDENCE_WEIGHT * unc_components_df["n_score"]
unc_components_df["w_a"] = AUTHORITY_WEIGHT * unc_components_df["a_score"]
unc_components_df["w_c"] = CONFLICT_WEIGHT * unc_components_df["c_score"]
VisualizationOut [34]
CollapseExpand
Stacked bars showing weighted uncertainty signals per ledger claim.
Stacked uncertainty signals for each ledger claim, with the weighted evidence-count, authority, and conflict terms summing to the bar height. Labels show decisions on the lexical candidates before quote approval. The 0.35 guide applies only with at least two recorded origins and no flagged conflict.

Citation integrity in practice

We close the implementation by rendering the final answer with citations. In this fixture, the manual review records which quotation from which document supports each claim and retains the digest of that reviewed body. A quote approved for one document cannot transfer to another document. An edit to the approved body requires a new review, even when the quoted sentence survives. The renderer cites the approved snapshot and offsets and gives a reason for claims it withholds.

PythonIn [35]
CollapseExpand
def render_citation(claim: Claim) -> str:
    seen = set()
    markers = []
    for sp in claim.evidence:
        key = (sp.doc_id, sp.start, sp.end)
        if key in seen:
            continue
        seen.add(key)
        markers.append(f"[{CORPUS_VERSION}/{sp.doc_id}:{sp.start}-{sp.end}]")
    return " ".join(markers)


def render_answer(claims: list, uncertainties: pd.DataFrame) -> str:
    u_index = {row["claim_id"]: row for _, row in uncertainties.iterrows()}
    supported_lines = []
    hedged_lines = []
    abstained_lines = []
    for c in claims:
        if not c.evidence:
            abstained_lines.append(
                f"- {c.text} (no approved evidence available)"
            )
            continue
        if not check_existence(c)[0]:
            abstained_lines.append(
                f"- {c.text} (stored quote failed validation)"
            )
            continue
        u_row = u_index.get(c.claim_id)
        label = u_row["label"] if u_row is not None else "abstain"
        line = f"{c.text} {render_citation(c)}"
        if label == "assert":
            supported_lines.append(line)
        elif label == "hedge":
            hedged_lines.append(line)
        else:
            abstained_lines.append(f"- {c.text} (withheld for review)")
    out = []
    if supported_lines:
        out.append(
            "Supported claims:\n" + "\n".join(f"- {l}" for l in supported_lines)
        )
    if hedged_lines:
        out.append(
            "Hedged claims (weak evidence):\n"
            + "\n".join(f"- {l}" for l in hedged_lines)
        )
    if abstained_lines:
        out.append("Abstained on:\n" + "\n".join(abstained_lines))
    return "\n\n".join(out)


AUDITOR_NOTICE_QUOTE = (
    "The rules clarify that bias audits must be performed by an independent "
    "auditor and that audit results must be published."
)
AUDITOR_REPRINT_QUOTE = (
    "Bias audits must be performed by an independent auditor."
)
NOTICE_PERIOD_QUOTE = (
    "Employers must publish audit results and notify candidates residing in "
    "Cedar City at least ten business days before use."
)
APPROVED_FIXTURE_EVIDENCE = {
    claims_to_check[0]: {
        ("rule14-notice", AUDITOR_NOTICE_QUOTE),
        ("news-a", AUDITOR_REPRINT_QUOTE),
        ("blog-b", AUDITOR_REPRINT_QUOTE),
    },
    claims_to_check[1]: {
        ("rule14-text", NOTICE_PERIOD_QUOTE),
        ("rule14-notice", AUDITOR_NOTICE_QUOTE),
        (
            "news-a",
            "According to the Cedar City Audit Office, employers must publish audit results.",
        ),
        (
            "blog-b",
            "Reports from City Policy News confirm that audit results must be published.",
        ),
        (
            "filing-d",
            "The tribunal's opinion reasoned that publication of audit summaries "
            "is a core duty of the law and rejected arguments that the auditor "
            "independence provision is guidance rather than rule.",
        ),
    },
    claims_to_check[2]: {("rule14-text", NOTICE_PERIOD_QUOTE)},
}

# These are the body digests recorded when the fictional quotes were approved.
REVIEWED_BODY_DIGESTS = {
    "rule14-text": "b3fc80bd293b8fd24b1a6e90da5fe66d821cfc10ec5154cea4178a4f9108ee05",
    "rule14-notice": "5328d4ba106572665e7c1af5ff9eadaad54df3638481cbb9f3164532d40c22f3",
    "news-a": "1492459026abf3bbe8a77b3cd42d6f4aeb409f06f9169467e27e9e7c49c3127d",
    "blog-b": "971ca3be56c2345bc959c3249d5d9bd07ff08f3be351ece3218c32d824cab7eb",
    "filing-d": "66c3a50de411ae08c9a5de2c06a0ba8864d78fabbe7fe3ac1ff2e180042fd7ce",
}


def verified_fixture_claims(claims: list) -> list:
    verified = []
    for claim in claims:
        approved = APPROVED_FIXTURE_EVIDENCE.get(claim.text, set())
        evidence = [
            span
            for span in claim.evidence
            if (span.doc_id, span.span) in approved
            and span.source_sha256 == REVIEWED_BODY_DIGESTS.get(span.doc_id)
            and span_exists(span)
        ]
        count, _ = independent_count(evidence)
        verified.append(
            Claim(claim.claim_id, claim.text, evidence, bool(evidence), count)
        )
    return verified


verified_ledger = verified_fixture_claims(ledger)
verified_uncertainties = pd.DataFrame(
    [
        claim_uncertainty(
            claim, bool(detect_conflicts(claim.text, claim.evidence))
        )
        for claim in verified_ledger
    ]
)
final_answer = render_answer(verified_ledger, verified_uncertainties)
ConsoleOut [36]
CollapseExpand
Hedged claims (weak evidence):
- audits must be performed by an independent auditor [cedar_city_synthetic_v2/news-a:132-188] [cedar_city_synthetic_v2/rule14-notice:78-198] [cedar_city_synthetic_v2/blog-b:135-191]
- audit results must be published [cedar_city_synthetic_v2/rule14-notice:78-198]

Abstained on:
- candidates residing in Cedar City must be notified at least ten business days before use (no approved evidence available)
- civil penalties apply to all AI hiring tools (no approved evidence available)
- EU framework requires an equivalent audit obligation (no approved evidence available)

Each printed citation names the corpus version, document ID, and one half-open character range. In this closed fixture, the approved quote map filters candidate spans before the report recalculates uncertainty. In C2, the academic review praises the availability of summaries. The map excludes it from the final answer because it gives no rule requiring publication.

Reproducible research traces

The outputs are repeatable for this fixture with a fixed query, corpus order, software environment and thresholds. A production trace would also record retrieval snapshots and versions of the planner and verifier.

  • Citation version. The renderer prints CORPUS_VERSION in each citation marker. Evidence spans also retain the document ID, body digest and character offsets. Record the corpus version at the trace level when storing runs in a service.
  • Deterministic retrieval. TF-IDF with fixed vocabulary and no sampling yields a deterministic ranked list.
  • Explicit thresholds. The lexical threshold, uncertainty weights and decision cutoff are named in code so that the same settings can be used for the score and its plot.
  • Stored artifacts. The notebook retains objects during a run. A production trace can store its revisions and corpus snapshots in a durable append-only log.

A deployed system might replace the TF-IDF retriever, add a semantic verifier and use iterative planning. Preserve the evidence offsets and source versions through those changes so another reader can repeat the quote check.

This fixture verifies selected quotations and applies the stated report policy to a fixed candidate ledger. To audit a deployed run, keep the archived corpus snapshot, evidence and review decisions with the version of the policy that produced the report. Those records let a reviewer resolve citations and reproduce decisions. Checking semantic support and the reasons for each abstention also requires the recorded evidence and the review procedure.

Limitations and impact

DeepResearch Bench evaluates generated research reports and separately evaluates web collection using citation counts and citation accuracy. The fixture above isolates a narrower question: how two provenance-counting rules behave on the same small corpus. Deep-research agents shift the trust question. In a chat assistant, the user asks "do I trust this sentence?" In a deep-research agent, the user should ask "do I trust this trace?" That is a much better question, but it is also a much harder one to answer well, and the pipeline above only goes partway. The demo makes three assumptions worth examining.

First, source quality is an imperfect proxy for truth. Our bank classifier and authority scores are heuristics based on publisher metadata, and the synthetic corpus exposes the assumptions so readers can audit them. In the wild, authority signals are noisy: a low-authority blog can be correct, and an authoritative institution can be wrong or out of date. The uncertainty score adds a penalty of 0.4 times one minus the largest assigned authority. That proxy does not determine whether a quote supports the claim. A well-designed system should pair it with content-based corroboration, cross-checking against independent sources regardless of the metadata. The independence computation helps, but only to the extent that the derives_from graph is accurately known. In real corpora it is often not known at all. Two unaffiliated outlets may be reproducing the same wire story, or a paper may be silently derived from a press release that pre-dates it.

Second, the support check is a weak entailment proxy. Our bag-of-content-words threshold is a stand-in for real entailment, which is hard. In practice, claims that are supported under a lexical overlap check can still be unsupported under a semantic reading ("the rules allow reporting of audit summaries" and "the rules require publication of audit summaries" share tokens but mean different things, and one may be false). Conversely, correct claims are sometimes missed by the lexical check because of legitimate paraphrasing. The correct production design uses an NLI model or a separate verifier pass (closer to what we discussed in Reranking: Cross-Encoders for Precise Information Retrieval), but even then, human review of high-stakes claims remains essential. Existence checking is exact and cheap; semantic sufficiency may require a verifier or reviewer; attribution (does the answer's paragraph actually use the evidence?) is in between.

Third, abstention is not free. An agent that hedges aggressively on weak evidence sounds less confident and may be less useful to downstream consumers, especially when those consumers are themselves automated and cannot adjudicate hedges. In practice, calibrated abstention requires a downstream consumer that knows what a hedge means. A "hedged" label in a report is not the same as a claim with a confidence interval; without a well-defined probabilistic interpretation, downstream reasoning systems can still be misled. The mitigating move is to preserve the full trace in the output, so that any downstream consumer who needs a numeric quantity can recompute it rather than consume a label. This is one place where the "structured trace as output" design pays off.

Despite these limitations, the impact of getting even a partial version of this pipeline right is substantial. The example shows how evidence misuse can persist after retrieval. One quoted sentence may not support the asserted obligation, and several articles may repeat the same source. The pipeline above makes evidence misuse first-class and auditable: independence is computed, spans are verified verbatim, and the report records abstention. These checks let a reader locate the evidence and challenge a claim.

A research service can persist its trace and review decisions between sessions. A transport can carry trace calls or artifacts. The application owns the shared trace schema, access, storage integrity and approvals. Its authorization policy determines when unverified claims or high-stakes actions need review. Evaluate that policy and the resulting reports with explicit, versioned fixtures.

Summary

Deep-research agents turn a single-pass RAG pipeline into an auditable, multi-step investigation. Every artifact in the trace (plan, queries, retrievals, selected sources, evidence spans, claim ledger, uncertainty scores, and the final answer with inline citations) serves a distinct verification purpose.

Key takeaways:

  • Search is a loop, source selection is a decision, evidence must be extracted verbatim, and the answer must be allowed to abstain. Each of these is a discipline that single-shot RAG skips.
  • Evidence independence is structural, not statistical. The effective evidence count for a claim is the number of recorded provenance roots, not the number of documents. Following the fixture’s single-parent chains computes this, and exposes when several documents repeat one source.
  • Citation existence and citation sufficiency are different checks. Existence checks the body digest, in-range character offsets and exact matching slice. Sufficiency is a semantic check that the span entails the claim. A pass on one does not imply a pass on the other.
  • Abstention is a first-class output state. Absent evidence, conflicting evidence, and weak independent evidence each warrant distinct handling. Silence is not evidence of absence.
  • Reproducibility comes from the trace schema. A versioned corpus, deterministic retriever, named thresholds, and append-only artifacts are what let another party audit an agent's answer weeks after the fact.

What the pipeline above provides is not a proof of truth; it is a checkable trace. That is the achievable goal of deep-research agents, and it is the right one.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about deep-research agents.

Deep-Research Agents

Question 1 of 80 of 8 completed
What is a single retrieval pass unable to do when an initial source introduces a term the system had never seen?
Join the discussionAsk a question or share what you learned.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

A different angle
All writing
Language AI Handbook · Vol. 16

Model Context Protocol

Learn how MCP connects AI hosts to tools, resources, and prompts using JSON-RPC, covering versions, capabilities, transports, and trust boundaries.

30 min read
Language AI Handbook · Vol. 16

Coding and Software-Engineering Agents

Learn how coding agents navigate repositories, verify edits with tests, and produce reviewable patches. Build a test-driven repair loop in Python.

37 min read
Language AI Handbook · Vol. 16

Durable and Asynchronous Agent Work

Design agent runners for recovery with event logs, leases, idempotency keys, retries, deadlines, and reconciliation.

46 min read

About the author

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@misc{brenndoerfer2026deepresearch, author = {Michael Brenndoerfer}, title = {Deep-Research Agents}, year = {2026}, url = {https://mbrenndoerfer.com/writing/deep-research-agents-multi-step-rag-citation-verification}, organization = {mbrenndoerfer.com}, note = {Accessed: 2026-12-03} }
APAAcademic
Michael Brenndoerfer (2026). Deep-Research Agents. Retrieved from https://mbrenndoerfer.com/writing/deep-research-agents-multi-step-rag-citation-verification
MLAAcademic
Michael Brenndoerfer. "Deep-Research Agents." 2026. Web. December 3, 2026. <https://mbrenndoerfer.com/writing/deep-research-agents-multi-step-rag-citation-verification>.
CHICAGOAcademic
Michael Brenndoerfer. "Deep-Research Agents." Accessed December 3, 2026. https://mbrenndoerfer.com/writing/deep-research-agents-multi-step-rag-citation-verification.
HARVARDAcademic
Michael Brenndoerfer (2026) 'Deep-Research Agents'. Available at: https://mbrenndoerfer.com/writing/deep-research-agents-multi-step-rag-citation-verification (Accessed: December 3, 2026).
SimpleBasic
Michael Brenndoerfer (2026). Deep-Research Agents. https://mbrenndoerfer.com/writing/deep-research-agents-multi-step-rag-citation-verification
Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy