AI

Grounded RAG: Hybrid Retrieval, Verified Citations, Honest Refusals

How we build question answering over regulatory and financial PDFs: hybrid search, citations checked by code, and refusals measured as a real outcome.

Weaveward ai editorial illustration

Question answering over tax regulations or annual reports fails in a specific way: a fluent paragraph with a plausible citation that points at the wrong article and quotes a number the source never printed. Users cannot tell, because checking a citation by hand costs the time the system was meant to save. The real defect is that nothing between the model and the reader checks the evidence.

Our position is that the language model should only explain. Ingestion, retrieval and deterministic checks decide what counts as evidence, whether there is enough of it, and whether the answer says what the cited text says. When the evidence is thin, the correct output is a refusal, and that refusal is a measured outcome.

Below is the pipeline we recommend for regulatory and financial PDFs. Project numbers come from RAG Finance, our prototype research assistant over Indonesian finance and tax regulations; everything else is engineering practice.

Ingest each content type with the extractor that suits it

Running prose, ruled tables, charts and scanned annexes break in different ways, so route each region to its own extractor and tag everything that comes out with its document, page, section and extraction method. Citations are only as precise as these anchors.

Content Extractor Typical failure Mitigation
Running text PDF text layer Headers, footers and page numbers leak into chunks Strip page furniture; carry the section heading across page breaks
Ruled tables Table grid detection, cells re-read from the word layer Cell text garbled or merged Keep tables whole; split long ones by rows with the header repeated
Charts and diagrams Vision model with a fixed output schema Plausible values that are not printed Forbid estimates; cross-check numbers against local OCR
Scanned pages OCR Glued words, numbers attached to the wrong label OCR only where the text layer is missing; flag unconfirmed numbers

Two rules matter more than the library. A table is evidence only while its header travels with its rows, so a split table repeats its header in every segment. And OCR is a good cross-check but a poor primary reader for charts, because it reads printed numbers but can lose which label each belongs to; a number a vision model reports that OCR cannot find should be flagged.

RAG Finance suits its corpus with a cheaper rule: official regulations mostly have a text layer, so a page goes to Tesseract (ind+eng) only when its extracted text is shorter than 80 characters. Each new document version is written with its chunks and vectors in one transaction.

Chunk along the document's own structure

Fixed-size windows cut regulations in the worst places: between an article and its ayat, or between a table row and its header. RAG Finance segments along the legal hierarchy (BAB, Bagian, Paragraf, Pasal), with separate zones for the preamble, the elucidation and attachments. Long articles split at ayat, then huruf or angka, then sentences; token windows only handle leftovers. Amending regulations keep their host article in the label, such as Pasal 2 (mengubah UU 6 Tahun 1983) > Pasal 8, so a restated provision traces back to the law it changes.

Each chunk stores its hierarchy, page range and a contextual heading embedded with the text, so an excerpt stays understandable on its own. For financial reports, a document > section > label (page) prefix and chunks that never cross a page mean every citation resolves to one page a reviewer can open.

Chunk size has a hard limit that is easy to miss. The multilingual e5 models read at most 512 model tokens and the embedding library silently truncates the rest. On the regulatory corpus, a 700-token chunker setting meant 2% of chunks lost their end, often the last paragraphs of a long Pasal, so the recommended setting for e5 is 400.

Hybrid retrieval, fused by rank

Each retriever is strong where the other is weak, and RAG Finance runs three of them side by side: vector search, keyword search, and a direct lookup for regulations and articles the question names.

Retriever Strong on Weak on Typical failure
Keyword (BM25 or full-text) Regulation numbers, article references, exact figures Paraphrase, everyday wording, cross-lingual queries A colloquial question never meets the statutory wording
Dense vectors Paraphrase, mixed Indonesian and English Numbers, identifiers, rare codes Two regulations whose numbers differ by one digit can look alike
Identifier lookup Regulations and articles the user names Everything else Only fires when the question names something
Fused (RRF) The union of the above Needs floors and calibrated thresholds A chunk only one retriever found stays mid-ranked

A cross-encoder reranker is the usual next step, but it adds latency and its gain is not guaranteed. RAG Finance ships with reranking set to none and configurable.

BM25 scores and cosine similarities live on unrelated scales, so we fuse ranks. Reciprocal rank fusion gives a document at rank r a contribution of w / (k + r) from each list and sums them. Cormack, Clarke and Büttcher fixed k = 60 in a pilot and found it near-optimal but not critical. The constant flattens the curve: rank 1 contributes 1/61 (about 0.0164) and rank 10 still 1/70 (about 0.0143), so a chunk both retrievers place fifth (2/65, about 0.0308) beats one that a single retriever places first.

