Deep-Research Agents › Implementation
Language AI HandbookAll chapters PythonIn [2]Expand
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_similarityThe 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]Expand
@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 = 0These 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]Expand
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]Expand
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]Expand
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]Expand
# 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]Expand

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]Expand
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]Expand
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 selectedConsoleOut [12]Expand
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 primaryThe 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]Expand
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 spansConsoleOut [14]Expand
[ 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]Expand
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]Expand
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]Expand
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 0Compare 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]Expand
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]Expand
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-noticeThe 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]Expand
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]Expand

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]Expand
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]Expand
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 matchA 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.
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!