of Enterprise Doc Intelligence, a sequence that builds an enterprise RAG system from 4 bricks: parsing, query parsing, retrieval, and era. It closes the brick’s three elements. The earlier half, Article 7B (anchor detection), produced ranked candidates; this one arbitrates: one LLM name ranks them with causes, and the output is one typed JSON an auditor can defend.

Retrieval is filtering on line_df and toc_df, anchor versus context: the psychological mannequin from Article 7A (retrieval as filtering). The anchors themselves come out of a three-stage detection pipeline (Article 7B, anchor detection): key phrase + embeddings in parallel, aggregation to a structural unit, then a single LLM name on the finish. This text is about that final name.
This text is about that single LLM name. The arbiter. It sees key phrase hits, embedding hits, and the part every candidate sits in, multi function structured temporary, and writes a per-candidate verdict with a purpose. The sample in a single line: detectors suggest, the arbiter decides. In a single name.
The article additionally covers what comes across the arbiter: the deterministic dispatcher that picks which detectors to run per query, the “not discovered” path (a dependable system should be capable to say no), and the unified JSON contract (RetrievalResult) that retrieval fingers to era.
All through this text we work on a single doc, Consideration Is All You Want (Vaswani et al. 2017, 15 pages; arXiv non-exclusive distribution license, declared on the arXiv summary web page). It carries a clear native TOC within the PDF define (22 entries, 3 ranges deep), and the content material is acquainted territory for any engineer touching RAG: encoder, decoder, consideration, queries, keys, values. That retains the concentrate on the retrieval strategies moderately than on parsing a domain-specific corpus. This text additionally assumes the doc carries its personal TOC; recovering one from uncooked textual content is left to follow-up work.

line_df and toc_df – Picture by creator1. The LLM arbiter: the only LLM name on the finish
That is the LLM name that Article 7B (anchor detection) positioned at stage 3. That article produced candidates from every detector; this part is what occurs to them. A candidate is a single passage a detector returned with its anchor (the place it was matched), its aggregated unit (part, web page, or chunk), and a snippet of surrounding context. The arbiter sees them multi function name, ranks them with causes, and outputs the ultimate record.
The three issues this part covers:
- Why rating fusion (RRF and mates) loses the sign the detectors already made obtainable.
- What structured temporary handy the arbiter so it will probably rank with causes.
- What to file per candidate so any auditor can reconstruct the choice.
The sample in a single line: detectors suggest, the arbiter decides, in a single name.
1.1 Rating fusion is the mistaken intuition
When a number of strategies return candidates, the reflex is to mix their scores. The strategies return numbers on totally different scales: cosine similarity, BM25 unbounded, and co-occurrence integer counts. Including them is meaningless. Normalizing every methodology’s rating to doesn’t assist both, as a result of a 0.9 cosine and a 0.9 normalized BM25 don’t imply the identical factor about the identical candidate.
The classical reply is Reciprocal Rank Fusion (RRF). It sidesteps the calibration drawback by ignoring scores and utilizing ranks:

with ok=20 by conference. Candidates ranked by a number of strategies accumulate contributions; candidates seen by just one methodology get a single small time period. RRF is the default in lots of vector DBs (Pinecone, Weaviate, Elastic) and works on frequent instances with out tuning.
However RRF leaves actual sign on the ground. Why a technique ranked a candidate issues. TOC ranked it as a result of a piece title matched. Key phrases ranked it as a result of premium and € co-occurred on the identical line. Embeddings ranked it as a result of one thing close to the web page was vaguely shut in vector area. RRF compresses all of that to a rank index. The settlement throughout strategies turns into a quantity, and the purpose for the settlement disappears.
That’s precisely what an skilled reads off the display: the part heading, the matched key phrases, the traces across the match. We argue {that a} small LLM name, given the identical info in a structured type, ranks higher than any score-fusion methodology.
We nonetheless log RRF when the encompassing device makes use of it by default, or use it as an affordable pre-filter when the candidate pool is just too giant to slot in an LLM name (top-200 by RRF, then LLM on the survivors). However the rating choice belongs to the LLM, to not a rating method.
1.2 Hand the LLM a structured temporary
The LLM is the layer that ranks. Its enter shouldn’t be “listed below are 5 passages, decide the most effective”. It’s a structured temporary, one row per candidate, itemizing what every retrieval methodology came upon:
candidate_id: secure reference (web page + line vary, or part + line offset).strategies: which retrieval strategies confirmed this candidate (TOC, key phrases, embeddings).part: the TOC part the candidate sits in, lifted fromtoc_df.matched_keywords: the key phrases from the parsed query that landed on this candidate.snippet: three to 5 traces of surrounding context, lifted fromline_df.
The temporary is what the LLM reads. It seems like what an skilled sees on their display: a piece heading on high, the matched key phrases within the physique, the traces across the match. A lot nearer to that than to a ranked record of cosine scores. The LLM ranks the candidates and writes a one-line purpose per stored candidate, which matches straight into the audit path. Every candidate will get one among 4 roles:
main: carries the reply.supporting: offers context the reply must make sense.tangential: associated however stored low-priority.discarded: the LLM’s drop, with a purpose recorded for audit.
class CandidateBrief(BaseModel):
candidate_id: str
strategies: record[str]
part: str
matched_keywords: record[str]
snippet: str
class CandidateRanking(BaseModel):
candidate_id: str
position: Literal["primary", "supporting", "tangential", "discarded"]
purpose: str
def llm_rank(
query: str,
briefs: record[CandidateBrief],
consumer,
) -> record[CandidateRanking]:
"""Learn the structured briefs, return one rating per candidate."""
...
A minimal runnable arbiter. One LLM name, the entire candidate record directly, structured output again.
def llm_rank(query: str, briefs: record[CandidateBrief], consumer) -> record[CandidateRanking]:
"""Hand the LLM the structured briefs, get one position + purpose per candidate."""
briefs_text = "n".be a part of(
f"[{b.candidate_id}] part={b.part!r}, strategies={b.strategies}, "
f"matched={b.matched_keywords}, snippet={b.snippet!r}"
for b in briefs
)
immediate = (
f"Query: {query}nnCandidates:n{briefs_text}nn"
"For every candidate, assign a task (main, supporting, tangential, "
"discarded) and a one-line purpose. Use the candidate_id verbatim."
)
return consumer.responses.parse(
mannequin=model_chat,
enter=immediate,
text_format=ArbiterOutput,
).output_parsed.rankings
Why this beats rating fusion:
- The LLM sees why every methodology ranked the candidate. A high-cosine match with no key phrase overlap might be topical noise. A TOC + key phrase settlement is an actual structural sign. RRF turns each into the identical rank quantity.
- The LLM can label candidates past maintain/drop: main, supporting, tangential. Helpful when the reply has a most important half and supporting context.
- The LLM can flag contradictions: two passages saying various things on the identical level. Frequent in contracts with amendments, in regulatory filings with revisions.
- The justification is apparent textual content and goes straight into the audit path. No
rrf_score = 0.0327line to clarify to compliance.
Price: one LLM name (a couple of second for a top-10 candidate pool). Cheaper than working embeddings on the entire doc. Less expensive than a mistaken reply in manufacturing.
A concrete temporary on the working paper. Query: “What positional encoding does the paper use?” TOC matching (which hits 3.5 Positional Encoding instantly) plus key phrases on the entire doc yield 4 candidates. Every turns into one row of the temporary.

The LLM reads the 4 briefs and the query, and returns:
{
"rankings": [
{
"candidate_id": "page_5_sinusoidal",
"role": "primary",
"reason": "Defines the sinusoidal positional encoding used in the paper"
},
{
"candidate_id": "page_6_learned",
"role": "primary",
"reason": "States the alternative (learned embeddings) the paper compared"
},
{
"candidate_id": "page_2_intro",
"role": "discarded",
"reason": "Mentions the motivation for positional encoding, but no options"
},
{
"candidate_id": "page_3_encoder",
"role": "discarded",
"reason": "Single mention in a different context, off-topic"
}
]
}
Two of 4 stored. The 2 discarded would have crept in beneath any score-fusion scheme: they’ve official key phrase hits. However the snippets learn like context, not like solutions. The LLM made that decision from the snippet, and wrote the explanation that goes into the audit path.
A dwell name towards the identical 4 briefs.