RAG Finance adds per-list weights and a normalisation to the range 0 to 1 so domain rules can set floors: a chunk of a regulation the user named is lifted to at least 0.55, or 0.7 at the named article. A sketch, on toy ids of the form regulation, article, ayat:

from collections import defaultdict
from collections.abc import Mapping, Sequence


def fuse(
    rankings: Mapping[str, Sequence[str]],
    *,
    k: int = 60,
    weights: Mapping[str, float] | None = None,
    floors: Mapping[str, float] | None = None,
) -> list[tuple[str, float]]:
    """Weighted RRF: score(d) = sum of w / (k + rank), normalised to [0, 1]."""
    weights, floors = weights or {}, floors or {}
    raw: defaultdict[str, float] = defaultdict(float)
    for name, ranked in rankings.items():
        for rank, chunk_id in enumerate(dict.fromkeys(ranked), start=1):
            raw[chunk_id] += weights.get(name, 1.0) / (k + rank)
    # Best possible: rank 1 in every list. Normalising makes floors meaningful.
    best = sum(weights.get(name, 1.0) for name in rankings) / (k + 1)
    fused = {}
    for chunk_id, score in raw.items():
        relevance = min(1.0, score / best)
        floor = floors.get(chunk_id, 0.0)  # e.g. an article the user named
        fused[chunk_id] = floor + (1.0 - floor) * relevance
    return sorted(fused.items(), key=lambda item: (-item[1], item[0]))


bm25 = ["pph:17:1", "kup:9:2", "ppn:4a:2", "pmk81:2:1"]
dense = ["hpp:3:17", "pph:17:1", "ppn:4a:2", "pph:4:2"]
named = {"pmk81:2:1": 0.7}  # the question names this regulation and article

for chunk_id, score in fuse({"bm25": bm25, "dense": dense}, floors=named):
    print(f"{chunk_id:10} {score:.3f}")
# pph:17:1 0.992, ppn:4a:2 0.968, pmk81:2:1 0.843,
# hpp:3:17 0.500, kup:9:2 0.492, pph:4:2 0.477

Normalisation makes one property visible: a chunk only one retriever found can never score much above 0.5, which is why named identifiers need an explicit floor. In RAG Finance, fused relevance is one feature among several (authority, status, metadata and title match), all kept on the candidate so a debug view can explain any ranking.

Indonesian and English in one index

Users ask in Indonesian, English or a mix, often in everyday wording. RAG Finance handles that with a multilingual embedding model (multilingual-e5-small with its query: and passage: prefixes), PostgreSQL full-text search with the indonesian configuration, and a glossary that expands colloquial terms into statutory ones, such as "pinjol" to LPBBTI. Keyword search runs as a precision-first cascade: all concepts, then all but one, then any distinctive term.

Calibrate similarity thresholds per model. e5 compresses similarities into roughly 0.77 to 0.91; on the evaluation set, relevant questions scored 0.835 to 0.909 at the top chunk and off-topic ones 0.77 to 0.832, so the floor sits at 0.834 in a very narrow gap that must be re-checked after every reindex.

Versions, amendments and effective dates

An answer can be correctly cited and still wrong because the article was amended. Indonesian laws are often amended by restating an article inside a later regulation: UU HPP restates UU PPh Pasal 17 with the 22% corporate rate. In RAG Finance, a document is the stable identity of a regulation at one source, and a new document_version is created only when the official file's SHA-256 changes. Amendments and revocations are relations between regulations, and status is set only from an explicit statement in the source or a full revocation clause, never inferred from a publication date. Guessing status from dates is how a revoked rule ends up presented as current law.

At query time, deterministic analysis decides whether the question concerns current or historical law, from words such as "sebelumnya" or a reference year before the current one. In current mode, a revoked chunk is demoted by 0.3 when the regulation that revoked it is also retrieved. After the sufficiency gate, an amendment lookup places later indexed wording beside the older article, but only when it comes from a regulation of the same rank (a PMK never amends a UU) and most of the older article's vocabulary recurs in a stretch of similar length. The evidence carries a note separating old text from amended text, and every decision is traced.

Verify citations with code, not with the model

