Module 5 — RAG, LangChain & AI Agents
Same theory-first structure as Modules 1–4: for every technique below, what it is, why it exists — the specific problem it was invented to solve — what else you could use instead, and a real financial example. Module 4 built an aligned language model with a hard limit: it only knows what was baked into its weights. Module 5 gives it the ability to look things up and take real actions.
Recap — what RR Finance already has
Module 5 is not a fresh start. Here's exactly what it inherits before adding retrieval and agentic tool-use.
A validated tabular baseline and deep-learning fundamentals, including the first inference-time attack (adversarial examples).
Text representations and contextual embeddings — the same similarity math this module's retrieval lessons build directly on.
A real, aligned, instruction-following model built from scratch (SFT → Reward Model → RL/DPO → LoRA), plus real LLM red-teaming.
Why retrieval, why agents
A model that only recalls what it memorised during training will confidently make things up when asked about anything that changed since — the problem this whole module solves in two connected halves.
The core problem
Parametric knowledge is frozen at training time — a policy that changed yesterday isn't in the weights, no matter how large the model is.
The pipeline this module walks
Chunk documents → embed them → retrieve by similarity → augment a prompt with what's retrieved → generalise into a tool-using, multi-step agent.
Why the security lessons follow naturally
A system that trusts retrieved content, and can act on it, is a system whose retrieved content can manipulate its actions — the natural next step after Module 3/4's prompt injection and jailbreaks.
Why RAG: Parametric Knowledge Has a Hard Limit
A frozen model plus a live document store beats retraining every time a policy changes.
Retrieval-Augmented Generation (RAG) keeps a model's weights frozen and instead retrieves relevant real documents at query time, handing them to the model as context — "open-book" answering instead of "closed-book" recall from memorised weights.
✓ Use it when
- Knowledge changes faster than you can retrain (RR Finance's policies, rate sheets)
- Answers must cite specific, current, or private documents a model shouldn't have memorised into its weights
✗ Reach for something else when
- The knowledge is genuinely stable and general (Module 4's fine-tuning is still the right tool for teaching a model a new skill or style, not new facts)
Chunking a Document Corpus
Splitting long documents into retrievable, self-contained pieces.
Whole documents are usually too long to retrieve and hand to a model wholesale. Chunking splits documents into smaller, retrievable pieces — small enough to be precise, large enough to retain context.
✓ Use it when
- Documents are longer than a retrievable unit should be (most real policy documents, manuals, filings)
✗ Watch out for
- Too small a chunk_size fragments a single fact across multiple chunks; too large re-introduces the "too much irrelevant text" problem chunking was meant to solve
RecursiveCharacterTextSplitter tries to split on natural boundaries (paragraph, then sentence, then word) before falling back to a hard character cut, to avoid severing a sentence mid-word wherever possible.Embeddings for Retrieval
Turning a chunk of text into a vector that captures its meaning.
A sentence embedding model maps a whole chunk of text to one dense vector, trained so semantically similar text ends up with similar vectors — a direct evolution of Module 3's Word2Vec (per-word) and contextual embeddings (per-token) to the chunk/document level.
✓ Use it when
- You need to catch paraphrases — a query about "loan limit" should find a chunk saying "maximum amount," with no words in common
✗ Reach for something else when
- Real internet access isn't available — this notebook falls back to Module 3's TF-IDF vectors, which are sparse and keyword-based rather than dense and semantic, and honestly weaker at catching paraphrases
all-MiniLM-L6-v2) is fixed by the chosen model — higher dimensionality can capture more nuance at the cost of more storage and compute per comparison.Vector Search With FAISS
Finding the most similar chunk out of potentially millions, fast.
FAISS (Facebook AI Similarity Search) is a real, widely used library for fast vector similarity search — exact search for smaller corpora, and approximate-but-much-faster indexes for very large ones.
✓ Use it when
- Retrieval needs to stay fast as the document corpus grows well beyond a handful of documents
✗ Trade-off to know
- At real scale (millions of vectors), an approximate index (e.g. HNSW) trades a small amount of accuracy for a large speed gain — the same accuracy/speed pattern as K-Means++ initialisation (Module 1) or PPO's clipping (Module 4)
Lexical Retrieval With BM25, and Hybrid Search
Why exact keyword match still matters alongside semantic search.
BM25 (Best Matching 25) is a classic, still widely used lexical ranking function — an evolution of Module 3's TF-IDF that additionally accounts for document length and saturates term-frequency's contribution.
✓ Use it when
- Exact, rare terms matter — a specific policy code, an exact numeric threshold, a compliance clause number
✗ Reach for something else when
- The query is a paraphrase with no shared vocabulary with the target chunk — that's exactly where dense embeddings (Concept 3) win instead
tf + k1 term flattens that curve.|D|/avgdl length-normalisation term.A Full RAG Pipeline With LangChain
Composing retrieval, prompting, and generation with the industry-standard framework.
LangChain's Runnable interface lets you compose a retriever and an LLM into a single callable pipeline (retriever | prompt | llm) — the same retrieval mechanism as Concept 4, now wrapped in a real, industry-standard orchestration layer instead of hand-wired glue code.
✓ Why the framework matters
- Swap the local template-based responder this notebook uses for Module 4's fine-tuned model, or a hosted LLM API, and the SAME pipeline code works unchanged
✗ What's simplified here, on purpose
- The generation step uses a lightweight local template responder, not a full LLM — clearly marked as the one piece you'd swap for production
PromptTemplate controls exactly how retrieved chunks are formatted into the model's context, and real RAG answer quality is highly sensitive to that template's exact wording.AI Agents: Giving the Model Tools
From reading documents to taking real actions.
An agent is a model that can call functions ("tools") and use their results. RAG lets a model read; tool-use lets it check live data and perform real actions — calculate an EMI, look up a balance, flag a case.
✓ Use it when
- The task needs current, live data (not just retrievable documents) or a real action (a calculation, a lookup, a state change)
✗ Watch out for
- Giving a model access to a dangerous tool (fund transfers) with the same casual trust as a safe one (a calculator) creates exactly the risk Concept 9's poisoning demo exploits
calculate_emi tool and a lookup_policy tool based on the request.LangGraph: Multi-Step, Stateful Agent Workflows
Explicit, inspectable graphs instead of implicit agent loops.
LangGraph models an agent as an explicit state graph: nodes are steps (retrieve, decide, calculate, respond), edges — including conditional ones — define what happens next based on the current state.
AgentExecutor) becomes hard to control and debug once workflows have conditional branches or loops — an explicit graph is easier to reason about, test, and visualise.
✓ Use it when
- The task needs multiple conditional steps in sequence — "check eligibility, and if it passes calculate the EMI, and if not explain why" is a workflow a single tool call can't express
✗ Overkill when
- A single tool call answers the request — Concept 7's simpler router is enough, and adding graph machinery just adds complexity
Cybersecurity: Retrieval Poisoning
When an attacker gets a malicious document into the document store.
A RAG system trusts whatever is in its document store. If an attacker gets a malicious document INTO that store, the retriever will happily surface it as if it were legitimate policy — the retrieval-era evolution of Module 3's prompt injection.
✓ What the notebook demonstrates
- A real, working attack — a crafted document engineered to rank highly against a predictable query, then shown to actually get retrieved ahead of the genuine policy chunk
✗ Real defences
- Access control on who can add documents, provenance/trust scoring per source, and treating retrieved content as untrusted data to verify — never as an implicit instruction
Cybersecurity: Tool-Call Hijacking
When retrieved content manipulates what an agent does, not just what it says.
Concept 9 poisoned what the agent reads. This is the higher-stakes version: a malicious retrieved document that manipulates an agent into calling a tool it shouldn't, or with attacker-chosen arguments — an agent with real tool access that trusts retrieved content the same way it trusts direct user input.
✓ What the notebook demonstrates
- A working hijack — a routine-looking case note with an embedded instruction gets retrieved for an unrelated query, and its text triggers an unintended, fraudulent tool call
✗ The real fix
- A trust boundary: treat retrieved document content as DATA to reason about, never as INSTRUCTIONS to act on — tool-routing decisions should come ONLY from the actual user's request, demonstrated working in the notebook
Module 5 hand-off
The notebook chunks and embeds a real RR Finance policy corpus, builds real FAISS and BM25 indexes, composes a real LangChain RAG pipeline, wires a tool-using agent through a real LangGraph workflow, and produces two working security demonstrations — saved as artifacts and a metrics summary for the next module.