1.3 Conflicts and the audit path
When strategies disagree, the LLM has to choose. Three guidelines of thumb assist:
- Belief the TOC on precise title matches. The creator wrote that title. 3.5 Positional Encoding matched instantly on the working query’s key phrases. No statistical methodology ought to override that.
- Belief co-occurrence key phrases with a robust sign. A line the place main and secondary key phrases seem collectively (positional + sinusoidal, or positional + realized) is sort of definitely related, even when it sits exterior the TOC-narrowed scope.
- Be skeptical of embedding-only hits: A candidate surfaced solely by embeddings, with no TOC or key phrase backing, wants a cautious look. Typically an actual synonym the key phrase methodology missed. Extra typically it’s topical noise. The LLM, studying the temporary, can often inform which is which.
The structured temporary is what lets the LLM apply these guidelines constantly. Rating fusion compresses why every methodology ranked a candidate to a single rank index and throws the foundations out with it.
Each candidate have to be defensible. Why was this passage proven to the person? The reply can’t be “the embedding similarity was 0.78”. It must be a transparent chain: which strategies confirmed this candidate, what temporary was proven to the LLM, what position the LLM assigned, what purpose it wrote. Every candidate carries that path from retrieval by way of era.
class CandidateProvenance(BaseModel):
candidate_id: str
methods_that_found_it: record[str]
rank_per_method: dict[str, int]
structural_context: CandidateBrief
llm_role: Literal["primary", "supporting",
"tangential", "discarded"]
llm_reason: str
class AuditedRetrievalResult(BaseModel):
candidates: record[dict]
provenances: record[CandidateProvenance]
methods_run: record[str]
methods_skipped: record[str]
skipped_reasons: dict[str, str]
For every candidate that reaches the person, the system can reply: which strategies voted for it, what was its rank in every, what did the LLM see, what position did the LLM assign and why, have been any strategies skipped and why.
A concrete entry for the page-5 candidate from the instance above:
provenances = [
CandidateProvenance(
candidate_id="page_5_sinusoidal",
methods_that_found_it=["toc", "keywords"],
rank_per_method={"toc": 1, "key phrases": 1},
structural_context=CandidateBrief(
candidate_id="page_5_sinusoidal",
strategies=["toc", "keywords"],
part="3.5 Positional Encoding",
matched_keywords=["positional", "encoding", "sinusoidal"],
snippet="We use sine and cosine features of various frequencies...",
),
llm_role="main",
llm_reason="Defines the sinusoidal positional encoding used within the paper",
),
# ... similar construction for the opposite stored candidate
]
methods_skipped = ["embeddings"]
skipped_reasons = {
"embeddings": "TOC and key phrases returned sturdy reinforcing indicators"
}
This isn’t only for debugging. In compliance, authorized, and audit contexts, this path is the documentation that justifies the system’s output. With out it, the retrieval pipeline is a black field, and a black field doesn’t cross a regulatory evaluate.
2. Selecting the strategies
2.1 Why embeddings come final
Most RAG tutorials, frameworks, and convention talks current embedding-based retrieval as the muse of the system. The implicit assumption is that embeddings are the default; the one query is which embedding mannequin to make use of.
After strolling by way of the grid, the place of this sequence turns into concrete: embeddings occupy a supporting position on each tables (title embedding match on toc_df, chunk embedding match on line_df), neither of which is the beneficial default for many enterprise paperwork. This isn’t a rejection of embeddings. It’s a re-prioritization primarily based on what works.
Motive 1, embeddings dilute high-signal tokens. Embed “Does article L131-1 of the insurance coverage code apply right here?” and the vector is a mean of “article”, “insurance coverage”, “code”, “apply”, “L131-1”. The token “L131-1” is all the question, however it’s one sign in seven. The vector for the proper passage might not be the closest match. Content material key phrase match finds it immediately.
We noticed a model of this within the minimal RAG pipeline with the well-known epsilon-label-smoothing failure: the web page that contained the reply was not even within the high 3 by cosine similarity. The web page that gained contained extra of the visible model of the query, not its particular info content material.
Motive 2, embeddings can not distinguish related-but-different ideas. The vector for “premium” and the vector for “deductible” are shut. Each are quantities in an insurance coverage contract, each seem in related contexts. A question for “premium” with cosine similarity returns passages mentioning “deductible” alongside passages mentioning “premium”. If the embedding-based retrieval brings again primarily deductible passages, the LLM downstream has nothing to disambiguate from.
Similar drawback with negation, time references, and any semantic distinction that relies on small phrase adjustments. Embeddings blur these distinctions; that’s each their energy and their weak spot.
Motive 3, embeddings haven’t any understanding of doc construction. A vector database is a flat assortment of chunks. It has no notion of “this chunk is within the Definitions part” or “this chunk is a part of an annex”. All of that construction was thrown away when the doc was chunked.
For a query like “What does the guarantee part say about flood injury?”, an embedding search returns chunks that point out “guarantee” and “flood”, probably from Definitions or Exclusions, neither of which is what the person wished. TOC reasoning would have picked Guarantee in a single step.
Made concrete on the working paper: the person asks “what does Determine 2 present?”. The query is dominated by one high-signal token (Determine 2); every little thing else is filler. Embedding averages all of it; regex anchors the precise token immediately.

