Future with Shivank · AI Agents in Finance · Section 10

Future with Shivank · Hands-on track · Section 10

Agentic RAG Search that thinks: route to the right document, split hard questions, check the evidence, and measure whether the answer can be trusted

Plain RAG looks up a few passages and writes an answer in one shot. That is fine for "what was revenue last year?" It breaks on the questions finance people actually ask, which mix a filing, a call transcript and an internal policy, and where a wrong number is a compliance problem. In this section you give retrieval a brain: an agent that decides where to look, notices what is missing, and looks again, plus the retrieval upgrades and the measurements that production teams rely on.

🏦 Tuesday, 9:10 am, Future with Shivank Bank, compliance desk. A portfolio manager wants to open a new position in Acme Robotics (a fictional company) before the market opens. Compliance has one question for you: "Does Acme's Q3 quick ratio satisfy the firm's risk policy?" The answer is spread across three documents: Acme's annual report (10-K), the latest Q3 earnings-call transcript, and the bank's own risk policy. You'll answer this question eight different ways and see exactly which approaches get it right, and why.
3agentic patterns: routing, decomposition, self-correcting agent
8ways to answer the same question, side by side in one lab
8simulations to click through
12interview questions with model answers
ConceptsWhy one-shot retrieval failsFour failure modes on real finance questions, and the three patterns that fix them.
Retrieval upgradesHybrid search + rerankingMeaning search and keyword search fused with RRF (built by hand, free to run), then an LLM reranker.
LabOne question, eight waysLlamaIndex + Claude: naive, router, sub-questions, agent, hybrid, rerank, both, and the RAG triad.
🧠 Analogy💰 Finance corner⚠️ Watch out💡 Tip🎯 Interview angle🧪 Simulation (click it!)

Section 10 · Part 1: the problem

Where one-shot retrieval breaks

10.1Naive RAG vs agentic RAG in one picture

You already know the RAG pipeline: split documents into chunks, turn each chunk into a vector, and at question time fetch the top-k most similar chunks and hand them to the LLM. We'll call that naive RAG. "Naive" isn't an insult: it's the right tool for simple lookups. The word just means it runs the same fixed steps for every question, with no decisions and no checking.

Naive RAG: one shot, same steps every time Questionas typed Embedtext → vector Top-k searchone blended index LLM writesfrom what came back Answernever checked Agentic RAG: a loop with decisions Questionas typed Planwhat is needed? Retrievefrom the right source Checkenough? consistent? Answerwith citations evidence missing or conflicting → look again (up to a step limit)
The only structural change is the decision loop: an LLM decides where to look, judges what came back, and searches again if needed. Everything else (chunks, embeddings, indexes) stays the same.
🧠 Analogy: the library assistant vs the research analyst

Naive RAG is a library assistant who hears your question, grabs the three books whose covers sound most like your words, reads you a paragraph, and leaves. Agentic RAG is a research analyst: they think "I need the company's latest figure and our internal limit", pull the right filing, notice the limit isn't in it, walk to the policy binder, and come back with an answer that cites both pages.

💰 Finance corner: the three documents and the quick ratio read this once

The quick ratio asks: if short-term bills all came due tomorrow, could the company pay them without selling inventory?

quick ratio = (current assets − inventories) ÷ current liabilities Acme, year-end 2024 = (498.0 − 119.8) ÷ 307.4 = 378.2 ÷ 307.4 = 1.23

Below 1.0 means the company needs to sell stock (inventory) or borrow to pay its short-term bills. The current ratio is the same thing with inventory (498.0 ÷ 307.4 = 1.62), so it is always the larger of the two.

DocumentWhat kind of truthKey facts for our question
10-K (annual report, FY2024)Audited, but up to a year oldQuick ratio 1.23, current ratio 1.62 at Dec 31, 2024; covenant: current ratio ≥ 1.25; largest customer 41% of revenue
Q3 earnings call (Oct 2025)Latest, unaudited, management's wordsQuick ratio 1.18 at Sep 30, 2025 (down from 1.23, inventory build); current ratio 1.58
Bank risk policy (v3.2)Rules, not facts about Acme§2.1 quick ratio ≥ 1.00; §2.2 current ratio ≥ 1.50 standard; §2.4 the 10-K is the controlling source, quarterly figures are checked for deterioration; §3.2 customer > 40% → enhanced due diligence

The full correct answer: Yes. The Q3 quick ratio of 1.18 is above the 1.00 minimum (and so is the controlling 10-K figure, 1.23). The memo should note the decline from 1.23 to 1.18. A careful analyst would also flag that the 41% customer concentration triggers enhanced due diligence under §3.2.

Four ways naive RAG fails on finance questions

🧱 Wrong source"Quick ratio" appears in the 10-K, the call and the policy. Similarity can't tell an audited figure from a quarterly one, or a fact from a rule.Result: the year-end 1.23 is quoted as if it were Q3.
🧱 Multi-part questionsOur question needs two facts from two documents. One top-k search over a blended index often returns chunks from only one of them.Result: half the evidence, a confident half-answer.
🧱 No sufficiency checkNothing asks "do I actually have what I need?" The LLM writes from whatever arrived.Result: a guessed number, or the wrong rule applied.
🧱 No other toolsA real check may need arithmetic, a market-data API or a date. Naive RAG can only fetch text.Result: "compute the ratio from these figures" goes wrong.
🧪 Simulation · the top-k lottery

Naive RAG on the compliance question: how many chunks should it fetch?

The blended index holds 10 chunks from the three documents, ranked by similarity to "Does Acme's Q3 quick ratio satisfy the firm's risk policy?" (illustrative scores). ★ marks the two facts the answer needs. Move the slider.

top-k (chunks fetched)3
⚠️ "Just raise k" is not a fix

At k = 3 the policy text crowds out the earnings call, because the question's words ("firm", "risk policy", "quick ratio") match the policy best. At k = 4 both facts arrive, but you can't pick k per question in advance. Raising k further adds the 10-K's 1.23, a competing number from a different period, plus more tokens and noise. The real fix is to decide where to look and check what came back. That's what the next three patterns do.

🎯 Interview angle: "Why not just use a bigger context window?"

Three reasons. Cost and latency grow with every token, on every question. Quality drops when the relevant sentence is buried in a long context. And it doesn't fix the logic: the model still has to know that the policy is a rule, the call is the latest figure and the 10-K is the controlling source. Long context and agentic retrieval work together: the agent keeps the context small and relevant.


Section 10 · Part 2: the three patterns

Three ways to give retrieval a brain

10.2Routing, decomposition, self-correction

All three patterns keep the same indexes. What changes is how much the LLM decides before and during retrieval. Think of it as a dial: more autonomy handles harder questions, but costs more LLM calls and is harder to test.

Routingpick ONE source
1 extra LLM call. For single-source questions over many documents.
Decompositionsplit, then fan out
A plan + one call per part. For questions with independent parts.
Self-correcting agentsearch, check, repeat
As many calls as it needs (capped). For open or dependent questions.

Pattern 1: Routing (pick the right shelf)

Keep one index per document (or per document type) instead of one blended index. Wrap each index as a tool with a name and a one-paragraph description. A selector LLM reads the question and the descriptions and picks the best tool. Only that index is searched.

"What was Acme'sQ3 quick ratio?" LLM selectorreads the descriptions,not the documents annual_report_10kaudited FY2024 figures, year-end ratios, covenants q3_earnings_call ✓latest quarterly figures: Q3 quick ratio… firm_risk_policythe bank's required thresholds and limits
Routing fixes the wrong source failure. The selector's decision and reason are saved in the response metadata, so you can log and audit every routing choice.
🧠 Analogy: the bank's reception desk

A receptionist doesn't know mortgage law or FX hedging. They read the signs on the doors ("Mortgages", "Foreign exchange", "Compliance") and send you to the right one. If the signs are vague ("Department A", "Department B"), even a brilliant receptionist sends you to the wrong room. Tool descriptions are the signs on the doors.

🧪 Simulation · be the router's sign-writer

Same selector, three sets of tool descriptions

Pick a description style and see where four questions are routed.

In LlamaIndex, the router is one object (you build it in the lab):

router = RouterQueryEngine(selector=LLMSingleSelector.from_defaults(), query_engine_tools=tools) router.query(q).metadata["selector_result"] # which tool, and the LLM's stated reason
SelectorHow it answersUse when
LLMSingleSelectorThe LLM writes JSON as text; LlamaIndex parses itAny LLM; our lab uses this
PydanticSingleSelectorUses the model's function calling to return a typed objectThe model supports tool calling; fewer parse errors
LLMMultiSelector / PydanticMultiSelectorCan pick several tools and merge their answersQuestions that touch 2–3 sources but don't need a full plan
💡 Validate routing like any classifier

Keep a small labelled set (question → correct tool), maybe 30–50 questions, and re-measure routing accuracy whenever a description or the document set changes. In production, descriptions are often backed up by hard signals: metadata (doc_type="policy", period="Q3-2025"), keyword rules, or a small trained classifier.

Pattern 2: Query decomposition (split the question)

Routing still sends the whole question to one place, so it can't answer our two-document question. Decomposition asks an LLM to rewrite the question as sub-questions, each tagged with the tool that should answer it. Each sub-question runs as a normal RAG query on its own index, and a final LLM call combines the answers.

"Does Acme's Q3quick ratio satisfythe risk policy?" Questiongenerator1 LLM call "What was Acme's Q3 quick ratio?"→ q3_earnings_callanswer: 1.18 (Sep 30, 2025) "What minimum quick ratio is required?"→ firm_risk_policyanswer: at least 1.00 (§2.1) Synthesize1.18 ≥ 1.00→ yes ✓
Decomposition fixes the multi-part question failure. In LlamaIndex it's SubQuestionQueryEngine with an LLMQuestionGenerator, using the same tools as the router.
🧠 Analogy: the checklist handed to two interns

You write a checklist ("get Acme's Q3 quick ratio from the call transcript", "get our minimum from the policy binder"), give one line to each intern, and combine what they bring back. Fast and clear, as long as neither line depends on the other's answer.

⚠️ The limit: all sub-questions are written up front

The plan is made before any retrieval happens. So it can't handle dependent (multi-hop) questions, where step 2 needs step 1's answer: "Who is Acme's largest customer, and what is that customer's credit rating?" You can't write the second sub-question until you know the customer's name. For chains like this you need retrieval interleaved with reasoning: an agent (next), or research methods such as self-ask (the model asks itself follow-up questions) and IRCoT (retrieve again after every reasoning step).

Pattern 3: The self-correcting agent (search until the file is complete)

Give the same three tools to an agent with a clear goal: "for a compliance check, get the issuer's figure and the policy threshold; if something is missing, search again; if you can't find it, say so." Now the plan isn't fixed. After every tool call the agent looks at what it has and decides the next move.

Compliancequestion Agent (Claude)think → call a tool→ check: enough?max 8 steps firm_risk_policyrule: quick ratio ≥ 1.00 (§2.1) q3_earnings_callfigure: 1.18 at Sep 30, 2025 annual_report_10kcontrolling figure: 1.23 (FY2024) Cited answeror "insufficientevidence" callcallcall
Each tool is a whole RAG query engine over one document. The agent's loop fixes the no sufficiency check failure, and since tools are just functions, you can add a calculator or a market-data API to fix the no other tools failure too.
🧪 Simulation · one agent run, step by step

Watch the agent notice what's missing

The diagram above lights up as you click.

🧠 Analogy: the investigator, not the clerk

A clerk files whatever paper you hand over. An investigator reads the file, says "we have the rule but not the company's number", goes and gets it, and won't sign the report until every claim has a source. The agent's system prompt is its investigation manual.

Guardrails that make the loop safe