RAG Finance asks the model for numbered [n] markers and validates them on the server. We recommend going one step further: every claim cites one or more chunk ids, and every citation carries a verbatim quote. Producing that shape reliably is covered in our article on structured LLM output validation and repair. Once the shape is valid, a verifier can check substance:

  • Every cited id must be a chunk that was in the context; an unknown id is an error
  • The quote must occur in a cited chunk after normalisation: compatibility decomposition, accents removed, case folded, spacing and punctuation dropped, decimal points kept
  • Every number in the claim must occur in the cited text
  • An answer is grounded only if every claim passes

Normalisation must be strict enough to fail a dropped "tidak" or a swapped figure, and loose enough to survive OCR that glued words together. Splitting quotes at ellipses lets the model elide the middle of a long sentence without inventing anything.

import re
import unicodedata
from dataclasses import dataclass

_ELLIPSIS = re.compile(r"\s*(?:\.\.\.|\u2026)\s*")
_NUMBER = re.compile(r"\d+(?:[.,]\d+)*")


def squash(text: str) -> str:
    """Fold case and accents, drop spacing and punctuation, keep decimal points."""
    text = unicodedata.normalize("NFKD", text)
    text = "".join(ch for ch in text if not unicodedata.combining(ch)).casefold()
    text = re.sub(r"[^\w.]+", "", text)
    return re.sub(r"(?<!\d)\.|\.(?!\d)", "", text)


def quote_in(quote: str, source: str) -> bool:
    parts = [squash(p) for p in _ELLIPSIS.split(quote) if squash(p)]
    return bool(parts) and all(p in squash(source) for p in parts)


@dataclass(frozen=True)
class Claim:
    text: str
    chunk_ids: tuple[str, ...]
    quote: str


def verify(claims: list[Claim], chunks: dict[str, str]) -> tuple[bool, list[str]]:
    problems: list[str] = []
    for n, claim in enumerate(claims, start=1):
        unknown = [cid for cid in claim.chunk_ids if cid not in chunks]
        if not claim.chunk_ids or unknown:
            problems.append(f"claim {n}: no citation, or unknown ids {unknown}")
            continue
        if not any(quote_in(claim.quote, chunks[cid]) for cid in claim.chunk_ids):
            problems.append(f"claim {n}: quote not found in {', '.join(claim.chunk_ids)}")
        cited = " ".join(chunks[cid] for cid in claim.chunk_ids)
        missing = set(_NUMBER.findall(claim.text)) - set(_NUMBER.findall(cited))
        if missing:
            problems.append(f"claim {n}: numbers not in cited text: {sorted(missing)}")
    return bool(claims) and not problems, problems

On toy evidence (illustrative wording, not quoted regulation text), it accepts a quote with different casing and spacing, and rejects a changed rate, a dropped negation and a citation to a chunk that was never retrieved:

chunks = {
    "hpp:3:17": "Tarif bagi Wajib Pajak badan dalam negeri sebesar 22% (dua puluh dua persen).",
    "ppn:kb:2": "Penyerahan barang ke Kawasan Berikat tidak dipungut PPN.",
}
claims = [
    Claim("The corporate rate is 22%.", ("hpp:3:17",), "wajib pajak BADAN dalam negeri sebesar 22 %"),
    Claim("The corporate rate is 25%.", ("hpp:3:17",), "sebesar 22%"),
    Claim("Such deliveries attract VAT.", ("ppn:kb:2",), "Penyerahan barang ke Kawasan Berikat dipungut PPN"),
    Claim("Rates fell in 2022.", ("pph:17:1",), "tarif"),
]
print(verify(claims, chunks))
# (False, ["claim 2: numbers not in cited text: ['25']",
#          'claim 3: quote not found in ppn:kb:2',
#          "claim 4: no citation, or unknown ids ['pph:17:1']"])
print(verify(claims[:1], chunks))  # (True, [])

A verifier can extend the number rule to calculations: accept a computed figure only if it re-computes from cited operands through a restricted expression walk (the four basic operations, never eval), checking every link of a chain.

Know the blind spot: a value from the right table but the wrong row or column passes, because the number does occur in the cited chunk. Showing the cited row to the reader is a partial safeguard; cell-level citations are the real fix.

What happens to a failing answer is policy. RAG Finance removes citation markers that point at no evidence item, flags regulation or article numbers that no evidence chunk, title or succession link contains, and stores the result with the answer's retrieval trace. For a regulated production deployment we recommend stricter handling: never present an unverifiable answer as grounded; regenerate once with the verifier's findings, otherwise refuse and list the closest sources.

Refusals are an outcome you measure