Embedding ranks pages by visible similarity to the question phrasing and should not put the precise Determine 2 mentions within the top-5 in any respect. The regex finds each line that accommodates the precise token, on the proper pages, deterministically. One sign in seven, misplaced within the common; one sign lifted out by the proper device.
2.2 When embeddings win
Embeddings shine in three instances:
- Vocabulary mismatch the place rewrites assist. “Exit early” embeds near “early termination provisions” as soon as the rewrites are in play. Title key phrase match and content material key phrase match miss this; chunk embedding match catches it. (TOC reasoning additionally catches this for a distinct purpose: the LLM understands that “exit early” pertains to Termination by way of implication, not similarity.)
- Conceptual or fuzzy questions: “Is the legal responsibility cap affordable?”: no particular key phrase to seek for. Embedding can expose passages with the proper conceptual form.
- Paperwork with out TOC and with out specialised vocabulary. Memos, emails, weblog posts. No construction to navigate; no skilled dictionary to use.
In all three instances, embeddings are usually not competing alone, they’re mixed with key phrase and TOC strategies (the hybrid embedding mixture) for the structural consciousness they lack.
Within the wild: On one manufacturing system we measured the contribution of every retrieval methodology by ablating them one after the other, towards a per-failure-mode analysis:
- Embedding-only baseline: 71% accuracy.
- Including TOC-based retrieval the place relevant: 84%.
- Including co-occurrence key phrase retrieval with the skilled dictionary: 91%.
- Including the orchestrator to choose strategies per query: 94%.
The 23-point hole between embeddings solely and all strategies with deterministic dispatching is what higher retrieval buys. No embedding-model improve we tried got here shut.
HyDE is a particular case of this precept. HyDE generates a hypothetical reply to the query, embeds it, then runs cosine similarity towards the doc chunks. The rationale it really works: the hypothetical reply carries the doc’s area vocabulary that the query lacks. “How do I exit a contract early?” turns into “early termination, discover interval, exit charges, written discover…” within the LLM’s draft, which then matches the true passages in embedding area.
On this framework, the identical logic is captured one stage earlier, at query parsing time, and codified into the skilled key phrase dictionary. HyDE is “embedding-based key phrase enlargement achieved implicitly per question”; this sequence favors “express key phrase enlargement achieved as soon as and reused”. Similar payoff, with three operational features:
- the key phrase set is auditable: the skilled sees what matched and why
- it pays its price as soon as as a substitute of per question
- it builds a everlasting asset (the dictionary) as a substitute of regenerating a one-shot speculation
In open-domain client settings with no area skilled and with out auditability necessities, HyDE retains a small benefit; within the enterprise contexts this sequence targets, express enlargement is virtually superior. The query parsing brick decomposes the mechanisms behind HyDE intimately and explains why the keyword-and-synonym one dominates when the doc vocabulary is bounded.
2.3 The choice tree
How does the dispatcher determine which mixture of cells to allow for a given query?
def choose_methods(intent, key phrases, doc_has_toc,
has_exact_codes=False,
vocabulary_diverges=False):
strategies = []
if doc_has_toc and intent in ("qa", "summarization"):
strategies.append("toc")
if key phrases:
strategies.append("co_occurrence")
if has_exact_codes:
strategies.append("bm25")
if not strategies or vocabulary_diverges:
strategies.append("embedding")
return strategies
- If the doc has a clear TOC, run title key phrase match (at all times) and title embedding match (optionally available) because the toc-side detectors. The arbiter will use the TOC to purpose about delicate title matches as a part of its single name.
- On
line_df, run content material key phrase match with the parsed query’s key phrases and co-occurrence boosts. That is the primary detector; its hits feed the arbiter instantly. - Add embeddings on line_df in parallel when vocabulary mismatch is anticipated or when the query is conceptual. Elective, skippable when key phrase sign is already clear.
- The LLM arbiter (Part 1) sees every little thing directly, ranks with causes. That is the only LLM name that turns detector hits right into a ultimate record.
- On very giant paperwork the place the candidate pool is just too large to suit one arbiter name, use reason-then-match as a pre-narrowing trick: one further LLM name on
toc_dfpicks the related sections, then content material key phrase runs inside, then the arbiter ranks the survivors. Two LLM calls whole as a substitute of 1, solely when scale calls for it.
In manufacturing, most questions activate key phrase + (optionally) embedding detectors and finish with the arbiter. The technique code beneath makes use of the older "toc_reasoning" / "reason_then_match" labels for backwards-compatibility; conceptually they map to “the arbiter does the reasoning” and “slim earlier than the arbiter” respectively. A follow-up built-in pipeline develops the orchestration across the dispatcher.
Frequent pitfall: Laborious-coding the identical retrieval technique for all questions. A pipeline that at all times runs embedding retrieval, even for paperwork with a clear TOC and questions with particular key phrases, is doing further work that produces noisier candidates than the less complicated strategies would have. The dispatcher ought to select; if it at all times chooses the identical factor, you’ve got ablated the selection.
def choose_retrieval_strategy(
intent: str,
key phrases: record[str],
doc_has_toc: bool,
has_exact_codes: bool = False,
vocabulary_diverges: bool = False,
) -> record[str]:
technique: record[str] = []
if doc_has_toc and intent in ("qa", "summarization"):
technique.append("toc_reasoning")
technique.append("title_keyword_match")
if key phrases:
if "toc_reasoning" in technique:
technique.append("reason_then_match")
else:
technique.append("content_keyword_match")
if has_exact_codes:
technique.append("bm25")
if not technique or vocabulary_diverges:
technique.append("chunk_embedding_match" if not doc_has_toc else "hybrid_embedding")
return technique
# 4 actual reader questions an individual finding out the paper would possibly ask, dispatched by the technique chooser.
doc_has_toc = len(toc_df) > 3
questions = [
{"q": "How does multi-head attention work?",
"intent": "qa", "keywords": ["multi-head", "attention"], "precise": False, "diverges": False},
{"q": "What does Determine 2 present?",
"intent": "qa", "key phrases": ["Figure 2"], "precise": True, "diverges": False},
{"q": "Why does this mannequin prepare sooner than RNNs?",
"intent": "qa", "key phrases": [], "precise": False, "diverges": True},
{"q": "Summarize the Coaching part.",
"intent": "summarization", "key phrases": ["Training"], "precise": False, "diverges": False},
]
for q in questions:
s = choose_retrieval_strategy(
q["intent"], q["keywords"], doc_has_toc,
has_exact_codes=q["exact"], vocabulary_diverges=q["diverges"],
)
print(f"{q['q']}n technique: {s}n")
Run on 4 pattern questions of various shapes: a vocabulary-rich QA, a query pointing at a selected determine, a conceptual query with no key phrases, and a summarization request:

3. Saying “not discovered” reliably
A dependable system should be capable to say no. That is more durable than it sounds, as a result of LLMs are skilled to supply responses, to not withhold them.
The structure has to assist “not discovered” at each stage:
- Metadata filtering returns zero paperwork. No retrieval is run. The system tells the person no doc matches the scope.
- TOC matching returns no related part. The pipeline falls by way of to the following methodology.
- All retrieval strategies return empty or low-confidence candidates. The pipeline experiences “no reply discovered within the obtainable paperwork,” explaining what was searched.
- Candidates exist however the LLM, in era, can not extract a solution. Dealt with on the era stage, however the retrieval stage should cross ahead sufficient metadata for era to be conservative.
3.1 Why key phrases show absence, embeddings can not
There’s a deep asymmetry between retrieval strategies on how they deal with absence. Embedding retrieval at all times returns a top-k with steady similarity scores. A web page about premiums returns 0.78 for a query about exclusions; a web page about exclusions returns 0.81. The place do you draw the road between discovered and not discovered? Nothing within the embedding area says “this isn’t the proper reply,” solely “that is nearer or farther than that different one.” You’ll be able to decide a threshold, however it’s arbitrary; on a distinct doc or a distinct query, the brink breaks.
Key phrase retrieval works the other manner. In case your skilled dictionary for “exclusion” covers each type the subject can take within the corpus (“exclusion”, “exclu de”, “non couvert”, “hors champ”, “ne couvre pas”), and the doc accommodates none of them, you’ve got a defensible declare: the subject shouldn’t be on this doc. Similar for quantities, dates, codes. When the regex for “€” matches nothing, there’s nothing to match. The absence is proof, not uncertainty.
That is precisely what a enterprise person has at all times achieved with Ctrl+F. They search the time period they anticipate, and when nothing comes up, they conclude the doc doesn’t cowl it. The conclusion holds as a result of they know which phrases to search for. Thirty years {of professional} doc work runs on this methodology. A retrieval pipeline that encodes the identical skilled vocabulary inherits the identical property: zero hits throughout an exhaustive key phrase set returns “not discovered” with a exact, auditable purpose.
In enterprise settings (authorized, compliance, finance), that is the distinction between “I’m undecided” (hedging) and “none of those particular phrases seem within the doc, and they’d be current if the reply have been right here” (a defensible search). The primary is ineffective to a compliance officer. The second is the reply.
This argument can be why skilled dictionaries (constructed at query parsing time) are definitely worth the funding. A dictionary that covers a subject exhaustively is not only a solution to discover the reply when it exists; it’s the mechanism that lets the system show the reply doesn’t exist when it doesn’t.
class RetrievalResult(BaseModel):
candidates: record[dict]
methods_used: record[str]
not_found: bool
not_found_reason: str | None = None
confidence: float
When not_found is True, the era stage is aware of to supply “the reply shouldn’t be within the obtainable paperwork” with the explanation, moderately than guessing. The era brick comes again to this.
class RetrievalResult(BaseModel):
candidates: record[dict]
methods_used: record[str]
not_found: bool
not_found_reason: str | None = None
confidence: float
# A reader's query whose reply is NOT on this paper: GDPR compliance has nothing to do with
# the Transformer structure. Key phrases beneath are extremely distinctive -- verified 0 hits within the paper.
absent_question = "What does this paper say about GDPR compliance and private information safety?"
absent_keywords = ["gdpr", "personal data", "compliance", "data protection officer"]
# Key phrase aspect: exhaustive search returns 0 hits -> defensible "not discovered".
title_hits = match_titles(toc_df, absent_keywords)
content_hits = line_df[line_df["text"].str.decrease().apply(
lambda t: any(kw in t for kw in absent_keywords)
)]
keyword_envelope = RetrievalResult(
candidates=[],
methods_used=["title_keyword_match", "content_keyword_match"],
not_found=title_hits.empty and content_hits.empty,
not_found_reason="no_keyword_match" if title_hits.empty and content_hits.empty else None,
confidence=0.0 if title_hits.empty and content_hits.empty else 0.8,
)
print("KEYWORD end result on absent matter:")
print(f" not_found = {keyword_envelope.not_found}, purpose = {keyword_envelope.not_found_reason}")
# Embedding aspect: nonetheless returns top-k with non-zero similarities. No threshold tells us "not in doc".
emb_hits, _ = retrieve_pages_by_similarity(page_df, line_df, absent_question, top_k=3, consumer=consumer)
print(f"nEMBEDDING end result on the identical absent matter:")
for _, r in emb_hits.iterrows():
print(f" web page {int(r['page_num']):>2} sim={r['similarity']:.3f} (could be returned as a candidate)")
print(" -> embedding can not say 'not discovered': it at all times returns top-k with steady scores.")
The distinction between the 2 strategies on an absent matter makes the schema invaluable. Asking the Consideration paper about GDPR compliance (a subject it by no means covers), key phrase retrieval flags not_found=True cleanly, whereas embedding retrieval nonetheless returns three pages with non-trivial cosine scores:

