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.
What RAG is (chunk → embed → store → retrieve → generate), vector databases, and the idea that an agent can call RAG as one of its tools (AWS module) · LLM-as-a-judge and faithfulness/relevance scoring in AgentCore Evaluations (AWS module) · ReAct-style think-act-observe loops (Section 6). Here we focus on what's new: where one-shot retrieval breaks on finance documents, the three agentic patterns in code, hybrid search with reciprocal rank fusion, reranking, and how to diagnose a RAG system with the evaluation triad.
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 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?
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.
| Document | What kind of truth | Key facts for our question |
|---|---|---|
| 10-K (annual report, FY2024) | Audited, but up to a year old | Quick 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 words | Quick 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
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.
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.
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.
1 extra LLM call. For single-source questions over many documents.
A plan + one call per part. For questions with independent parts.
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.
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.
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):
| Selector | How it answers | Use when |
|---|---|---|
LLMSingleSelector | The LLM writes JSON as text; LlamaIndex parses it | Any LLM; our lab uses this |
PydanticSingleSelector | Uses the model's function calling to return a typed object | The model supports tool calling; fewer parse errors |
LLMMultiSelector / PydanticMultiSelector | Can pick several tools and merge their answers | Questions that touch 2–3 sources but don't need a full plan |
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.
SubQuestionQueryEngine with an LLMQuestionGenerator, using the same tools as the router.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 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.
Watch the agent notice what's missing
The diagram above lights up as you click.
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
max_iterations stops a confused agent from searching forever. On the cap, write the best answer so far and say it's incomplete.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
Pick an approach. Watch the evidence, the cost, and the answer.
| Pattern | Best for | LLM calls on our question | Main weakness |
|---|---|---|---|
| Naive RAG | Single-fact lookups in one document | 1 | Fixed top-k; no source awareness; no check |
| Router | Many documents, each question has one right source | 2 | Only one source per question; depends on descriptions |
| Decomposition | Questions with independent parts across sources | ≈4 (1 plan + 1 per part + 1 combine) | No dependent multi-hop; plan can't adapt |
| Self-correcting agent | Open questions, dependent steps, compliance checks | ≈5–7 (each tool call has its own LLM call inside) | Cost and latency vary; harder to test |
"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).
Of the chunks that matter, how many made it into the results.
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) | |
|---|---|---|
| Matches | Meaning: "liquidity cushion" finds a chunk about the quick ratio | Exact words, giving extra weight to rare ones |
| Misses | Exact tokens: tickers, bond names ("4.25% notes due 2031"), section numbers ("§2.1"), specific figures | Synonyms and paraphrases: "acid-test ratio" won't match "quick ratio" |
| Needs | An 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" |
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:
k1 (≈1.2–2.0) sets how fast the bonus flattens out.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).
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 scorestokenizeturns"Quick ratio was 1.18."into['quick', 'ratio', 'was', '1.18']. The regex keeps decimal numbers whole, so1.18is one "word". That matters in finance.avg_lenis the average chunk length in words; it's the yardstick for the length dial.- For each chunk, for each distinct query word:
n_with_termcounts the chunks that contain the word, andidfis large when that count is small (a rare word). tfis how often the word appears in this chunk. The fractiontf × (k1+1) / (tf + k1 × norm)grows withtfbut 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.normis 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:
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.
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]))rank_idssorts chunk ids by score, best first, and drops zero scores (chunks that share no words with the query).rrfwalks each ranked list.enumerategives the position (0, 1, 2…) and the chunk id; the chunk's running total grows by1 / (k + rank). A chunk in both lists collects two contributions.- The last line sorts the totals, highest first: that's the fused ranking.
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:
- 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).
- Dense alone puts the Q3 figure first but includes the analyst's liquidity question, which has no number in it.
- 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.
Fuse the two lists yourself
★ = the two facts the answer needs. The top 3 fused chunks go to the LLM.
In LlamaIndex the whole hybrid set-up is one object, QueryFusionRetriever (lab step 9). Two of its settings are easy to mix up:
| Setting | What it controls | Our choice |
|---|---|---|
num_queries | How 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 |
mode | How the ranked lists are merged. Needed even with one query, because dense + sparse already gives two lists. | "reciprocal_rerank" = RRF |
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
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.
| Scorer | How it reads | Speed / cost | In LlamaIndex |
|---|---|---|---|
| Bi-encoder (the embedding search itself) | Question and chunk turned into vectors separately, then compared | Fastest; chunk vectors are pre-computed | as_retriever() |
| Cross-encoder | A small model reads question + chunk together and outputs one relevance score | Fast, runs locally, no API | SentenceTransformerRerank |
| LLM reranker | The LLM sees a numbered list of chunks and ranks them as a group ("listwise") | Slowest; one LLM call per batch | LLMRerank |
LLMRerank works in four moves:
choice_batch_size (10 by default) so each prompt fits.Doc: 2, Relevance: 8 (1–10), leaving out chunks it thinks are irrelevant.top_n, discard the rest."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.
"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.
"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.
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.
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
| Metric | How it's computed | Low score means |
|---|---|---|
| Answer relevancy | A 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 relevancy | A judge checks how much of the retrieved context is relevant to the question | The retriever fetched noise: fix chunking, routing, hybrid search or reranking |
Three scores came back. What do you fix first?
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:
| Evaluator | Judge prompt asks for | What you read |
|---|---|---|
FaithfulnessEvaluator | YES / NO: is the answer supported by the context? | result.passing (True / False) |
AnswerRelevancyEvaluator | Feedback, then [RESULT] and an integer out of 2 | result.score, normalised to 0–1 |
ContextRelevancyEvaluator | Feedback, then [RESULT] and a number out of 4 | result.score, normalised to 0–1 |
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
What you're building
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 stepAll 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.
main(); every step reuses the same indexes.Step 1: setup and the one global switchboard
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 = 20DATA_DIRis "thedatafolder next to this script", so the script works from any terminal location.Path(__file__).parentis the script's own folder.SOURCESmaps 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.configure_models()sets LlamaIndex's globalSettings: 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.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 = 20repeats a little text between neighbouring chunks so a sentence cut in half still appears whole somewhere.
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
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}…")- Every LlamaIndex query returns a
Response.str(response)is the answer text;response.source_nodesis the list of chunks it was built from. - Each item is a
NodeWithScore:.scoreis 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. - The agent doesn't return
source_nodesitself (its evidence comes from tool calls), soshow()also accepts anodeslist we collect separately in step 8.
Step 3: separate indexes and one blended index
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())))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.load_indices()follows the variable flow:("ten_k", "acme_10k_excerpt.md")→_load([...])→ oneDocument→VectorStoreIndex.from_documentssplits 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.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
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
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."),
),
]QueryEngineTool.from_defaultswraps a whole RAG pipeline (one document's query engine) as a tool with anameand adescription. Router, sub-question engine and agent all consume the same list.- 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.
- Each tool searches with
similarity_top_k=3inside its own document, so it can't be crowded out by the other two.
Step 6: the 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 questionRouterQueryEngine= selector + tools. For each question: 1 LLM call to choose a tool, then that tool's own RAG query (1 more LLM call).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.- 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.
- After the loop,
answerstill holds the last answer, the comparison question's, which goes intoCOMPARISON.
Step 7: sub-question decomposition
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)- 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. - We pass
question_genexplicitly 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. verbose=Trueprints each sub-question, its tool, and its answer in colour as it runs: the easiest way to see the plan.- 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
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)AGENT_SYSTEM_PROMPTis 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.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.async for event in handler.stream_events()lets us watch it work. EachToolCallResultevent carriestool_name(which document),tool_kwargs["input"](the search the agent wrote, e.g."Acme Q3 quick ratio"), andtool_output.raw_output, the tool's fullResponse, whosesource_nodesare the chunks. We append those totrajectoryandevidence.await handlerwaits for the final answer.asyncio.run(_run())runs the async code from ordinary synchronous Python.- The printed trajectory is the proof of self-correction: typically
firm_risk_policy(...)first, thenq3_earnings_call(...)once the agent notices it has the rule but not the figure.
Step 9: hybrid retrieval
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)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.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.QueryFusionRetrieverruns both, fuses with RRF (mode="reciprocal_rerank", k = 60), and keeps the top 5.num_queries=1means no LLM-written paraphrases.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
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
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
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- Each evaluator reads
response.source_nodesas the context automatically, so you only pass the response (and the question, for the two relevancy metrics). - Each
evaluate_responseis one or more judge calls toSettings.llm. In production you'd often use a different model as the judge, to avoid a model grading its own homework. - For this simple question expect
faithful=Trueand 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
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)STEPSmaps a name to a small function. Every function takes(indices, combined)and uses what it needs, somaincan call any of them the same way.mainbuilds the indexes once, runs the chosen steps, then prints every pattern's answer to the comparison question, side by side.- 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.
From lab to production: what changes in a real bank
| Concern | What to do |
|---|---|
| Fresh documents | New 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 filters | Filter by ticker, period and document type before similarity search. That alone stops a 2023 figure leaking into a 2025 answer. |
| Entitlements and information barriers | Deal 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 sources | Write 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 click | Return chunk ids, document, page and period with every answer, so a human can verify in seconds. |
| Cost and latency | Route 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 change | A fixed labelled set: routing accuracy, triad scores, and "must refuse" cases where the evidence doesn't exist. Section 11 builds this out. |
"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
| Topic | Big idea | Where you saw it in code |
|---|---|---|
| Naive RAG limits | Fixed top-k can't tell sources apart, can't split questions, never checks | as_query_engine(similarity_top_k=3) |
| Routing | One index per source; descriptions are the routing signal | QueryEngineTool, RouterQueryEngine, selector_result |
| Decomposition | Split into independent sub-questions, answer each, combine | SubQuestionQueryEngine, LLMQuestionGenerator |
| Self-correcting agent | Search, check, search again; cite everything; cap the steps | FunctionAgent, max_iterations, ToolCallResult |
| Hybrid + rerank | Recall with dense + BM25 fused by RRF; precision with a reranker | QueryFusionRetriever, BM25Retriever, LLMRerank, rrf() |
| Evaluation | The triad points at the broken part: retriever, generator or question | FaithfulnessEvaluator and the two relevancy evaluators |
- 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.
- Use the least autonomy that works: router → decomposition → agent. Each step up costs more calls and is harder to test.
- Descriptions are the router's only signal. Write them to say what's unique, and measure routing accuracy.
- An agent is only as safe as its rules: citations with periods, a step cap, a fail-safe "insufficient evidence", and a logged trajectory.
- Hybrid search finds more; reranking keeps the best. Fuse ranks, not scores (RRF, k = 60).
- Measure with the triad, and in finance require every claim to be supported.
- Retrieval quality and reasoning loops are complementary: build the agent on top of good retrieval.
Everything on this page is for learning. Acme Robotics, its filings and the bank's policy are fictional; sample outputs are illustrative. Nothing here is investment, legal or compliance advice.
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.
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.
"""
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.
"""
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).
# 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.
# 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.
# 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.