Refuse in two places. The first is before the model. RAG Finance runs a sufficiency gate over the whole question, or over each part of a planned one. Similarity alone does not pass it, because some embedding models score every chunk in a narrow band; a chunk must also cover the question's concepts (for example, half of its glossary topics), or belong to a regulation the user named. When nothing passes, the service returns a deterministic no-answer ("Saya belum menemukan dasar hukum yang cukup") with the closest sources and never calls the answer model. A general-knowledge fallback exists behind a flag that is off by default.

The second is after the model, when it finds the evidence does not answer. RAG Finance treats an uncited answer that only says so as a no-answer too, and records the outcome (success, no_evidence or general) with the trace. A refusal that slips in a figure from neither the question nor the evidence is still a failure, so refusals go through the same number check.

Score refusal as four cells: answered when answerable, refused when answerable, refused when not answerable, and answered when not answerable (the dangerous one). Track the two error cells separately, because tightening thresholds trades one for the other.

Evaluate each stage, then attribute failures

An answer can be lost in extraction, retrieval or generation, so we measure each and attribute every wrong answer to the first stage that lost what it needed. Ingestion coverage asks whether the evidence exists in any chunk. Retrieval reports hit@k, MRR and context recall. Answers get a deterministic check, with an LLM judge reported beside it, never instead of it.

from dataclasses import dataclass


@dataclass(frozen=True)
class Case:
    answerable: bool
    gold: frozenset[str]        # chunk ids that hold the evidence
    retrieved: tuple[str, ...]  # ranked chunk ids
    cited: tuple[str, ...]      # chunk ids the final answer cites
    refused: bool


def hit_at_k(cases: list[Case], k: int = 5) -> float:
    rows = [c for c in cases if c.answerable]
    return sum(bool(c.gold & set(c.retrieved[:k])) for c in rows) / len(rows)


def citation_precision(cases: list[Case]) -> float:
    pairs = [(cid, c.gold) for c in cases if not c.refused for cid in c.cited]
    return sum(cid in gold for cid, gold in pairs) / len(pairs) if pairs else 0.0


def refusal_outcomes(cases: list[Case]) -> dict[str, int]:
    out = {"answered": 0, "wrong_refusal": 0, "correct_refusal": 0, "should_have_refused": 0}
    for c in cases:
        if c.answerable:
            out["wrong_refusal" if c.refused else "answered"] += 1
        else:
            out["correct_refusal" if c.refused else "should_have_refused"] += 1
    return out

RAG Finance's harness reports hit@k, MRR, evidence precision, no-answer accuracy and, in full mode, citation validity and the grounded refusal rate. Its numbers are useful and small: on 693 real regulatory chunks and 25 labelled questions, multilingual-e5-small reached hit@5 0.96 and MRR 0.84, while the much faster potion-multilingual-128M reached hit@5 0.80 and MRR 0.59. That is a regression signal on a prototype, not an accuracy claim about real user traffic.

Two lessons generalise. Include should-not-answer cases on purpose; the RAG Finance dataset has categories for fictitious regulations and wrong-domain questions. And test the scorer as carefully as the system: a fact check that matches "22" inside "2022" credits answers that never stated the rate. Wiring these checks into releases is the subject of our article on LLM release evaluation gates in CI.

FAQ

Do we still need retrieval if the whole document fits in the context window?

Not always. If one short document is the whole corpus, a full-document prompt with prompt caching can work, and the same verifier still applies. A regulatory corpus built from five official sources plus uploads will not fit in one prompt, and retrieval leaves a per-question trace to debug.

Should every pipeline add a cross-encoder reranker?

Only if it wins on your evaluation set, measured on paraphrased questions as well as on the document's own wording. Every candidate it scores adds latency.

Checklist

  • Route each content type to its own extractor and keep page, section and method anchors on every chunk
  • Chunk along document structure, under the embedding model's real token limit
  • Fuse BM25 and dense results with RRF (k around 60) and add explicit floors for named identifiers
  • Calibrate similarity floors per embedding model and re-check them after every reindex
  • Derive regulation status from explicit statements and succession links, never from publication dates
  • Verify every quote and number in code; never show an unverifiable answer as grounded
  • Gate on evidence sufficiency before calling the model, and score refusals as four outcomes
  • Attribute each failure to the first stage that lost the evidence

Primary references

The regulatory prototype behind most of this article is described in our finance and tax regulatory research assistant case study, and our AI solutions page explains how we scope grounded assistants like it.

Let’s connect the dots

What would this look like for your business?

Let's turn the right ideas into a clear next step.

Discuss your project