3.2 No reply beats a mistaken one
In a client chatbot, a mistaken reply is annoying. In an enterprise doc QA system, it’s costly.
A number of examples:
- A compliance officer asks whether or not a contract has a non-compete clause. The system returns “sure, lasting 3 years” primarily based on a mistaken passage. The officer depends on this in a gathering. The clause seems to be 1 yr. Choices have been made on mistaken info.
- A finance staff asks in regards to the legal responsibility cap on a vendor contract. The system returns the seller’s insurance coverage cap (a distinct quantity, in a distinct part) as a result of retrieval confused the 2. Negotiations proceed on a mistaken assumption. The error is caught a month later.
- A authorized staff asks whether or not a contract covers information breaches. The system returns a passage about basic damages that mentions information tangentially. The staff assumes protection exists. The corporate faces an uninsured incident.
In all of those, no reply would have been higher than a mistaken reply. No reply prompts the person to dig deeper, ask a colleague, learn the doc. Fallacious reply with a assured tone short-circuits that course of and creates a false sense of certainty.
A retrieval pipeline that is aware of the way to say “I didn’t discover something” is extra invaluable than one with the next recall charge however no humility. This isn’t a technical desire, it’s a enterprise requirement.
4. The retrieval output: one JSON prepared for era
The whole lot on this article fed one goal: produce the proper candidates handy to the era stage. The strategies, the LLM arbiter, the dispatcher, the “not discovered” dealing with, all of it converges on a single typed object.
This part names it explicitly. Retrieval delivers one RetrievalResult per (doc, query) pair. The era brick reads it, produces the reply, and by no means has to ask retrieval something extra. A follow-up orchestration loop can lengthen the identical RetrievalResult if era wants extra context, however the contract form stays the identical.
4.1 One candidate, two scopes
Per the anchor-and-context framing of Article 7A (retrieval as filtering), each candidate carries each. The anchor is the place the match landed: a slim line vary on a selected web page, with the part it belongs to. The context is the prolonged window retrieval determined to cross ahead: a paragraph, a piece, or a window of N traces, once more as a line vary with web page bounds.
Why each? Technology wants the anchor for citations (spotlight the matched traces on the PDF, hyperlink the reply again to the exact traces) and the context for grounding (learn the encompassing paragraph or part the reply sits in). Storing solely the context loses the exact quotation. Storing solely the anchor loses the encompassing proof that makes the reply interpretable.
The conference: the context’s vary at all times accommodates the anchor’s vary. The width of the context comes from query parsing, pushed by the 2 orthogonal axes the parser tags: answer_shape (cardinality) and answer_type (worth), plus answer_context on StructuralHints (how a lot surrounding textual content to learn). A (single, quantity) query with answer_context=line will get a slim context (the anchor plus a number of traces of security margin). A (itemizing, textual content) query with answer_context=part will get the entire part.
4.2 The unified schema
class CandidateScope(BaseModel):
"""A spread in line_df: web page + line bounds, plus the part it belongs to."""
page_start: int
page_end: int
line_start: int
line_end: int
section_id: str | None = None
class RetrievedCandidate(BaseModel):
"""One passage retrieved as a potential reply supply."""
candidate_id: str
anchor: CandidateScope # the place the match landed (slim)
context: CandidateScope # what will get handed to era (prolonged)
snippet: str # brief, for the LLM arbiter temporary
textual content: str # full context textual content, for era
strategies: record[str] # which strategies surfaced it
matched_keywords: record[str] # which key phrases landed on the anchor
section_title: str | None = None
position: Literal["primary", "supporting", "tangential"] | None = None
purpose: str | None = None # LLM arbiter justification
class RetrievalResult(BaseModel):
"""The entire retrieval output, handed to era as a single JSON."""
doc_id: str
query: str
candidates: record[RetrievedCandidate] # ordered: main first
methods_used: record[str]
not_found: bool
not_found_reason: str | None = None
confidence: float
The doc_id and query on the high are what makes the end result replayable. Persist this object and you’ll re-run era later, on the identical retrieval, with out paying for retrieval once more. That’s the foundation for the audit path (Part 1.3), for batch analysis, and for any orchestrator that has to check two era prompts on the identical retrieved proof.
4.3 A dwell JSON on the working paper
The identical query we utilized in Part 1 to demo the LLM arbiter: “What positional encoding does the paper use?”. Two main candidates survive, each anchored on the 3.5 Positional Encoding part, with contexts that stretch to the total part physique.
{
"doc_id": "1706.03762v7",
"query": "What positional encoding does the paper use?",
"candidates": [
{
"candidate_id": "p5_l12_l14",
"anchor": {
"page_start": 5,
"page_end": 5,
"line_start": 12,
"line_end": 14,
"section_id": "11"
},
"context": {
"page_start": 5,
"page_end": 6,
"line_start": 1,
"line_end": 40,
"section_id": "11"
},
"snippet": "We use sine and cosine functions of different frequencies...",
"text": "3.5 Positional Encoding [... full section body, 40 lines, elided for the print ...]",
"strategies": [
"title_keyword_match",
"content_keyword_match"
],
"matched_keywords": [
"positional",
"encoding",
"sinusoidal"
],
"section_title": "3.5 Positional Encoding",
"position": "main",
"purpose": "Defines the sinusoidal positional encoding utilized by the paper."
},
{
"candidate_id": "p6_l4_l5",
"anchor": {
"page_start": 6,
"page_end": 6,
"line_start": 4,
"line_end": 5,
"section_id": "11"
},
"context": {
"page_start": 5,
"page_end": 6,
"line_start": 1,
"line_end": 40,
"section_id": "11"
},
"snippet": "We additionally experimented with realized positional embeddings...",
"textual content": "3.5 Positional Encoding [... same full section body as candidate 1, shared context ...]",
"strategies": [
"title_keyword_match",
"content_keyword_match"
],
"matched_keywords": [
"positional",
"encoding",
"learned"
],
"section_title": "3.5 Positional Encoding",
"position": "main",
"purpose": "Mentions the realized variant the paper additionally examined."
}
],
"methods_used": [
"title_keyword_match",
"content_keyword_match",
"llm_arbiter"
],
"not_found": false,
"not_found_reason": null,
"confidence": 0.95
}
Whenever you construct retrieval as a service or a batch step, that is the artifact that goes into the database, will get versioned, and helps replay. It is usually what your auditor reads once they ask why a passage was proven to the person.
The identical cache conference the parsing brick installs applies. save_retrieved_pages(pdf_path, query, retrieved_pages_df) writes the page-level end result (with match_count, matched_keywords columns intact) to output/. The filtered_line_df is deliberately not cached. Technology re-derives it from line_df + web page numbers on the spot. Persisting web page IDs is a budget default; persisting the heavy filtered DataFrame could be duplicate state. This retains every brick boundary clear: retrieval writes web page picks, era reads them, neither wants something extra.
5. Conclusion
Retrieval shouldn’t be search. It’s filtering on structured tables. As soon as parsing has produced line_df and toc_df, each retrieval methodology is a manner of selecting rows out of 1 or each. Anchor detection runs in three levels: key phrase detection on line_df and toc_df (at all times, free) and optionally available embedding similarity in parallel, aggregation to a structural unit (part, web page, chunk), then one LLM arbiter name that ranks the candidates with causes. Key phrases keep always-on as a result of they’re auditable and provides a defensible “not discovered”; embeddings are optionally available and helpful for vocabulary mismatch; BM25 underperforms business-coded key phrase filtering on enterprise questions. Anchor small (line, title), broaden for context (paragraph, part); collapsing the 2 granularities is the most typical pipeline mistake.
Article 8 (era) takes over from right here, the fourth brick. With the proper candidates retrieved on the proper granularity, the LLM nonetheless has actual work: extracting the reply, formatting it, citing it, refusing to invent when the reply shouldn’t be there. That step has to run as managed execution moderately than free-form prediction.
This text is a part of the Enterprise Doc Intelligence sequence. The minimal RAG pipeline reveals the retrieval output feeding era finish to finish on an actual PDF.
6. Sources and additional studying
The BM25 basis the article depends on is Robertson and Zaragoza (The Probabilistic Relevance Framework: BM25 and Past, FnT IR 2009). The rank-fusion mechanic when combining key phrase and embedding scorers is Reciprocal Rank Fusion (Cormack et al., SIGIR 2009). The empirical declare that BM25 stays a robust baseline out-of-distribution is grounded by Thakur et al. (BEIR, NeurIPS 2021). The article is in the identical route because the hybrid-search consensus that Anthropic’s Contextual Retrieval (Sept 2024), Elastic, and Vespa now endorse. The closest revealed equal to the TOC-as-retriever sample is RAPTOR (Sarthi et al., ICLR 2024); the article exploits the doc’s current TOC as a substitute of clustering its personal.
Similar route because the article:
- Robertson & Zaragoza, The Probabilistic Relevance Framework: BM25 and Past, FnT IR 2009. Canonical BM25 reference; the article’s declare that BM25 measures frequency the place enterprise retrieval wants co-occurrence rests on this.
- Cormack, Clarke, Buettcher, Reciprocal Rank Fusion outperforms Condorcet, SIGIR 2009. The fusion mechanic the article makes use of when combining key phrase and embedding scorers.
- Thakur et al., BEIR: A Heterogeneous Benchmark for Zero-shot Analysis of Data Retrieval Fashions, NeurIPS 2021 (arXiv:2104.08663). Empirical assist for the article’s declare that BM25 is a robust baseline that dense retrievers don’t at all times beat.
- Sarthi et al., RAPTOR: Recursive Abstractive Processing for Tree-Organized Retrieval, ICLR 2024 (arXiv:2401.18059). Hierarchical retrieval; the closest revealed equal to the TOC-as-retriever sample. RAPTOR clusters the doc right into a tree; this text makes use of the TOC the doc already declares.
- Anthropic, Contextual Retrieval (Sept 2024 engineering publish). Hybrid-search consensus that the article is in the identical route as.
Totally different angle, totally different context:
- Karpukhin et al., Dense Passage Retrieval for Open-Area Query Answering (DPR), EMNLP 2020 (arXiv:2004.04906). Dense retrieval because the manufacturing default. The context is in-domain open QA; this text places BM25 / key phrases first and embeddings final on enterprise corpora.
- Khattab & Zaharia, ColBERT: Environment friendly and Efficient Passage Search through Contextualized Late Interplay over BERT, SIGIR 2020 (arXiv:2004.12832). Token-level late interplay because the retrieval primitive. Totally different context from this text’s anchor-vs-context separation.
- Izacard et al., Unsupervised Dense Data Retrieval with Contrastive Studying (Contriever), 2022 (arXiv:2112.09118). Unsupervised dense retrieval reaching BM25-grade out-of-distribution efficiency. Helpful distinction with the article’s BM25-first stance on enterprise corpora.
- Izacard et al., Atlas: Few-shot Studying with Retrieval Augmented Language Fashions, 2022 (arXiv:2208.03299). Giant-scale dense retrieval + RAG examine; helpful context for the embedding-first household of approaches.
Earlier within the sequence:
- Doc Intelligence: sequence intro. What the sequence builds, brick by brick, and in what order.
- Baseline Enterprise RAG, from PDF to highlighted reply. The four-brick pipeline finish to finish: PDF in, highlighted reply out.
- Embeddings Aren’t Magic: The Predictable Failure Modes of RAG Retrieval. The place embedding similarity wins (synonyms, typos, paraphrase), the place it predictably breaks (unknown phrases, negation, term-vs-answer relevance), and the way to use it anyway.
- Rerankers Aren’t Magic Both: When the Cross-Encoder Layer Is Well worth the Price. What a cross-encoder provides over bi-encoder embeddings, measured, and when it’s definitely worth the latency.
- RAG shouldn’t be machine studying, and the ML toolkit solves the mistaken drawback. Why chunk-size sweeps and finetuning optimize the mistaken factor; route by query sort as a substitute.
- From regex to imaginative and prescient fashions: which RAG approach matches which drawback. Two axes, doc complexity and query management, that decide the approach for every case.
- 10 frequent RAG errors we maintain seeing in manufacturing. Ten manufacturing errors, organized brick by brick, with the repair for every.
- Past extract_text: the 2 layers of a PDF that drive RAG high quality. The primary half of the parsing brick: the doc’s nature, indicators, and abstract.
- Cease returning flat textual content from a PDF: the relational form RAG wants. The second half of the parsing brick: the relational tables each downstream brick reads.