1Cite every figureSource document and reporting period ("1.18, Q3 FY2025 call"). Uncited numbers are a red flag in review.
2Cap the stepsmax_iterations stops a confused agent from searching forever. On the cap, write the best answer so far and say it's incomplete.
3Fail safeIf a required figure can't be found: "insufficient evidence", never an estimate. In compliance, a refusal is cheap; a wrong "yes" is expensive.
4Log the trajectoryRecord every tool call and its input. That's how you debug, and how you show an auditor where each number came from.
Research names you may hear in interviews optional
  • Self-RAG: a model trained to decide when to retrieve and to critique its own output with special reflection tokens.
  • CRAG (Corrective RAG): a light evaluator grades the retrieved documents; if they look poor, the system rewrites the query or searches elsewhere (e.g. the web) before answering.
  • FLARE: while writing, if the model is unsure about the next sentence, it pauses and retrieves first.

All three share the idea behind our agent: check retrieval quality, and retrieve again when it isn't good enough.

The race: the same question, five approaches

🧪 Simulation · pattern race

Pick an approach. Watch the evidence, the cost, and the answer.

PatternBest forLLM calls on our questionMain weakness
Naive RAGSingle-fact lookups in one document1Fixed top-k; no source awareness; no check
RouterMany documents, each question has one right source2Only one source per question; depends on descriptions
DecompositionQuestions with independent parts across sources≈4 (1 plan + 1 per part + 1 combine)No dependent multi-hop; plan can't adapt
Self-correcting agentOpen questions, dependent steps, compliance checks≈5–7 (each tool call has its own LLM call inside)Cost and latency vary; harder to test
① Does one document contain the whole answer? → Router (or plain RAG if there's only one document).
② Does the question split into parts that don't depend on each other? → Decomposition.
③ Does a later step need an earlier answer, or must the evidence be checked before answering? → Agent, with a step cap and citation rules.
④ In production, combine them: a cheap router sends easy questions to plain RAG and wakes the agent only for hard ones.
🎯 Interview angle: "Explain agentic RAG in two sentences"

"Naive RAG runs a fixed retrieve-then-generate step. Agentic RAG puts an LLM in control of retrieval: it chooses sources, splits or reformulates the question, checks whether the evidence is sufficient and retrieves again if not, so it handles multi-source and multi-step questions at the cost of more LLM calls." Then add: "I'd use the least autonomy that answers the question: router, then decomposition, then an agent."


Section 10 · Part 3: better retrieval

Hybrid search and reranking

10.3Make every single search better

The three patterns decide where and how often to search. They can't help if each individual search returns the wrong chunks. Two upgrades fix that, and they work with any pattern: hybrid search casts a wider, smarter net (better recall), and reranking keeps only the best catch (better precision).

Recalldid we find it?
Of the chunks that matter, how many made it into the results.
Precisionis it all useful?
Of the chunks we send to the LLM, how many actually matter.

Two kinds of search, two kinds of blind spot

Dense search (embeddings)Sparse search (BM25 keywords)
MatchesMeaning: "liquidity cushion" finds a chunk about the quick ratioExact words, giving extra weight to rare ones
MissesExact tokens: tickers, bond names ("4.25% notes due 2031"), section numbers ("§2.1"), specific figuresSynonyms and paraphrases: "acid-test ratio" won't match "quick ratio"
NeedsAn embedding model (an API call or a GPU)Just word counts: no API, instant, explainable
Finance example"Is the company struggling to pay short-term bills?""CET1 ratio", "Reg SHO", "ACME 2031 notes"
🧠 Analogy: two sniffer dogs

One dog follows the scent of meaning: it finds things that are about the same topic even if the words differ. The other follows exact footprints: it never confuses "Q3" with "Q2", but loses the trail if the words change. Send both, then combine their finds by a fair vote. That vote is reciprocal rank fusion.

BM25 in plain English

BM25 ("best matching, version 25") is the standard keyword-ranking formula, a refined version of the classic TF-IDF. For each word in the question it adds up a score built from three dials:

Term frequency (k1)more is better, up to a pointA chunk that says "quick ratio" twice beats one that says it once, but ten times isn't ten times better. k1 (≈1.2–2.0) sets how fast the bonus flattens out.
Rarity (idf)rare words count more"Acme" appears everywhere in our corpus, so it barely helps. "Quick" appears in a few chunks, so it's a strong signal.
Length (b)long ≠ relevantA long chunk contains more words by accident. b (≈0.75) scales scores down for longer-than-average chunks.

Here it is from scratch: about 20 lines, no libraries. It's part of rrf_by_hand.py, which runs free with no API key (full file in the appendix).

Python · rrf_by_hand.py · BM25 from scratch
import math
import re
from pathlib import Path

DATA_DIR = Path(__file__).parent / "data"


def tokenize(text: str) -> list[str]:
    """Lower-case words and numbers: 'Quick ratio was 1.18.' → ['quick','ratio','was','1.18']"""
    return re.findall(r"[a-z0-9]+(?:\.[0-9]+)?", text.lower())


def bm25_scores(query: str, docs: list[str], k1: float = 1.5, b: float = 0.75) -> list[float]:
    """Score every doc for the query with BM25.

    For each query word:
        idf  = how RARE the word is across all docs   (rare words matter more)
        tf   = how often it appears in THIS doc       (more is better, but saturates)
        norm = penalty for long docs                  (long docs aren't better by default)
    score = Σ idf × tf×(k1+1) / (tf + k1×norm)
    """
    tokenized = [tokenize(d) for d in docs]
    n_docs = len(docs)
    avg_len = sum(len(t) for t in tokenized) / n_docs
    scores = []
    for words in tokenized:
        score = 0.0
        for term in set(tokenize(query)):
            n_with_term = sum(1 for t in tokenized if term in t)
            if n_with_term == 0:
                continue
            idf = math.log(1 + (n_docs - n_with_term + 0.5) / (n_with_term + 0.5))
            tf = words.count(term)
            norm = 1 - b + b * len(words) / avg_len           # = 1 for an average-length doc
            score += idf * tf * (k1 + 1) / (tf + k1 * norm)
        scores.append(score)
    return scores
  1. tokenize turns "Quick ratio was 1.18." into ['quick', 'ratio', 'was', '1.18']. The regex keeps decimal numbers whole, so 1.18 is one "word". That matters in finance.
  2. avg_len is the average chunk length in words; it's the yardstick for the length dial.
  3. For each chunk, for each distinct query word: n_with_term counts the chunks that contain the word, and idf is large when that count is small (a rare word).
  4. tf is how often the word appears in this chunk. The fraction tf × (k1+1) / (tf + k1 × norm) grows with tf but levels off. Try it: with k1 = 1.5 and an average-length chunk, tf = 1 gives 1.0, tf = 2 gives 1.43, tf = 10 gives 2.17.
  5. norm is 1.0 for an average-length chunk, above 1 for a longer one (which lowers the score) and below 1 for a shorter one.

Fusing two rankings: Reciprocal Rank Fusion (RRF)

Now you have two ranked lists. You can't just add the scores: cosine similarities sit around 0.3–0.8, while BM25 scores are unbounded (7.54 in our run). Adding them lets BM25 drown out meaning search. RRF ignores the scores completely and uses only positions:

RRF score(chunk) = Σ over each list that contains it of 1 / (k + rank) rank starts at 0, k = 60 1st place in one list → 1/60 = 0.0167 2nd in one list + 3rd in other → 1/61 + 1/62 = 0.0325 (appearing in BOTH beats topping one)

The constant k = 60 comes from the original RRF paper and is LlamaIndex's default. It makes neighbouring ranks almost equal (1/60 vs 1/61), so agreement between the two searches matters more than who came first. A smaller k gives the top spots more weight.

Python · rrf_by_hand.py · rank_ids and rrf
def rank_ids(scores: list[float]) -> list[int]:
    """Doc ids ordered best → worst (only docs with a positive score)."""
    return [i for i in sorted(range(len(scores)), key=lambda i: -scores[i]) if scores[i] > 0]


def rrf(ranked_lists: list[list[int]], k: int = 60) -> dict[int, float]:
    """Reciprocal Rank Fusion. Each list gives a doc 1/(k + rank), rank starting at 0.

    Raw scores are ignored completely — only POSITIONS count. So a BM25 score of 9.7
    and a cosine of 0.41 can be merged fairly. Appearing in BOTH lists beats topping one.
    """
    fused: dict[int, float] = {}
    for ranking in ranked_lists:
        for rank, doc_id in enumerate(ranking):
            fused[doc_id] = fused.get(doc_id, 0.0) + 1.0 / (k + rank)
    return dict(sorted(fused.items(), key=lambda kv: -kv[1]))
  1. rank_ids sorts chunk ids by score, best first, and drops zero scores (chunks that share no words with the query).
  2. rrf walks each ranked list. enumerate gives the position (0, 1, 2…) and the chunk id; the chunk's running total grows by 1 / (k + rank). A chunk in both lists collects two contributions.
  3. The last line sorts the totals, highest first: that's the fused ranking.
Python · rrf_by_hand.py · the demo
def load_paragraphs() -> list[tuple[str, str]]:
    """(file name, paragraph) for every non-heading paragraph in ./data."""
    out = []
    for path in sorted(DATA_DIR.glob("*.md")):
        for para in path.read_text(encoding="utf-8").split("\n\n"):
            if para.strip() and not para.startswith("#"):
                out.append((path.name, " ".join(para.split())))
    return out


def find(paras, needle: str) -> int:
    return next(i for i, (_, p) in enumerate(paras) if needle in p)


if __name__ == "__main__":
    paras = load_paragraphs()
    texts = [p for _, p in paras]
    question = "Does Acme's Q3 quick ratio satisfy the firm's risk policy?"

    # 1) Keyword side: BM25 over every paragraph
    bm25 = bm25_scores(question, texts)
    bm25_rank = rank_ids(bm25)[:5]

    # 2) Meaning side: in the full lab this list comes from the vector index.
    #    Here we write down a typical dense ranking so the script needs no API key:
    #    embeddings match MEANING, so the paragraph about "liquidity" and "inventory
    #    build" ranks high even though it never says "risk policy".
    dense_rank = [find(paras, "quick ratio at quarter-end"),
                  find(paras, "2.1 Quick ratio"),
                  find(paras, "Should investors worry about liquidity"),
                  find(paras, "2.4 Source of figures"),
                  find(paras, "Excluding inventories")]

    print(f"Question: {question}\n")
    print("BM25 top 5 (keyword match):")
    for r, i in enumerate(bm25_rank):
        print(f"  rank {r}  score {bm25[i]:5.2f}  {paras[i][0]:<26} {texts[i][:55]}…")
    print("\nDense top 5 (meaning match):")
    for r, i in enumerate(dense_rank):
        print(f"  rank {r}               {paras[i][0]:<26} {texts[i][:55]}…")

    # 3) Fuse by rank
    fused = rrf([dense_rank, bm25_rank])
    print("\nRRF fused (k=60):  score = Σ 1/(60 + rank)")
    for i, s in list(fused.items())[:5]:
        where = [name for name, lst in (("dense", dense_rank), ("bm25", bm25_rank)) if i in lst]
        ranks = ", ".join(f"{n}#{(dense_rank if n == 'dense' else bm25_rank).index(i)}" for n in where)
        print(f"  {s:.4f}  [{ranks:<16}] {paras[i][0]:<26} {texts[i][:45]}…")

    # 4) Why not just add the raw scores?
    top_bm25 = bm25[bm25_rank[0]]
    print(f"\nWhy fuse ranks, not scores: a top BM25 score here is {top_bm25:.2f}, while a top")
    print("cosine similarity is usually 0.3–0.8. Adding them lets BM25 drown out meaning search.")
    print(f"1/60 = {1/60:.4f} (1st place in one list)   1/61 + 1/62 = {1/61 + 1/62:.4f} (2nd + 3rd in two lists)")

The demo splits the three documents into paragraphs, ranks them with BM25, takes a typical dense ranking (written down so the script needs no API key; in the lab it comes from the real vector index), and fuses them. Real output:

Question: Does Acme's Q3 quick ratio satisfy the firm's risk policy? BM25 top 5 (keyword match): rank 0 score 7.54 firm_risk_policy.md 2.1 Quick ratio: the issuer's quick ratio must be at le… rank 1 score 5.58 firm_risk_policy.md This policy applies to every new long equity position o… rank 2 score 4.07 firm_risk_policy.md 2.2 Current ratio: a current ratio of at least 1.50 is … rank 3 score 3.97 acme_earnings_call_q3.md **Maria Lopez:** No. We remain well above the covenant … rank 4 score 3.86 acme_earnings_call_q3.md On the balance sheet: our quick ratio at quarter-end, S… Dense top 5 (meaning match): rank 0 acme_earnings_call_q3.md On the balance sheet: our quick ratio at quarter-end, S… rank 1 firm_risk_policy.md 2.1 Quick ratio: the issuer's quick ratio must be at le… rank 2 acme_earnings_call_q3.md **Sam Ortiz, sell-side analyst:** Should investors worr… rank 3 firm_risk_policy.md 2.4 Source of figures: the issuer's most recent audited… rank 4 acme_10k_excerpt.md At December 31, 2024, current assets were $498.0 millio… RRF fused (k=60): score = Σ 1/(60 + rank) 0.0331 [dense#1, bm25#0 ] firm_risk_policy.md 2.1 Quick ratio: the issuer's quick ratio mus… 0.0323 [dense#0, bm25#4 ] acme_earnings_call_q3.md On the balance sheet: our quick ratio at quar… 0.0164 [bm25#1 ] firm_risk_policy.md This policy applies to every new long equity … 0.0161 [dense#2 ] acme_earnings_call_q3.md **Sam Ortiz, sell-side analyst:** Should inve… 0.0161 [bm25#2 ] firm_risk_policy.md 2.2 Current ratio: a current ratio of at leas… Why fuse ranks, not scores: a top BM25 score here is 7.54, while a top cosine similarity is usually 0.3–0.8. Adding them lets BM25 drown out meaning search. 1/60 = 0.0167 (1st place in one list) 1/61 + 1/62 = 0.0325 (2nd + 3rd in two lists)
  1. BM25 alone loves the policy (the question's words "quick ratio", "risk", "policy" all appear there) and puts the Q3 figure only 5th (rank 4).
  2. Dense alone puts the Q3 figure first but includes the analyst's liquidity question, which has no number in it.
  3. Fused, the two chunks that appear in both lists rise to the top: policy §2.1 and the Q3 quick ratio. Those are exactly the two facts our question needs.
🧪 Simulation · RRF vs adding raw scores

Fuse the two lists yourself

★ = the two facts the answer needs. The top 3 fused chunks go to the LLM.

RRF constant k60

In LlamaIndex the whole hybrid set-up is one object, QueryFusionRetriever (lab step 9). Two of its settings are easy to mix up:

SettingWhat it controlsOur choice
num_queriesHow many versions of the question are searched. Above 1, the LLM writes paraphrases and each is searched ("RAG-Fusion"): better recall, extra LLM calls.1: original question only, cheap and repeatable
modeHow the ranked lists are merged. Needed even with one query, because dense + sparse already gives two lists."reciprocal_rerank" = RRF
💰 Finance corner: when search should walk relationships (Graph RAG)

Some questions are about connections, not passages: "Which of our holdings depend on the same actuator supplier as Acme?" or "Which counterparties are exposed to Acme's largest customer?" Graph RAG first extracts entities (companies, suppliers, customers) and relationships into a knowledge graph, then answers by following edges. It's powerful for supply-chain and counterparty questions, but expensive to build and keep current. Reach for it when relationship questions are common, not by default.

Reranking: a wide net, then a careful pick

Index10,000 chunks Hybrid retrievaltop 20 · millisecondsgoal: recall Rerankertop 3 · goal: precision LLM answers
The first stage is fast and wide; the second is slow and careful, but only looks at 20 chunks, not 10,000.
🧠 Analogy: hiring for an analyst role

A keyword screen of 5,000 CVs is fast and finds everyone plausible (recall). Then a senior banker interviews the top 20 properly and keeps 3 (precision). You'd never interview all 5,000, and you'd never hire straight from the keyword screen.

ScorerHow it readsSpeed / costIn LlamaIndex
Bi-encoder (the embedding search itself)Question and chunk turned into vectors separately, then comparedFastest; chunk vectors are pre-computedas_retriever()
Cross-encoderA small model reads question + chunk together and outputs one relevance scoreFast, runs locally, no APISentenceTransformerRerank
LLM rerankerThe LLM sees a numbered list of chunks and ranks them as a group ("listwise")Slowest; one LLM call per batchLLMRerank

LLMRerank works in four moves:

1BatchSplit the candidates into groups of choice_batch_size (10 by default) so each prompt fits.
2ScoreThe LLM replies with lines like Doc: 2, Relevance: 8 (1–10), leaving out chunks it thinks are irrelevant.
3ParseLlamaIndex reads the numbers back and attaches each score to its chunk.
4Keep top_nMerge all batches, sort by score, keep the best top_n, discard the rest.
🧪 Simulation · rerank or not?

"What was Acme's gross margin in fiscal 2024, and why did it expand?"

Six chunks from the 10-K came back from vector search. Only one explains the margin. ★ marks it.

Chunks sent to the LLM2
🎯 Interview angle: "Your RAG misses obvious documents. What do you try, in order?"

"First I check whether the right chunk is anywhere in the top 20–50; if not, it's a recall problem: add BM25 for hybrid search, fix chunking, add metadata filters (ticker, period, document type), or route to per-document indexes. If it's in the top 50 but not the top 3, it's a precision problem: add a reranker, a cross-encoder first since it's cheap, or an LLM reranker if quality matters more than latency. And I'd measure each change on a labelled question set, not on one example."


Section 10 · Part 4: measurement

How do you know the answer can be trusted?

10.4The RAG triad: three checks, three failure modes

A RAG answer touches three things: the question, the retrieved context, and the generated answer. Check each pair and you get the three standard metrics. Each one points at a different broken part, which is why you need all three.

Question Retrieved contextthe chunks Answerwhat the LLM wrote Context relevancy did we fetch the right chunks? → judges the RETRIEVER Answer relevancy did we answer what was asked? → judges the whole response Faithfulness is every claim backed by the chunks? → judges the GENERATOR
Faithfulness and answer relevancy grade the answer; context relevancy grades the retrieval. Libraries such as RAGAS, DeepEval and TruLens all implement versions of this triad.
🧠 Analogy: three questions an editor asks a junior analyst

"Did you pull the right sources?" (context relevancy) · "Can you show me where every sentence comes from?" (faithfulness) · "Did you actually answer the client's question?" (answer relevancy). A report can pass two and fail the third, and each failure has a different fix.

Faithfulness, step by step

Faithfulness catches hallucination: claims the context doesn't support. A judge LLM (1) splits the answer into separate claims, (2) checks each claim against the retrieved chunks, and (3) scores supported claims ÷ total claims. Note that "true in the real world" isn't enough: the claim must be supported by the retrieved context.

🧪 Simulation · grade this answer yourself

Q: "What was Acme's net income per diluted share in fiscal 2024?"

Retrieved context: "Net income was $96.3 million. Diluted earnings per share were $1.92, compared with $1.51 in fiscal 2023. EBITDA was $131.0 million."
Tick each claim in the answer that this context supports.

💰 Why finance demands 1.0 faithfulness

In a chatbot, 0.9 faithfulness sounds great. In a compliance memo, it means one claim in ten has no source, and you don't know which one. Production finance systems typically require every figure to be supported (faithfulness = 1.0, or a hard per-claim check) and block or escalate anything else. Derived numbers (like a growth rate) should either be computed by a tool, so the calculation is on record, or shown with their inputs.

The other two metrics

MetricHow it's computedLow score means
Answer relevancyA judge checks how much of the answer addresses the question (some libraries also generate questions from the answer and compare them to the original)Grounded, but answered a different question: gave the year-end figure when Q3 was asked
Context relevancyA judge checks how much of the retrieved context is relevant to the questionThe retriever fetched noise: fix chunking, routing, hybrid search or reranking
🧪 Simulation · diagnose the RAG system (interview practice)

Three scores came back. What do you fix first?

Pick an answer.

The triad in LlamaIndex

LlamaIndex ships one evaluator per metric. Each is an LLM judge with a fixed grading prompt, and each returns an EvaluationResult:

EvaluatorJudge prompt asks forWhat you read
FaithfulnessEvaluatorYES / NO: is the answer supported by the context?result.passing (True / False)
AnswerRelevancyEvaluatorFeedback, then [RESULT] and an integer out of 2result.score, normalised to 0–1
ContextRelevancyEvaluatorFeedback, then [RESULT] and a number out of 4result.score, normalised to 0–1
⚠️ The judge is a model too

LLM judges vary run to run and between model versions. For scores you can compare over time: pin the judge model and its version, keep the grading prompt under version control, run on a fixed labelled question set, and check the judge against human grades on a sample. Section 11 goes deep on calibrating judges.


Section 10 · Part 5: hands-on lab

Lab: one compliance question, eight ways

10.5Build every pattern on the same three documents

📅 Tuesday, 9:25 am. You build a small script that answers the compliance question with every approach from this section and prints the answers side by side, with the exact chunks each one used. When the portfolio manager asks "why should I trust the agent's answer?", you'll have the evidence.

What you're building

section10_agentic_rag/ ├── .env # ANTHROPIC_API_KEY=... OPENAI_API_KEY=... (embeddings only) ├── agentic_rag_lab.py # the lab: 8 steps, run all or one ├── rrf_by_hand.py # free: BM25 + RRF from scratch (you saw it in 10.3) └── data/ ├── acme_10k_excerpt.md # FY2024 annual report excerpt ├── acme_earnings_call_q3.md # Q3 FY2025 call transcript excerpt └── firm_risk_policy.md # the bank's liquidity policy v3.2
Terminal · set up once (Python 3.10+)
python -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install llama-index-core llama-index-llms-anthropic llama-index-embeddings-openai \
            llama-index-retrievers-bm25 python-dotenv
# .env next to the script:
#   ANTHROPIC_API_KEY=sk-ant-...
#   OPENAI_API_KEY=sk-...
python agentic_rag_lab.py            # all eight steps + the side-by-side table
python agentic_rag_lab.py agent      # or a single step

All files, including the three documents, are in the Complete code appendix. A full run makes roughly 40 Claude calls; embeddings cost a fraction of a cent.

data/3 markdown files load_indices()3 separate indexes load_combined_index()1 blended index 3 described toolsbuild_query_engine_tools hybrid retrieverdense + BM25 + RRF router · subq · agent (+ rerank, evaluate use the 10-K index directly) hybrid · hybrid_rerank naive (top-3)
The corpus is embedded once in main(); every step reuses the same indexes.

Step 1: setup and the one global switchboard

Python · agentic_rag_lab.py · setup
from __future__ import annotations

import asyncio
import sys
from pathlib import Path

from dotenv import load_dotenv
from llama_index.core import Settings, SimpleDirectoryReader, VectorStoreIndex

load_dotenv()

DATA_DIR = Path(__file__).parent / "data"
SOURCES = {                                  # short key  → file in ./data
    "ten_k": "acme_10k_excerpt.md",
    "earnings_call": "acme_earnings_call_q3.md",
    "risk_policy": "firm_risk_policy.md",
}
COMPARISON_QUESTION = "Does Acme's Q3 quick ratio satisfy the firm's risk policy?"

LLM_MODEL = "claude-sonnet-5-5"              # the reasoning + answer-writing model
EMBED_MODEL = "text-embedding-3-small"       # turns text into vectors for search


def configure_models() -> None:
    """Set the global models once; every index, engine and agent below reuses them."""
    from llama_index.embeddings.openai import OpenAIEmbedding
    from llama_index.llms.anthropic import Anthropic

    Settings.llm = Anthropic(model=LLM_MODEL, max_tokens=2048)
    Settings.embed_model = OpenAIEmbedding(model=EMBED_MODEL)


# Small chunks (≈150 tokens) so each document becomes several pieces. With one
# giant chunk per file, "top-3" would simply fetch the whole corpus and hide the
# problems naive RAG has on real, long filings.
Settings.chunk_size = 150
Settings.chunk_overlap = 20
  1. DATA_DIR is "the data folder next to this script", so the script works from any terminal location. Path(__file__).parent is the script's own folder.
  2. SOURCES maps a short key to a file name: "ten_k" → "acme_10k_excerpt.md". Later code loops over it, so adding a fourth document is one line.
  3. configure_models() sets LlamaIndex's global Settings: Claude writes and reasons, an OpenAI model turns text into vectors. Every index, engine and agent below picks these up automatically. The imports are inside the function so the file can be imported (for example, by a test with fake models) without API keys.
  4. Settings.chunk_size = 150 (tokens) splits each document into 3–4 chunks. With the default (1,024 tokens) each of our short files would be one chunk, and "top-3" would quietly fetch the whole corpus, hiding exactly the problems real 200-page filings cause. chunk_overlap = 20 repeats a little text between neighbouring chunks so a sentence cut in half still appears whole somewhere.
💡 Model IDs

LLM_MODEL is the only line to change if you want a different Claude model. Use a current model ID from the provider's model list; Claude handles reasoning and tool calls here, and the embedding model only needs to be cheap and consistent (re-embed everything if you ever change it).

Step 2: a printer that shows the evidence

Python · agentic_rag_lab.py · show
COMPARISON: dict[str, str] = {}              # step name → answer to COMPARISON_QUESTION


def _source_of(node) -> str:
    return node.metadata.get("source", "(sub-answer)")   # sub-question answers have no file


def show(title: str, question: str, answer, nodes=None) -> None:
    """Print a question, the answer, and WHICH chunks the answer was built from."""
    nodes = nodes if nodes is not None else getattr(answer, "source_nodes", []) or []
    print(f"\n{'=' * 78}\n{title}\nQ: {question}\n{'-' * 78}")
    print(f"A: {str(answer).strip()}")
    print(f"\n  evidence used ({len(nodes)} chunks):")
    for n in nodes:
        score = f"{n.score:.3f}" if n.score is not None else "  -  "
        snippet = " ".join(n.node.get_content().split())[:70]
        print(f"   [{score}] {_source_of(n):<26} {snippet}…")
  1. Every LlamaIndex query returns a Response. str(response) is the answer text; response.source_nodes is the list of chunks it was built from.
  2. Each item is a NodeWithScore: .score is the similarity (or the reranker's 1–10 score), .node.get_content() is the chunk text, and .metadata["source"] is the file name we attach in step 3.
  3. The agent doesn't return source_nodes itself (its evidence comes from tool calls), so show() also accepts a nodes list we collect separately in step 8.

Step 3: separate indexes and one blended index

Python · agentic_rag_lab.py · loading and indexing
def _load(files: list[str]):
    """Read files from ./data and tag every document with its file name as 'source'."""
    return SimpleDirectoryReader(
        input_files=[DATA_DIR / f for f in files],
        file_metadata=lambda path: {"source": Path(path).name},
    ).load_data()


def load_indices() -> dict[str, VectorStoreIndex]:
    """One SEPARATE vector index per document — this is what makes routing possible."""
    return {key: VectorStoreIndex.from_documents(_load([fname]))
            for key, fname in SOURCES.items()}


def load_combined_index() -> VectorStoreIndex:
    """ONE index with all three documents blended together (the naive set-up)."""
    return VectorStoreIndex.from_documents(_load(list(SOURCES.values())))
  1. file_metadata=lambda path: {"source": …} stamps every document (and so every chunk) with its file name. That label is printed with the evidence, and LlamaIndex includes metadata in the text the LLM sees, which helps it cite sources.
  2. load_indices() follows the variable flow: ("ten_k", "acme_10k_excerpt.md") → _load([...]) → one Document → VectorStoreIndex.from_documents splits it into ~4 chunks, embeds each one and stores the vectors in memory → indices["ten_k"]. Three keys, three separate indexes. This is what makes routing possible.
  3. load_combined_index() puts all three documents into one index: the naive set-up, and the pool our hybrid retriever searches.

Step 4: the naive baseline

Python · agentic_rag_lab.py · step_naive
def step_naive(combined: VectorStoreIndex) -> None:
    engine = combined.as_query_engine(similarity_top_k=3)     # fetch 3 chunks, then answer

    simple = "What was Acme's full-year 2024 total revenue?"  # one fact, one document
    show("NAIVE RAG — single fact", simple, engine.query(simple))

    answer = engine.query(COMPARISON_QUESTION)                # two facts, two documents
    show("NAIVE RAG — cross-document question", COMPARISON_QUESTION, answer)
    COMPARISON["naive"] = str(answer)

as_query_engine(similarity_top_k=3) builds the classic pipeline: embed the question → fetch the 3 nearest chunks → one LLM call writes the answer. The single-fact revenue question works. On the comparison question, watch which documents the 3 chunks come from: often all from the policy (as in the top-k simulation in 10.1), so the Q3 figure never reaches the LLM.

Step 5: turn each index into a described tool

Python · agentic_rag_lab.py · build_query_engine_tools
from llama_index.core.tools import QueryEngineTool


def build_query_engine_tools(indices: dict[str, VectorStoreIndex]) -> list[QueryEngineTool]:
    """Wrap each document index as a TOOL with a name and a plain-English description.

    The LLM never sees the documents when it chooses — it only reads these
    descriptions. Vague or overlapping descriptions = wrong source picked.
    """
    return [
        QueryEngineTool.from_defaults(
            query_engine=indices["ten_k"].as_query_engine(similarity_top_k=3),
            name="annual_report_10k",
            description=(
                "Acme Robotics' audited FY2024 annual report (Form 10-K). Full-year "
                "revenue, margins, EPS, year-end balance sheet, year-end current and "
                "quick ratios, credit-facility covenants and risk factors."),
        ),
        QueryEngineTool.from_defaults(
            query_engine=indices["earnings_call"].as_query_engine(similarity_top_k=3),
            name="q3_earnings_call",
            description=(
                "Acme Robotics' Q3 FY2025 earnings-call transcript (October 2025). "
                "Most recent quarterly figures: Q3 revenue, Q3 quick and current "
                "ratios, inventory build, raised guidance, analyst Q&A."),
        ),
        QueryEngineTool.from_defaults(
            query_engine=indices["risk_policy"].as_query_engine(similarity_top_k=3),
            name="firm_risk_policy",
            description=(
                "Future with Shivank Bank's internal liquidity and counterparty risk "
                "policy. The REQUIRED thresholds for a new long position: minimum "
                "quick ratio, current-ratio bands, max net debt/EBITDA, which source "
                "is controlling, concentration limits."),
        ),
    ]
  1. QueryEngineTool.from_defaults wraps a whole RAG pipeline (one document's query engine) as a tool with a name and a description. Router, sub-question engine and agent all consume the same list.
  2. Read the descriptions closely. Each says what makes its document different: "audited FY2024" and "year-end" for the 10-K, "most recent quarterly" and "Q3" for the call, "REQUIRED thresholds" for the policy. That's what lets an LLM route "Q3 quick ratio" to the call and "minimum quick ratio" to the policy.
  3. Each tool searches with similarity_top_k=3 inside its own document, so it can't be crowded out by the other two.

Step 6: the router

Python · agentic_rag_lab.py · step_router
from llama_index.core.query_engine import RouterQueryEngine
from llama_index.core.selectors import LLMSingleSelector


def step_router(indices: dict[str, VectorStoreIndex]) -> None:
    router = RouterQueryEngine(
        selector=LLMSingleSelector.from_defaults(),            # LLM picks exactly ONE tool
        query_engine_tools=build_query_engine_tools(indices),
    )
    tool_names = [t.metadata.name for t in build_query_engine_tools(indices)]

    for q in ["What is the firm's minimum required quick ratio for a new long position?",
              "What was Acme's Q3 quick ratio?",
              "What credit-facility covenants does Acme disclose in its 10-K?",
              COMPARISON_QUESTION]:
        answer = router.query(q)
        pick = answer.metadata["selector_result"].selections[0]   # the routing decision
        show(f"ROUTER → picked '{tool_names[pick.index]}'  (why: {pick.reason[:60]}…)",
             q, answer)
    COMPARISON["router"] = str(answer)                     # answer to the last question
  1. RouterQueryEngine = selector + tools. For each question: 1 LLM call to choose a tool, then that tool's own RAG query (1 more LLM call).
  2. answer.metadata["selector_result"].selections[0] is the decision: .index (0, 1 or 2, a position in the tools list) and .reason (the LLM's explanation). tool_names[pick.index] turns the position into a readable name. Log both in production.
  3. Three single-source questions show correct routing. The fourth is our comparison question: the router can only pick one document, so it will answer half the question, or borrow a nearby rule. You'll see that in the results.
  4. After the loop, answer still holds the last answer, the comparison question's, which goes into COMPARISON.

Step 7: sub-question decomposition

Python · agentic_rag_lab.py · step_subquestion
from llama_index.core.query_engine import SubQuestionQueryEngine
from llama_index.core.question_gen import LLMQuestionGenerator


def step_subquestion(indices: dict[str, VectorStoreIndex]) -> None:
    engine = SubQuestionQueryEngine.from_defaults(
        query_engine_tools=build_query_engine_tools(indices),
        # Pass the generator explicitly; the default one is OpenAI-specific.
        question_gen=LLMQuestionGenerator.from_defaults(),
        verbose=True,                       # prints each generated sub-question + tool
    )
    spanning = ("How did Acme's quick ratio change from year-end 2024 to Q3, and does "
                "the Q3 level breach the firm's risk policy?")
    show("SUB-QUESTIONS — trend + policy", spanning, engine.query(spanning))

    answer = engine.query(COMPARISON_QUESTION)
    show("SUB-QUESTIONS — comparison question", COMPARISON_QUESTION, answer)
    COMPARISON["subq"] = str(answer)
  1. Variable flow: the question + the tool names and descriptions → LLMQuestionGenerator (1 LLM call) → a JSON list like [{"sub_question": "What was Acme's Q3 quick ratio?", "tool_name": "q3_earnings_call"}, …] → each sub-question runs on its tool → a final LLM call combines the sub-answers.
  2. We pass question_gen explicitly because LlamaIndex's default generator is OpenAI-specific (it uses OpenAI function calling and an extra package); the LLM-prompted generator works with any model, including Claude. The sub-questions themselves run concurrently by default, so two sub-questions take about as long as one.
  3. verbose=True prints each sub-question, its tool, and its answer in colour as it runs: the easiest way to see the plan.
  4. The "spanning" question has three parts (year-end, Q3, policy), so expect three sub-questions there and two for the comparison question. In show(), the sub-answers themselves appear as evidence labelled (sub-answer).

Step 8: the self-correcting agent

Python · agentic_rag_lab.py · the agent
from llama_index.core.agent.workflow import FunctionAgent, ToolCallResult

AGENT_SYSTEM_PROMPT = (
    "You are a buy-side compliance analyst. Answer using ONLY the document tools "
    "provided. First work out what evidence the question needs: a compliance check "
    "usually needs BOTH the issuer's figure from its filings AND the matching "
    "threshold from the firm's risk policy. Before concluding, check that you have "
    "every piece; if one tool call did not give you everything, call another tool. "
    "If a required figure cannot be found, say so explicitly instead of estimating. "
    "Cite the source document and reporting period for every figure you use."
)
MAX_AGENT_STEPS = 8          # guardrail: never loop forever, however confused the model is


def run_agent_sync(agent: FunctionAgent, task: str):
    """Run the agent; also record its tool calls (the 'trajectory') and evidence chunks."""
    trajectory: list[str] = []
    evidence: list = []

    async def _run():
        handler = agent.run(task, max_iterations=MAX_AGENT_STEPS,
                            early_stopping_method="generate")
        async for event in handler.stream_events():          # watch it work, live
            if isinstance(event, ToolCallResult):
                trajectory.append(f"{event.tool_name}({event.tool_kwargs.get('input', '')!r})")
                raw = getattr(event.tool_output, "raw_output", None)   # the tool's Response
                evidence.extend(getattr(raw, "source_nodes", None) or [])
        return await handler

    response = asyncio.run(_run())
    return response, trajectory, evidence


def step_agent(indices: dict[str, VectorStoreIndex]) -> None:
    agent = FunctionAgent(
        tools=build_query_engine_tools(indices),
        llm=Settings.llm,
        system_prompt=AGENT_SYSTEM_PROMPT,
    )
    task = ("Can we open a new long position in Acme Robotics under the firm's liquidity "
            "policy? Check the quick-ratio rule against Acme's most recent disclosed "
            "quick ratio.")
    for q, keep in ((task, False), (COMPARISON_QUESTION, True)):
        response, trajectory, evidence = run_agent_sync(agent, q)
        print("\n  agent tool calls, in order:")
        for i, call in enumerate(trajectory, 1):
            print(f"   {i}. {call}")
        show("SELF-CORRECTING AGENT", q, response, evidence)
        if keep:
            COMPARISON["agent"] = str(response)
  1. AGENT_SYSTEM_PROMPT is the investigation manual: work out what evidence is needed (figure and threshold), check before concluding, call another tool if something's missing, never estimate, cite document and period. The loop's behaviour comes from these sentences.
  2. agent.run(task, max_iterations=8, early_stopping_method="generate") starts the run and returns a handler straight away; the agent works in the background. The step cap is a guardrail; "generate" means "at the cap, write the best answer from what you have" instead of raising an error.
  3. async for event in handler.stream_events() lets us watch it work. Each ToolCallResult event carries tool_name (which document), tool_kwargs["input"] (the search the agent wrote, e.g. "Acme Q3 quick ratio"), and tool_output.raw_output, the tool's full Response, whose source_nodes are the chunks. We append those to trajectory and evidence.
  4. await handler waits for the final answer. asyncio.run(_run()) runs the async code from ordinary synchronous Python.
  5. The printed trajectory is the proof of self-correction: typically firm_risk_policy(...) first, then q3_earnings_call(...) once the agent notices it has the rule but not the figure.

Step 9: hybrid retrieval

Python · agentic_rag_lab.py · build_hybrid_retriever and step_hybrid
from llama_index.core.query_engine import RetrieverQueryEngine
from llama_index.core.retrievers import QueryFusionRetriever
from llama_index.retrievers.bm25 import BM25Retriever


def build_hybrid_retriever(combined: VectorStoreIndex) -> QueryFusionRetriever:
    """Meaning search + keyword search over the SAME chunks, merged by rank (RRF)."""
    dense = combined.as_retriever(similarity_top_k=5)                  # by meaning
    sparse = BM25Retriever.from_defaults(docstore=combined.docstore,   # by exact words
                                         similarity_top_k=5)
    return QueryFusionRetriever(
        [dense, sparse],
        similarity_top_k=5,          # keep the best 5 after fusion
        num_queries=1,               # 1 = no LLM rewrites of the question (cheap, repeatable)
        mode="reciprocal_rerank",    # Reciprocal Rank Fusion: score = Σ 1/(60 + rank)
        use_async=False,
    )


def step_hybrid(combined: VectorStoreIndex) -> None:
    engine = RetrieverQueryEngine.from_args(build_hybrid_retriever(combined))
    answer = engine.query(COMPARISON_QUESTION)
    show("HYBRID (dense + BM25, fused)", COMPARISON_QUESTION, answer)
    COMPARISON["hybrid"] = str(answer)
  1. combined.as_retriever(similarity_top_k=5) is the dense side. A retriever only fetches chunks; a query engine fetches and then writes an answer.
  2. BM25Retriever.from_defaults(docstore=combined.docstore) builds a keyword index over the same chunks; the docstore holds every chunk's text. No embeddings, no API calls.
  3. QueryFusionRetriever runs both, fuses with RRF (mode="reciprocal_rerank", k = 60), and keeps the top 5. num_queries=1 means no LLM-written paraphrases.
  4. RetrieverQueryEngine.from_args(retriever) adds the answer-writing step on top. On a corpus this tiny the fused scores look alike (≈0.016 vs ≈0.033); on thousands of chunks the differences matter much more.

Step 10: reranking

Python · agentic_rag_lab.py · step_rerank
from llama_index.core.postprocessor import LLMRerank


def step_rerank(indices: dict[str, VectorStoreIndex]) -> None:
    engine = indices["ten_k"].as_query_engine(
        similarity_top_k=6,                        # cast a wide net…
        node_postprocessors=[LLMRerank(top_n=2)],  # …then the LLM keeps the best 2
    )
    q = "What was Acme's gross margin in fiscal 2024 and why did it expand?"
    show("RERANK (top-6 → best 2)", q, engine.query(q))

node_postprocessors is a list of steps that run after retrieval and before the answer. Each can filter, reorder or trim chunks (others drop low-similarity chunks or stale dates). LLMRerank(top_n=2) sends the 6 candidates to Claude in one batch, gets Doc: n, Relevance: s lines back, and keeps the best 2. Cost: +1 LLM call. We use a single-document question on purpose: reranking is a precision tool.

Step 11: hybrid + rerank, the production default

Python · agentic_rag_lab.py · step_hybrid_rerank
def step_hybrid_rerank(combined: VectorStoreIndex) -> None:
    engine = RetrieverQueryEngine.from_args(
        build_hybrid_retriever(combined),                  # recall: wide, fused pool
        node_postprocessors=[LLMRerank(top_n=3)],          # precision: keep the best 3
    )
    answer = engine.query(COMPARISON_QUESTION)
    show("HYBRID + RERANK", COMPARISON_QUESTION, answer)
    COMPARISON["hybrid_rerank"] = str(answer)

The only change from step 9 is one argument. Hybrid search maximizes recall (the right chunk is probably in the pool of 5), the reranker restores precision (only the best 3 reach the LLM). This same engine can be wrapped as a tool, so the router and agent get better retrieval for free.

Step 12: grade an answer with the triad

Python · agentic_rag_lab.py · step_evaluate
from llama_index.core.evaluation import (
    AnswerRelevancyEvaluator,
    ContextRelevancyEvaluator,
    FaithfulnessEvaluator,
)


def step_evaluate(indices: dict[str, VectorStoreIndex]) -> dict:
    engine = indices["ten_k"].as_query_engine(similarity_top_k=3)
    q = "What was Acme's net income per diluted share in fiscal 2024?"
    response = engine.query(q)
    show("EVALUATE — the answer being graded", q, response)

    # The RAG triad. Each uses the LLM as a judge with a fixed grading prompt.
    faithful = FaithfulnessEvaluator().evaluate_response(response=response)
    answer_rel = AnswerRelevancyEvaluator().evaluate_response(query=q, response=response)
    context_rel = ContextRelevancyEvaluator().evaluate_response(query=q, response=response)

    scores = {
        "faithful": faithful.passing,          # True/False: every claim backed by chunks?
        "answer_relevancy": answer_rel.score,  # 0–1: does the answer address the question?
        "context_relevancy": context_rel.score,  # 0–1: were the fetched chunks on topic?
    }
    print("\n  RAG triad:", scores)
    return scores
  1. Each evaluator reads response.source_nodes as the context automatically, so you only pass the response (and the question, for the two relevancy metrics).
  2. Each evaluate_response is one or more judge calls to Settings.llm. In production you'd often use a different model as the judge, to avoid a model grading its own homework.
  3. For this simple question expect faithful=True and high relevancy. The interesting cases are the failures: run the evaluators on the router's comparison answer and see faithfulness or relevancy drop.

Step 13: run it all, or one step

Python · agentic_rag_lab.py · main
STEPS = {
    "naive":         lambda ix, comb: step_naive(comb),
    "router":        lambda ix, comb: step_router(ix),
    "subq":          lambda ix, comb: step_subquestion(ix),
    "agent":         lambda ix, comb: step_agent(ix),
    "hybrid":        lambda ix, comb: step_hybrid(comb),
    "rerank":        lambda ix, comb: step_rerank(ix),
    "hybrid_rerank": lambda ix, comb: step_hybrid_rerank(comb),
    "evaluate":      lambda ix, comb: step_evaluate(ix),
}


def main(selected: list[str]) -> None:
    indices, combined = load_indices(), load_combined_index()   # embeds the corpus once
    for name in selected:
        STEPS[name](indices, combined)

    if len(COMPARISON) > 1:                                      # the side-by-side view
        print(f"\n{'#' * 78}\nSAME QUESTION, EVERY PATTERN: {COMPARISON_QUESTION}\n{'#' * 78}")
        for name, answer in COMPARISON.items():
            print(f"\n[{name}]\n  " + " ".join(answer.split())[:400])


if __name__ == "__main__":
    wanted = sys.argv[1:] or list(STEPS)
    unknown = [w for w in wanted if w not in STEPS]
    if unknown:
        sys.exit(f"Unknown step(s) {unknown}. Choose from: {', '.join(STEPS)}")
    configure_models()
    main(wanted)
  1. STEPS maps a name to a small function. Every function takes (indices, combined) and uses what it needs, so main can call any of them the same way.
  2. main builds the indexes once, runs the chosen steps, then prints every pattern's answer to the comparison question, side by side.
  3. A mistyped step name (python agentic_rag_lab.py routr) exits with the list of valid names before any API call is made.

Section 10 · Part 6: results

What the side-by-side table teaches

10.6Reading the results

Here is what the final comparison typically looks like. It's illustrative and abridged: LLM wording changes on every run, and which chunks naive RAG fetches depends on the embedding model. The pattern of results is what's stable, and it's what you should be able to explain in an interview.

############################################################################## SAME QUESTION, EVERY PATTERN: Does Acme's Q3 quick ratio satisfy the firm's risk policy? ############################################################################## [naive] The firm's risk policy requires a quick ratio of at least 1.00 for a new long position (section 2.1). The provided context does not state Acme's Q3 quick ratio, so compliance cannot be confirmed. [router] Yes. Acme's quick ratio was 1.18 at the end of Q3, and management noted the company remains well above the 1.25 minimum in its credit facility. [subq] Yes. Acme's Q3 quick ratio was 1.18 (Q3 FY2025 earnings call), above the 1.00 minimum required by the firm's risk policy (section 2.1). [agent] Yes. Acme's quick ratio at September 30, 2025 was 1.18 (Q3 FY2025 earnings call); the policy requires at least 1.00 for a new long position (risk policy 2.1). Note: it fell from 1.23 at year-end 2024 (FY2024 10-K) because of an inventory build. Under 2.4 the decline should be recorded in the investment memo. [hybrid] Yes. The policy requires a quick ratio of at least 1.00, and Acme reported 1.18 for Q3. [hybrid_rerank] Yes. Acme's Q3 quick ratio of 1.18 exceeds the 1.00 minimum in section 2.1 of the policy.
Naive: honest, but half an answerTop-3 came back from the policy only, so the Q3 figure never reached the LLM. With a good prompt it says so; with a weaker prompt it might guess a number, which is worse.Fix: routing or decomposition, not a bigger k.
Router: right verdict, wrong reasonIt searched only the call transcript, found 1.18, and compared it with the lender's 1.25 current-ratio covenant: a different ratio from a different rulebook (and 1.18 is below 1.25, so the sentence contradicts itself). It looks fine at a glance and fails an audit.Fix: never route a multi-source question to one source; use decomposition or a multi-selector, and check faithfulness.
Decomposition: correct and citedThe two parts were obvious up front, so the plan worked first time. About 4 LLM calls.Best value when the parts are independent.
Agent: correct, cited and carefulIt noticed the missing figure, fetched it, and added what a compliance reviewer wants: the trend and the controlling-source rule. About 5–7 LLM calls, and the number varies by run.Best for memos and checks that must stand up to review.
Hybrid (+ rerank): correct here, but blindFusion pulled both key chunks into one pool, so one LLM call could answer. But there's no reasoning loop: had a figure been missing, nothing would have noticed.Better evidence, not better thinking.
The big lessonRetrieval upgrades (hybrid, rerank) and reasoning loops (router, decomposition, agent) fix different failures. Production stacks use both: the agent's tools are themselves hybrid + rerank engines.Agent on top, good retrieval underneath.

From lab to production: what changes in a real bank

ConcernWhat to do
Fresh documentsNew 10-Qs, call transcripts and policy versions arrive constantly. Index incrementally and store filing date, period and version as metadata, so "latest" is a filter, not a guess.
Metadata filtersFilter by ticker, period and document type before similarity search. That alone stops a 2023 figure leaking into a 2025 answer.
Entitlements and information barriersDeal teams may hold material non-public information (MNPI) that research must never see. Enforce access by filtering retrieval on the user's permissions in code, never by asking the LLM to "ignore" documents.
Conflicting sourcesWrite the source hierarchy down (like policy §2.4: the 10-K controls, quarterly figures are checked for deterioration) and give it to the agent. Show both values with their periods instead of silently picking one.
Citations a reviewer can clickReturn chunk ids, document, page and period with every answer, so a human can verify in seconds.
Cost and latencyRoute easy questions to plain RAG; cap agent steps; prefer a cross-encoder reranker; cache embeddings and frequent answers; keep num_queries=1 unless recall demands more.
Evaluation on every changeA fixed labelled set: routing accuracy, triad scores, and "must refuse" cases where the evidence doesn't exist. Section 11 builds this out.
🎯 Interview angle: "The 10-K says 1.23 and the Q3 call says 1.18. Which does your system use?"

"Neither silently. The firm's policy decides: here the audited 10-K is the controlling source, and quarterly figures are checked for deterioration. So the agent reports both with their periods, applies the rule to the controlling figure, flags the decline, and escalates if the latest figure breaches a limit. I'd put that hierarchy in the agent's instructions and in document metadata, and add a test case where the two sources disagree."


Interview prep

12 questions you can now answer well

Click a question, answer it out loud first, then compare. Good answers are short, give a reason, and name a trade-off.

What is agentic RAG, and how is it different from naive RAG?

Naive RAG runs a fixed pipeline: embed the question, fetch the top-k chunks, generate once. Agentic RAG puts an LLM in control of retrieval: it chooses which source to search, can split or rephrase the question, checks whether the evidence is enough, and searches again if it isn't. It handles multi-source and multi-step questions, at the cost of more LLM calls and less predictable latency.

Router, sub-question decomposition, or agent: how do you choose?

Use the least autonomy that answers the question. One right source → router. Independent parts across sources → decomposition. Dependent steps, or answers that must be checked before they're given → an agent with a step cap and citation rules. In production, a cheap router often sends easy questions to plain RAG and wakes the agent only for hard ones.

Why do tool descriptions matter so much, and how do you validate routing?

The selector never sees the documents, only the names and descriptions, so vague or overlapping descriptions send questions to the wrong source. Each description should say what's unique about its source (period, audited or not, rules vs facts). Validate it like a classifier: a labelled set of question → correct tool, re-measured whenever descriptions or documents change, with the selector's choice and reason logged for every query. Back it up with metadata or rules where they are more reliable.

What can't SubQuestionQueryEngine do?

It writes all sub-questions before retrieving anything, so it can't handle dependent multi-hop questions where step 2 needs step 1's answer ("find the largest customer, then that customer's credit rating"). For those, interleave retrieval and reasoning: an agent, or methods like self-ask and IRCoT. It also adds about one LLM call per sub-question plus the plan and the final combine.

How do you stop an agentic RAG loop from running forever or making things up?

A hard step cap (max_iterations) with a defined behaviour at the cap; a system prompt that requires a citation (document and period) for every figure; an explicit fail-safe ("insufficient evidence", never an estimate); a token or cost budget; and trajectory logging so every tool call can be reviewed. A faithfulness check on the final answer adds a second line of defence.

Dense vs sparse retrieval: why use both in finance?

Dense (embedding) search matches meaning but is weak on exact tokens such as tickers, bond names, section numbers and specific figures. Sparse BM25 matches exact words and rewards rare ones, but misses synonyms ("acid-test" vs "quick ratio"). Finance text is full of both identifiers and paraphrase, so hybrid search improves recall. BM25 is also cheap: no API, just word statistics.

Explain reciprocal rank fusion. Why ranks and not scores?

Each chunk gets Σ 1/(k + rank) over the lists it appears in, with rank starting at 0 and k = 60 by convention. Scores from different retrievers aren't comparable (cosine ≈ 0–1, BM25 unbounded), so adding them lets one retriever dominate. Using ranks is scale-free, and with k = 60 neighbouring ranks are worth almost the same, so a chunk found by both retrievers (≈0.033) beats one that tops a single list (≈0.017).

Bi-encoder, cross-encoder, LLM reranker: what's the difference?

A bi-encoder embeds the query and chunk separately and compares vectors: very fast, used for first-stage retrieval. A cross-encoder reads query and chunk together and outputs one score: more accurate, fast enough to rerank tens of chunks locally. An LLM reranker such as LLMRerank ranks a batch of chunks in one prompt (listwise, 1–10 scores): most flexible, but one LLM call per batch. Typical stack: hybrid retrieval for ~20–50 candidates, then a reranker down to 3–5.

Explain the RAG triad and how you'd use it to debug.

Context relevancy (question ↔ context) judges the retriever. Faithfulness (context ↔ answer) judges whether the generator stuck to the evidence. Answer relevancy (question ↔ answer) judges whether the question was actually answered. Low context relevancy → fix retrieval (routing, hybrid, chunking, reranking). Good context but low faithfulness → the generator is hallucinating (prompt, citations, model). Faithful but low answer relevancy → it answered a different question (query understanding, decomposition).

Faithfulness is 0.9. Is that good enough for a compliance answer?

No. It means roughly one claim in ten has no support in the retrieved evidence, and you don't know which. For compliance and client-facing finance, require every figure to be supported (1.0, or a per-claim check) and block or escalate otherwise. Derived numbers should be computed by a tool so the calculation is on record. And remember the judge itself is a model: pin its version and calibrate it against human grades.

Two documents give different numbers for the same metric. What should the system do?

Never pick one silently. Apply a written source hierarchy (e.g. the audited 10-K controls, quarterly figures are monitored for deterioration), report both values with their periods, apply the rule to the controlling figure, flag the change, and escalate if the latest figure breaches a limit. Put the hierarchy in the agent's instructions and in metadata, and keep a regression test where sources disagree.

How would you cut the cost and latency of an agentic RAG system?

Route simple questions to plain RAG; cap agent steps; run sub-questions concurrently; use a cross-encoder instead of an LLM reranker; keep query rewriting off (num_queries=1) unless recall needs it; use metadata filters so searches are smaller; cache embeddings and frequent answers; and use a smaller model for selection and reranking, keeping the strongest model for the final synthesis.


Wrap-up

What to remember

TopicBig ideaWhere you saw it in code
Naive RAG limitsFixed top-k can't tell sources apart, can't split questions, never checksas_query_engine(similarity_top_k=3)
RoutingOne index per source; descriptions are the routing signalQueryEngineTool, RouterQueryEngine, selector_result
DecompositionSplit into independent sub-questions, answer each, combineSubQuestionQueryEngine, LLMQuestionGenerator
Self-correcting agentSearch, check, search again; cite everything; cap the stepsFunctionAgent, max_iterations, ToolCallResult
Hybrid + rerankRecall with dense + BM25 fused by RRF; precision with a rerankerQueryFusionRetriever, BM25Retriever, LLMRerank, rrf()
EvaluationThe triad points at the broken part: retriever, generator or questionFaithfulnessEvaluator and the two relevancy evaluators
  1. Naive RAG is a fixed pipeline; it fails on wrong sources, multi-part questions, missing evidence and non-text work. Raising k isn't a fix.
  2. Use the least autonomy that works: router → decomposition → agent. Each step up costs more calls and is harder to test.
  3. Descriptions are the router's only signal. Write them to say what's unique, and measure routing accuracy.
  4. An agent is only as safe as its rules: citations with periods, a step cap, a fail-safe "insufficient evidence", and a logged trajectory.
  5. Hybrid search finds more; reranking keeps the best. Fuse ranks, not scores (RRF, k = 60).
  6. Measure with the triad, and in finance require every claim to be supported.
  7. Retrieval quality and reasoning loops are complementary: build the agent on top of good retrieval.

QuizCheck yourself


Appendix

Complete code for the lab

Everything you need is on this page, nothing to download. Create the folders below, then create each file with exactly the name shown and paste the content in. The three documents are part of the lab: the code reads them from the data folder.

section10_agentic_rag/ ├── .env # ANTHROPIC_API_KEY=... OPENAI_API_KEY=... ├── agentic_rag_lab.py ├── rrf_by_hand.py # free: no key, no libraries └── data/ ├── acme_10k_excerpt.md ├── acme_earnings_call_q3.md └── firm_risk_policy.md
Terminal · set up once (Python 3.10+)
python -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install llama-index-core llama-index-llms-anthropic llama-index-embeddings-openai \
            llama-index-retrievers-bm25 python-dotenv
python rrf_by_hand.py            # free warm-up
python agentic_rag_lab.py        # needs both keys in .env
📄 agentic_rag_lab.py section10_agentic_rag/agentic_rag_lab.py

The full lab: eight steps and the side-by-side comparison. Needs ANTHROPIC_API_KEY and OPENAI_API_KEY.

section10_agentic_rag/agentic_rag_lab.py
"""
Section 10 lab — Agentic RAG on a compliance question (LlamaIndex + Claude)
==========================================================================
The question every step tries to answer:

    "Does Acme's Q3 quick ratio satisfy the firm's risk policy?"

To answer it you need TWO facts from TWO different documents:
    • Acme's Q3 quick ratio            → the Q3 earnings-call transcript (1.18)
    • the bank's minimum quick ratio   → the internal risk policy        (1.00)

We answer the same question eight ways and compare:

    naive      one blended index, top-3 chunks, no thinking          (the baseline)
    router     an LLM picks ONE document to search                   (routing)
    subq       an LLM splits the question into per-document parts    (decomposition)
    agent      an agent searches, checks, and searches again         (self-correction)
    hybrid     meaning search + keyword search, fused with RRF       (better recall)
    rerank     fetch 6 chunks, an LLM keeps the best 2               (better precision)
    hybrid_rerank   both together                                    (production default)
    evaluate   grade an answer: faithfulness / relevancy triad       (measurement)

How to run
----------
1. pip install llama-index-core llama-index-llms-anthropic llama-index-embeddings-openai \
               llama-index-retrievers-bm25 python-dotenv
2. Create a .env file next to this script:
       ANTHROPIC_API_KEY=sk-ant-...
       OPENAI_API_KEY=sk-...            (only used for embeddings — fractions of a cent)
3. python agentic_rag_lab.py               # every step, then a side-by-side table
   python agentic_rag_lab.py agent         # just one step (naive, router, subq, agent,
                                           #   hybrid, rerank, hybrid_rerank, evaluate)

The three documents live in ./data and are synthetic. Roughly 40 Claude calls in total.
Learning only — not investment advice.
"""

from __future__ import annotations

import asyncio
import sys
from pathlib import Path

from dotenv import load_dotenv
from llama_index.core import Settings, SimpleDirectoryReader, VectorStoreIndex

load_dotenv()

DATA_DIR = Path(__file__).parent / "data"
SOURCES = {                                  # short key  → file in ./data
    "ten_k": "acme_10k_excerpt.md",
    "earnings_call": "acme_earnings_call_q3.md",
    "risk_policy": "firm_risk_policy.md",
}
COMPARISON_QUESTION = "Does Acme's Q3 quick ratio satisfy the firm's risk policy?"

LLM_MODEL = "claude-sonnet-5-5"              # the reasoning + answer-writing model
EMBED_MODEL = "text-embedding-3-small"       # turns text into vectors for search


def configure_models() -> None:
    """Set the global models once; every index, engine and agent below reuses them."""
    from llama_index.embeddings.openai import OpenAIEmbedding
    from llama_index.llms.anthropic import Anthropic

    Settings.llm = Anthropic(model=LLM_MODEL, max_tokens=2048)
    Settings.embed_model = OpenAIEmbedding(model=EMBED_MODEL)


# Small chunks (≈150 tokens) so each document becomes several pieces. With one
# giant chunk per file, "top-3" would simply fetch the whole corpus and hide the
# problems naive RAG has on real, long filings.
Settings.chunk_size = 150
Settings.chunk_overlap = 20

COMPARISON: dict[str, str] = {}              # step name → answer to COMPARISON_QUESTION


def _source_of(node) -> str:
    return node.metadata.get("source", "(sub-answer)")   # sub-question answers have no file


def show(title: str, question: str, answer, nodes=None) -> None:
    """Print a question, the answer, and WHICH chunks the answer was built from."""
    nodes = nodes if nodes is not None else getattr(answer, "source_nodes", []) or []
    print(f"\n{'=' * 78}\n{title}\nQ: {question}\n{'-' * 78}")
    print(f"A: {str(answer).strip()}")
    print(f"\n  evidence used ({len(nodes)} chunks):")
    for n in nodes:
        score = f"{n.score:.3f}" if n.score is not None else "  -  "
        snippet = " ".join(n.node.get_content().split())[:70]
        print(f"   [{score}] {_source_of(n):<26} {snippet}…")

def _load(files: list[str]):
    """Read files from ./data and tag every document with its file name as 'source'."""
    return SimpleDirectoryReader(
        input_files=[DATA_DIR / f for f in files],
        file_metadata=lambda path: {"source": Path(path).name},
    ).load_data()


def load_indices() -> dict[str, VectorStoreIndex]:
    """One SEPARATE vector index per document — this is what makes routing possible."""
    return {key: VectorStoreIndex.from_documents(_load([fname]))
            for key, fname in SOURCES.items()}


def load_combined_index() -> VectorStoreIndex:
    """ONE index with all three documents blended together (the naive set-up)."""
    return VectorStoreIndex.from_documents(_load(list(SOURCES.values())))

def step_naive(combined: VectorStoreIndex) -> None:
    engine = combined.as_query_engine(similarity_top_k=3)     # fetch 3 chunks, then answer

    simple = "What was Acme's full-year 2024 total revenue?"  # one fact, one document
    show("NAIVE RAG — single fact", simple, engine.query(simple))

    answer = engine.query(COMPARISON_QUESTION)                # two facts, two documents
    show("NAIVE RAG — cross-document question", COMPARISON_QUESTION, answer)
    COMPARISON["naive"] = str(answer)

from llama_index.core.tools import QueryEngineTool


def build_query_engine_tools(indices: dict[str, VectorStoreIndex]) -> list[QueryEngineTool]:
    """Wrap each document index as a TOOL with a name and a plain-English description.

    The LLM never sees the documents when it chooses — it only reads these
    descriptions. Vague or overlapping descriptions = wrong source picked.
    """
    return [
        QueryEngineTool.from_defaults(
            query_engine=indices["ten_k"].as_query_engine(similarity_top_k=3),
            name="annual_report_10k",
            description=(
                "Acme Robotics' audited FY2024 annual report (Form 10-K). Full-year "
                "revenue, margins, EPS, year-end balance sheet, year-end current and "
                "quick ratios, credit-facility covenants and risk factors."),
        ),
        QueryEngineTool.from_defaults(
            query_engine=indices["earnings_call"].as_query_engine(similarity_top_k=3),
            name="q3_earnings_call",
            description=(
                "Acme Robotics' Q3 FY2025 earnings-call transcript (October 2025). "
                "Most recent quarterly figures: Q3 revenue, Q3 quick and current "
                "ratios, inventory build, raised guidance, analyst Q&A."),
        ),
        QueryEngineTool.from_defaults(
            query_engine=indices["risk_policy"].as_query_engine(similarity_top_k=3),
            name="firm_risk_policy",
            description=(
                "Future with Shivank Bank's internal liquidity and counterparty risk "
                "policy. The REQUIRED thresholds for a new long position: minimum "
                "quick ratio, current-ratio bands, max net debt/EBITDA, which source "
                "is controlling, concentration limits."),
        ),
    ]

from llama_index.core.query_engine import RouterQueryEngine
from llama_index.core.selectors import LLMSingleSelector


def step_router(indices: dict[str, VectorStoreIndex]) -> None:
    router = RouterQueryEngine(
        selector=LLMSingleSelector.from_defaults(),            # LLM picks exactly ONE tool
        query_engine_tools=build_query_engine_tools(indices),
    )
    tool_names = [t.metadata.name for t in build_query_engine_tools(indices)]

    for q in ["What is the firm's minimum required quick ratio for a new long position?",
              "What was Acme's Q3 quick ratio?",
              "What credit-facility covenants does Acme disclose in its 10-K?",
              COMPARISON_QUESTION]:
        answer = router.query(q)
        pick = answer.metadata["selector_result"].selections[0]   # the routing decision
        show(f"ROUTER → picked '{tool_names[pick.index]}'  (why: {pick.reason[:60]}…)",
             q, answer)
    COMPARISON["router"] = str(answer)                     # answer to the last question

from llama_index.core.query_engine import SubQuestionQueryEngine
from llama_index.core.question_gen import LLMQuestionGenerator


def step_subquestion(indices: dict[str, VectorStoreIndex]) -> None:
    engine = SubQuestionQueryEngine.from_defaults(
        query_engine_tools=build_query_engine_tools(indices),
        # Pass the generator explicitly; the default one is OpenAI-specific.
        question_gen=LLMQuestionGenerator.from_defaults(),
        verbose=True,                       # prints each generated sub-question + tool
    )
    spanning = ("How did Acme's quick ratio change from year-end 2024 to Q3, and does "
                "the Q3 level breach the firm's risk policy?")
    show("SUB-QUESTIONS — trend + policy", spanning, engine.query(spanning))

    answer = engine.query(COMPARISON_QUESTION)
    show("SUB-QUESTIONS — comparison question", COMPARISON_QUESTION, answer)
    COMPARISON["subq"] = str(answer)

from llama_index.core.agent.workflow import FunctionAgent, ToolCallResult

AGENT_SYSTEM_PROMPT = (
    "You are a buy-side compliance analyst. Answer using ONLY the document tools "
    "provided. First work out what evidence the question needs: a compliance check "
    "usually needs BOTH the issuer's figure from its filings AND the matching "
    "threshold from the firm's risk policy. Before concluding, check that you have "
    "every piece; if one tool call did not give you everything, call another tool. "
    "If a required figure cannot be found, say so explicitly instead of estimating. "
    "Cite the source document and reporting period for every figure you use."
)
MAX_AGENT_STEPS = 8          # guardrail: never loop forever, however confused the model is


def run_agent_sync(agent: FunctionAgent, task: str):
    """Run the agent; also record its tool calls (the 'trajectory') and evidence chunks."""
    trajectory: list[str] = []
    evidence: list = []

    async def _run():
        handler = agent.run(task, max_iterations=MAX_AGENT_STEPS,
                            early_stopping_method="generate")
        async for event in handler.stream_events():          # watch it work, live
            if isinstance(event, ToolCallResult):
                trajectory.append(f"{event.tool_name}({event.tool_kwargs.get('input', '')!r})")
                raw = getattr(event.tool_output, "raw_output", None)   # the tool's Response
                evidence.extend(getattr(raw, "source_nodes", None) or [])
        return await handler

    response = asyncio.run(_run())
    return response, trajectory, evidence


def step_agent(indices: dict[str, VectorStoreIndex]) -> None:
    agent = FunctionAgent(
        tools=build_query_engine_tools(indices),
        llm=Settings.llm,
        system_prompt=AGENT_SYSTEM_PROMPT,
    )
    task = ("Can we open a new long position in Acme Robotics under the firm's liquidity "
            "policy? Check the quick-ratio rule against Acme's most recent disclosed "
            "quick ratio.")
    for q, keep in ((task, False), (COMPARISON_QUESTION, True)):
        response, trajectory, evidence = run_agent_sync(agent, q)
        print("\n  agent tool calls, in order:")
        for i, call in enumerate(trajectory, 1):
            print(f"   {i}. {call}")
        show("SELF-CORRECTING AGENT", q, response, evidence)
        if keep:
            COMPARISON["agent"] = str(response)

from llama_index.core.query_engine import RetrieverQueryEngine
from llama_index.core.retrievers import QueryFusionRetriever
from llama_index.retrievers.bm25 import BM25Retriever


def build_hybrid_retriever(combined: VectorStoreIndex) -> QueryFusionRetriever:
    """Meaning search + keyword search over the SAME chunks, merged by rank (RRF)."""
    dense = combined.as_retriever(similarity_top_k=5)                  # by meaning
    sparse = BM25Retriever.from_defaults(docstore=combined.docstore,   # by exact words
                                         similarity_top_k=5)
    return QueryFusionRetriever(
        [dense, sparse],
        similarity_top_k=5,          # keep the best 5 after fusion
        num_queries=1,               # 1 = no LLM rewrites of the question (cheap, repeatable)
        mode="reciprocal_rerank",    # Reciprocal Rank Fusion: score = Σ 1/(60 + rank)
        use_async=False,
    )


def step_hybrid(combined: VectorStoreIndex) -> None:
    engine = RetrieverQueryEngine.from_args(build_hybrid_retriever(combined))
    answer = engine.query(COMPARISON_QUESTION)
    show("HYBRID (dense + BM25, fused)", COMPARISON_QUESTION, answer)
    COMPARISON["hybrid"] = str(answer)

from llama_index.core.postprocessor import LLMRerank


def step_rerank(indices: dict[str, VectorStoreIndex]) -> None:
    engine = indices["ten_k"].as_query_engine(
        similarity_top_k=6,                        # cast a wide net…
        node_postprocessors=[LLMRerank(top_n=2)],  # …then the LLM keeps the best 2
    )
    q = "What was Acme's gross margin in fiscal 2024 and why did it expand?"
    show("RERANK (top-6 → best 2)", q, engine.query(q))

def step_hybrid_rerank(combined: VectorStoreIndex) -> None:
    engine = RetrieverQueryEngine.from_args(
        build_hybrid_retriever(combined),                  # recall: wide, fused pool
        node_postprocessors=[LLMRerank(top_n=3)],          # precision: keep the best 3
    )
    answer = engine.query(COMPARISON_QUESTION)
    show("HYBRID + RERANK", COMPARISON_QUESTION, answer)
    COMPARISON["hybrid_rerank"] = str(answer)

from llama_index.core.evaluation import (
    AnswerRelevancyEvaluator,
    ContextRelevancyEvaluator,
    FaithfulnessEvaluator,
)


def step_evaluate(indices: dict[str, VectorStoreIndex]) -> dict:
    engine = indices["ten_k"].as_query_engine(similarity_top_k=3)
    q = "What was Acme's net income per diluted share in fiscal 2024?"
    response = engine.query(q)
    show("EVALUATE — the answer being graded", q, response)

    # The RAG triad. Each uses the LLM as a judge with a fixed grading prompt.
    faithful = FaithfulnessEvaluator().evaluate_response(response=response)
    answer_rel = AnswerRelevancyEvaluator().evaluate_response(query=q, response=response)
    context_rel = ContextRelevancyEvaluator().evaluate_response(query=q, response=response)

    scores = {
        "faithful": faithful.passing,          # True/False: every claim backed by chunks?
        "answer_relevancy": answer_rel.score,  # 0–1: does the answer address the question?
        "context_relevancy": context_rel.score,  # 0–1: were the fetched chunks on topic?
    }
    print("\n  RAG triad:", scores)
    return scores

STEPS = {
    "naive":         lambda ix, comb: step_naive(comb),
    "router":        lambda ix, comb: step_router(ix),
    "subq":          lambda ix, comb: step_subquestion(ix),
    "agent":         lambda ix, comb: step_agent(ix),
    "hybrid":        lambda ix, comb: step_hybrid(comb),
    "rerank":        lambda ix, comb: step_rerank(ix),
    "hybrid_rerank": lambda ix, comb: step_hybrid_rerank(comb),
    "evaluate":      lambda ix, comb: step_evaluate(ix),
}


def main(selected: list[str]) -> None:
    indices, combined = load_indices(), load_combined_index()   # embeds the corpus once
    for name in selected:
        STEPS[name](indices, combined)

    if len(COMPARISON) > 1:                                      # the side-by-side view
        print(f"\n{'#' * 78}\nSAME QUESTION, EVERY PATTERN: {COMPARISON_QUESTION}\n{'#' * 78}")
        for name, answer in COMPARISON.items():
            print(f"\n[{name}]\n  " + " ".join(answer.split())[:400])


if __name__ == "__main__":
    wanted = sys.argv[1:] or list(STEPS)
    unknown = [w for w in wanted if w not in STEPS]
    if unknown:
        sys.exit(f"Unknown step(s) {unknown}. Choose from: {', '.join(STEPS)}")
    configure_models()
    main(wanted)
📄 rrf_by_hand.py section10_agentic_rag/rrf_by_hand.py

Free: BM25 and reciprocal rank fusion from scratch, standard library only.

section10_agentic_rag/rrf_by_hand.py
"""
Section 10 — BM25 and Reciprocal Rank Fusion from scratch (no API key, no libraries)
===================================================================================
Hybrid search = two ranked lists (meaning search + keyword search) merged into one.
This script builds the keyword side (BM25) and the merge (RRF) by hand, so you can
see every number. It runs instantly and costs nothing.

How to run
----------
    python rrf_by_hand.py

It reads the three documents in ./data, splits them into paragraphs, ranks them with
BM25 for the compliance question, fuses that list with a dense (meaning) ranking, and
shows why we fuse RANKS instead of adding raw SCORES.
"""

import math
import re
from pathlib import Path

DATA_DIR = Path(__file__).parent / "data"


def tokenize(text: str) -> list[str]:
    """Lower-case words and numbers: 'Quick ratio was 1.18.' → ['quick','ratio','was','1.18']"""
    return re.findall(r"[a-z0-9]+(?:\.[0-9]+)?", text.lower())


def bm25_scores(query: str, docs: list[str], k1: float = 1.5, b: float = 0.75) -> list[float]:
    """Score every doc for the query with BM25.

    For each query word:
        idf  = how RARE the word is across all docs   (rare words matter more)
        tf   = how often it appears in THIS doc       (more is better, but saturates)
        norm = penalty for long docs                  (long docs aren't better by default)
    score = Σ idf × tf×(k1+1) / (tf + k1×norm)
    """
    tokenized = [tokenize(d) for d in docs]
    n_docs = len(docs)
    avg_len = sum(len(t) for t in tokenized) / n_docs
    scores = []
    for words in tokenized:
        score = 0.0
        for term in set(tokenize(query)):
            n_with_term = sum(1 for t in tokenized if term in t)
            if n_with_term == 0:
                continue
            idf = math.log(1 + (n_docs - n_with_term + 0.5) / (n_with_term + 0.5))
            tf = words.count(term)
            norm = 1 - b + b * len(words) / avg_len           # = 1 for an average-length doc
            score += idf * tf * (k1 + 1) / (tf + k1 * norm)
        scores.append(score)
    return scores

def rank_ids(scores: list[float]) -> list[int]:
    """Doc ids ordered best → worst (only docs with a positive score)."""
    return [i for i in sorted(range(len(scores)), key=lambda i: -scores[i]) if scores[i] > 0]


def rrf(ranked_lists: list[list[int]], k: int = 60) -> dict[int, float]:
    """Reciprocal Rank Fusion. Each list gives a doc 1/(k + rank), rank starting at 0.

    Raw scores are ignored completely — only POSITIONS count. So a BM25 score of 9.7
    and a cosine of 0.41 can be merged fairly. Appearing in BOTH lists beats topping one.
    """
    fused: dict[int, float] = {}
    for ranking in ranked_lists:
        for rank, doc_id in enumerate(ranking):
            fused[doc_id] = fused.get(doc_id, 0.0) + 1.0 / (k + rank)
    return dict(sorted(fused.items(), key=lambda kv: -kv[1]))

def load_paragraphs() -> list[tuple[str, str]]:
    """(file name, paragraph) for every non-heading paragraph in ./data."""
    out = []
    for path in sorted(DATA_DIR.glob("*.md")):
        for para in path.read_text(encoding="utf-8").split("\n\n"):
            if para.strip() and not para.startswith("#"):
                out.append((path.name, " ".join(para.split())))
    return out


def find(paras, needle: str) -> int:
    return next(i for i, (_, p) in enumerate(paras) if needle in p)


if __name__ == "__main__":
    paras = load_paragraphs()
    texts = [p for _, p in paras]
    question = "Does Acme's Q3 quick ratio satisfy the firm's risk policy?"

    # 1) Keyword side: BM25 over every paragraph
    bm25 = bm25_scores(question, texts)
    bm25_rank = rank_ids(bm25)[:5]

    # 2) Meaning side: in the full lab this list comes from the vector index.
    #    Here we write down a typical dense ranking so the script needs no API key:
    #    embeddings match MEANING, so the paragraph about "liquidity" and "inventory
    #    build" ranks high even though it never says "risk policy".
    dense_rank = [find(paras, "quick ratio at quarter-end"),
                  find(paras, "2.1 Quick ratio"),
                  find(paras, "Should investors worry about liquidity"),
                  find(paras, "2.4 Source of figures"),
                  find(paras, "Excluding inventories")]

    print(f"Question: {question}\n")
    print("BM25 top 5 (keyword match):")
    for r, i in enumerate(bm25_rank):
        print(f"  rank {r}  score {bm25[i]:5.2f}  {paras[i][0]:<26} {texts[i][:55]}…")
    print("\nDense top 5 (meaning match):")
    for r, i in enumerate(dense_rank):
        print(f"  rank {r}               {paras[i][0]:<26} {texts[i][:55]}…")

    # 3) Fuse by rank
    fused = rrf([dense_rank, bm25_rank])
    print("\nRRF fused (k=60):  score = Σ 1/(60 + rank)")
    for i, s in list(fused.items())[:5]:
        where = [name for name, lst in (("dense", dense_rank), ("bm25", bm25_rank)) if i in lst]
        ranks = ", ".join(f"{n}#{(dense_rank if n == 'dense' else bm25_rank).index(i)}" for n in where)
        print(f"  {s:.4f}  [{ranks:<16}] {paras[i][0]:<26} {texts[i][:45]}…")

    # 4) Why not just add the raw scores?
    top_bm25 = bm25[bm25_rank[0]]
    print(f"\nWhy fuse ranks, not scores: a top BM25 score here is {top_bm25:.2f}, while a top")
    print("cosine similarity is usually 0.3–0.8. Adding them lets BM25 drown out meaning search.")
    print(f"1/60 = {1/60:.4f} (1st place in one list)   1/61 + 1/62 = {1/61 + 1/62:.4f} (2nd + 3rd in two lists)")
📄 data/acme_10k_excerpt.md section10_agentic_rag/data/acme_10k_excerpt.md

Fictional annual report excerpt (FY2024).

section10_agentic_rag/data/acme_10k_excerpt.md
# Acme Robotics, Inc. — Form 10-K (excerpt), fiscal year ended December 31, 2024

## Item 7. Management's discussion — results of operations

Total revenue for fiscal 2024 was $612.4 million, up 14% from $537.2 million in fiscal 2023. Software and services revenue grew 31% to $198.6 million and now represents 32% of total revenue.

Gross margin was 43.1% in fiscal 2024, up from 40.2% in fiscal 2023. The expansion was driven mainly by the shift in revenue mix toward higher-margin software subscriptions, partly offset by higher component costs for the warehouse-robot line.

Net income was $96.3 million. Diluted earnings per share were $1.92, compared with $1.51 in fiscal 2023. EBITDA was $131.0 million.

## Liquidity and capital resources

At December 31, 2024, current assets were $498.0 million and current liabilities were $307.4 million, giving a current ratio of 1.62. Excluding inventories of $119.8 million, the quick ratio was 1.23.

Cash and cash equivalents were $142.5 million. Total long-term debt was $180.0 million, all of it the term loan under our credit facility. Net debt to EBITDA was 0.29x.

## Credit facility covenants

Our $250 million revolving credit and term loan facility requires us to maintain (i) a minimum current ratio of 1.25 and (ii) a maximum net leverage ratio (net debt to EBITDA) of 3.0x, both tested quarterly. We were in compliance with all covenants at December 31, 2024.

## Item 1A. Risk factors (selected)

Customer concentration: our largest customer, a global e-commerce retailer, accounted for 41% of fiscal 2024 revenue. The loss of this customer would materially reduce our revenue and profitability.

Supply chain: we depend on a single supplier for the actuators used in our humanoid robot line.
📄 data/acme_earnings_call_q3.md section10_agentic_rag/data/acme_earnings_call_q3.md

Fictional Q3 FY2025 earnings-call excerpt.

section10_agentic_rag/data/acme_earnings_call_q3.md
# Acme Robotics — Q3 fiscal 2025 earnings call (transcript excerpt), October 28, 2025

**Operator:** Welcome to Acme Robotics' third-quarter fiscal 2025 earnings call.

**Maria Lopez, Chief Financial Officer:** Thank you. Q3 revenue was $171.8 million, up 16% year over year, with software subscriptions again the fastest-growing line. Gross margin for the quarter was 43.8%.

On the balance sheet: our quick ratio at quarter-end, September 30, 2025, was 1.18, down from 1.23 at year-end. The decline is deliberate — we built inventory ahead of the humanoid launch. The current ratio was 1.58.

**David Kim, Chief Executive Officer:** Demand is strong. We are raising full-year fiscal 2025 revenue guidance to between $690 million and $705 million.

**Sam Ortiz, sell-side analyst:** Should investors worry about liquidity with inventory this high?

**Maria Lopez:** No. We remain well above the covenant minimum current ratio of 1.25 in our credit facility, and we expect the quick ratio to recover in Q1 as the inventory converts to sales.

**Priya Nair, buy-side analyst:** Is customer concentration changing?

**David Kim:** Our largest customer is still a little above 40% of revenue, but the new humanoid contracts should dilute that over the next year.
📄 data/firm_risk_policy.md section10_agentic_rag/data/firm_risk_policy.md

The bank's (fictional) liquidity and counterparty risk policy.

section10_agentic_rag/data/firm_risk_policy.md
# Future with Shivank Bank — Investment Liquidity and Counterparty Risk Policy (v3.2, effective January 1, 2025)

## 1. Scope

This policy applies to every new long equity position opened by the bank's managed funds.

## 2. Issuer liquidity requirements for a new long position

2.1 Quick ratio: the issuer's quick ratio must be at least 1.00.

2.2 Current ratio: a current ratio of at least 1.50 is standard. Between 1.25 and 1.50, a Risk Committee exception is required. Below 1.25, new positions are prohibited.

2.3 Leverage: the issuer's net debt to EBITDA must not exceed 3.0x.

2.4 Source of figures: the issuer's most recent audited annual report (Form 10-K) is the controlling source. More recent quarterly figures (10-Q, earnings calls) must be reviewed for deterioration and noted in the investment memo. If a quarterly figure breaches a limit in this section, escalate to the Risk Committee before trading.

## 3. Concentration

3.1 Exposure to a single issuer must not exceed 5% of the fund's net asset value.

3.2 Issuers whose largest customer exceeds 40% of revenue require enhanced due diligence before purchase.

## 4. Covenant awareness

Analysts must record the issuer's financial covenants and the current headroom against each one in the investment memo.