STANFORD-CME295 COURSE GUIDE

AI Agents — Stanford CME295 Lecture 6

A chapter-by-chapter readback of the free course by Stanford Online on Stanford Online.

Length1:40:43
Chapters19
Modules6
Plain Markdown with clickable timestamps — drops into Obsidian, Notion or GitHub as-is.

It traces one continuous arc from RAG internals (bi-encoders, BM25, NDCG) all the way to agent harnesses, MCP and coding agents — grounding agent design in concrete retrieval mechanics rather than buzzwords.

Who it's for
Read this guide if
  • You want to understand why hybrid BM25 + semantic retrieval beats either alone
  • You are building RAG systems and need re-ranking and NDCG/Recall@k evaluation
  • You want a concrete mental model of tool calling, MCP servers/clients and prompt caching
  • You are comparing coding agent harnesses and compaction strategies
Skip ahead if
  • You want a hands-on coding walkthrough of an agent framework
  • You already know RAG, re-ranking and NDCG cold and only need coding-agent specifics
  • You need fine-tuning theory rather than system design
In brief
  • ~100 minutes (6043 s) of lecture, split into 18 readable chapters across 7 modules
  • Covers the full RAG pipeline: chunking, bi-encoders, BM25, hybrid retrieval, re-ranking, NDCG
  • Second half covers tools, MCP, prompt caching, REACT, memory and coding agents
  • Concrete numbers throughout: ~1M-token context, ~100 candidates, 10% chunk overlap, cached input 10x cheaper
  • Graduate-level Stanford course (CME295, Autumn 2026), lecture 6

The walkthrough

Each chapter below is our original written explanation of what happens at that moment in the video — a paraphrase, not a transcript. Click any timestamp to jump the player.

Why RAG Exists

These chapters establish the core problem: LLMs only know their training data and cannot act. Even GPT-6 Astra's ~1M-token context window cannot absorb everything since its April 30, 2026 cutoff, motivating retrieval-augmented generation.

0:00

Introduction

The lecture frames AI agents through the evolution of coding assistance: manual coding, then ChatGPT-style prompting around late 2022, then IDE autocomplete driven by next-token prediction in 2024, and finally today's coding agents that handle full end-to-end tasks — writing code, testing it, and deploying. This progression motivates why a plain LLM is no longer enough: modern agents must know current facts and perform actions. The instructor sets up the lecture as the journey from passive text prediction to systems that retrieve, decide, and execute.

5:40

Two Limitations of LLMs

Two limits motivate the lecture. First, an LLM only knows its training data: it cannot answer questions about your private codebase, and models state a knowledge cutoff (the example given is GPT-6 Astra with an April 30, 2026 cutoff), so a recent midterm election result would be unknown. Second, LLMs can only respond to prompts, not act — the instructor notes a model cannot actually order a 17-inch teddy bear. Stuffing fresh data into prompts fails because context is limited, and even a roughly one-million-token window performs worse on long inputs.

8:53

RAG: Retrieve, Augment, Generate

RAG solves the knowledge problem by augmenting the prompt with only query-relevant information: retrieve documents from a knowledge base by comparing them to the query, insert them into the prompt via special tags, and generate. The instructor highlights hidden costs — retrieved tokens count toward input pricing, and reasoning tokens are billed even when hidden from users — so retrieval must be optimized. Cost also scales per input token, and the 'needle in a haystack' test shows accuracy degrades on long inputs, especially for facts near the top of documents.

12:43

Building the Knowledge Base

The retrieval step is called the most critical part of RAG, because natural language allows rephrasing without exact word matches. Building the knowledge base means collecting documents, splitting them into chunks, and embedding each chunk as a vector. Key hyperparameters are embedding size (on the order of thousands, larger for nuanced documents), chunk size (hundreds of tokens), and overlap, typically around 10%. Overlap prevents information being sliced at naive chunk boundaries and avoids chunks whose sentences lack the preceding context they need to be interpretable.

Candidate Retrieval

Candidate retrieval maximizes recall cheaply over millions of chunks: bi-encoders precompute embeddings, BM25 handles exact keyword matches like 'Cuddly', and hybrid ranking combines both. Query-side tricks such as hypothetical document embeddings fix the question-versus-document mismatch.

17:12

Candidate Retrieval & Bi-encoders

Retrieval runs in two steps: first a cheap candidate pass maximizing recall over thousands or millions of documents, then a more involved ranking model that selects the top-K chunks (roughly 100 candidates) for the prompt. The bi-encoder embeds the query and each chunk separately, which is cheap because chunk embeddings are precomputed — at inference time only the query embedding and an approximate nearest-neighbor search run. Chunks stay fixed per request; the query determines what is retrieved, and new documents can be added as long as the same embedding model is used.

19:00

Semantic vs. Keyword: BM25 & Hybrid

Semantic similarity needs 'apple to apple' comparisons. The running example: a query 'Where is Cuddly?' (a teddy bear) may wrongly retrieve chunks about 'Huggy' or 'Where is Paris located?' because wording is similar, while missing the actual Cuddly chunks. BM25 fixes this with exact keyword matching, but keyword matching alone also fails when meaning is expressed in different words. In practice, hybrid retrieval combines ranks from semantic search and BM25, and the hybrid usually outperforms either method on its own.

24:00

Query-Side Improvements & Chunk Contextualization

Because queries are questions and documents are sentences, a shared encoder creates embedding discrepancy; hypothetical document embedding addresses this by generating a fake document from the prompt and matching that against chunks. If a query bundles several questions, it can be rewritten into separate questions retrieved independently. Chunks can also lack standalone context, so an LLM prompted with the whole document can add context to each chunk. A cost trick: put the fixed document at the start of the prompt so cached pricing applies — OpenAI cached input is 10x cheaper than the ~$10 per million tokens.

Re-Ranking & Evaluation

With only ~100 candidates, a cross-encoder scoring query and chunk jointly can afford full attention between tokens, distinguishing 'red scarf, blue socks' from 'blue scarf, red socks'. Quality is then measured with NDCG, reciprocal rank, Recall@k and precision against labeled data.

28:36

Re-Ranking with Cross-Encoders

The second pipeline stage re-ranks the ~100 retrieved chunks. Since the set is small, query and chunk can be passed together through one shared encoder: special tokens mark which part is query and which is chunk, and attention models token relationships directly, capturing nuance that separate single-vector encodings lose. The example is 'teddy bear with red scarf and blue socks' versus 'blue scarf and red socks', which embed similarly apart but distinguishably together. A BERT-style encoder with a CLS-token projection predicts binary relevance, and each chunk is scored individually to produce the final ranking.

35:16

Retrieval Evaluation Metrics

Evaluation compares top-k predictions against labeled relevant documents. NDCG (Normalized Discounted Cumulative Gain) at k scores rankings higher when relevant documents sit at the top; dividing DCG by the perfect-ranking DCG bounds the metric between 0 and 1, where closer to 1 is better. Reciprocal rank is 1 divided by the rank of the first relevant chunk. Recall@k measures the proportion of all relevant documents captured in the top-k, while precision measures the proportion of predicted top-k documents that are truly relevant — the same definition as binary classification precision.

42:20

Practical RAG Notes & Where RAG Stops

Several practical points close the RAG discussion. For code, semantic similarity rarely makes sense — coders want exact matches via grep, which finds all occurrences of a term; semantic and keyword search suit natural-language problems. Teams usually include all k retrieved chunks in the prompt, though a relevance threshold can filter weak ones, and chunks are typically ordered most-to-least relevant. Vector databases serve candidate retrieval but cannot do re-ranking, since joint scores cannot be precomputed. Crucially, a real-time query like 'find a teddy bear near me' needs GPS and a live backend — beyond static RAG.

Tools & Tool Calling

Tools let an LLM predict actions instead of answers: predict the call, execute it (GPS, web search, calculator, code execution, email), then feed the result back. Tools are Python functions with typed inputs and structured outputs whose implementation code is never shown to the model.

47:20

The Three-Stage Tool Call

Tools let an LLM predict actions rather than answer directly, in three stages: the model predicts which tool call to make, the action executes (getting GPS coordinates, querying a backend), and the result is fed back so the model writes a final user-facing response. Latency is usually acceptable: GPS is near-instant and backend searches, while noticeable, tend to be shorter than generation time, so tool latency rarely dominates. Executing code is technically not a tool call — it is wrapped as a command, after which the agent becomes available again.

50:50

Designing Interpretable Tools

Providers express tools in Python: each tool is a function whose name matches the API description shown to the LLM, complete with inputs, outputs and documentation, while the implementation code stays hidden until execution. Inputs need clearly typed arguments (like 'location'), and outputs must be structured with enums or classes so the model can convert results back into natural language — the example tool returns name, distance and mood fields, letting the LLM report that 'Teddy' is nearby. Common tool classes include web search, calculators for math (next-token prediction is unreliable for 2×3), code execution for plots, and action flows like drafting emails. Historically SFT baked tool use in; today it is prompted.

Tool Conflicts, Routing & MCP

As tool sets grow, overlapping tools change query interpretation ('find my teddy bear' — files or physical location?). Lightweight routing models select a subset of tools, MCP standardizes definitions into tools, prompts and resources, and prompt caching with TTLs keeps instruction costs down.

1:04:06

Tool Conflicts

Exposing many tools creates conflicts when scopes overlap: for 'show me my teddy bear's morning routine', get_doc and get_drive might both apply — benign if outputs are identical, but problematic when interpretation changes. 'Can you find me my teddy bear' could mean searching files for a picture or physically locating it. Blaming underspecified queries on users is called unfair, since inactive-but-active tools can pick up the query, and tool-space controllers and tool servers are usually different entities. Forcing determinism with temperature=0 can degrade quality and lock in a consistently wrong answer.

1:09:10

Routing & Context Rot

Mitigation starts with tool selection: a subset is chosen using conversation history (physical context points to find_teddy_bear), memory of past query specificity, enterprise user profiles (finance versus engineering tool sets), and user activation preferences. The routing model is deliberately a lightweight, low-latency transformer-style LLM, because routing works in natural-language space and is not a hard task. Selection is two-step — pick the subset, then place only that subset in the context. Even with non-overlapping tools, too many hurt performance due to 'context rot': tool-calling degrades as context grows, so providers minimize bloat.

1:12:08

MCP & Prompt Caching

Without standards, every tool needs a separate implementation per LLM; MCP lets a tool connect to any supporting provider. MCP splits into a server (tool implementation and business logic) and a client (which queries the server; users touch the client), and defines three buckets: tools, prompts (shortcuts into workflows), and resources (items clients feed to tools). A poetry example maps two tools, two prompts and the teddy bear's book collection as a resource — implement once, connect anywhere. Prompt caching offsets instruction costs (savings up to an order of magnitude), now with time-to-live options like 5 minutes or 1 hour, where a workflow reusing input every minute fits a 5-minute TTL.

Harnesses, REACT & Memory

The harness — tools, prompting, compaction, memory — complements the model like a car body around an engine. REACT loops observe-plan-act until a satisfactory state, while compaction and long-term memory keep the context window usable; fixed instructions go first so cached pricing applies.

1:15:19

Prompt Layout & Caching Mechanics

A prompt typically contains the user query, tool definitions, and user context — the latter inferred invisibly by the provider, e.g. the current date answering 'what day is it' without a tool call, or rough IP-based location steering web searches. Variable parts (like a timestamp that changes each query) must come after fixed parts, because caching cannot be leveraged if variable content precedes fixed instructions; fixed text at the top makes instruction tuning cost 'cached money'. Caching is keys-and-values, so editing a tool description invalidates it — a small cost since descriptions change at most daily, even at hundreds of requests per minute.

1:23:08

The Harness & REACT

The harness is defined as everything surrounding the model except the model itself: tools, action ordering, compaction strategy, memory, prompting. Model and harness are complementary like an engine and the rest of a car — a weak model with a strong harness, or vice versa, will not work. The REACT paradigm (formalized 2023) means Reason + ACT: observe the current state, plan, execute tools, observe results, and loop until a satisfactory state before answering. A thermostat agent demonstrates this: ground the temperature via a tool, compare to a comfortable range, increase temperature, verify. The observe/plan/act steps become native through SFT, and each execution includes a dedicated recap stage.

1:28:09

A2A, Compaction & Memory

Agents also have their own interaction protocol: A2A, released the prior year, standardizes how agents communicate and defines each agent's skills. When the context window fills, compaction strategies apply: delete tool-call outputs needed only for the next turn, use time-based sliding windows, or structure prior work into buckets like the PIE coding agent's 'current progress' and 'remaining work'. Terminology: short-term memory is the context window; long-term memory persists across conversations, implemented via RAG over past chats or memory tools triggered by cues. Reasoning traces are generally not kept after compaction — only a high-level gist of user intent remains.

1:33:32

Coding Agents

Coding agents run a reason-plus-act loop inside an execution environment that touches the user's system. Safety has shifted from per-action manual approval (common about a year ago) to auto-approval by a lighter model judging proposed actions. They largely ignore traditional RAG — grep with regex is extremely effective because regexes predict user intent better than semantic retrieval. Users control context via agents.md, a standardized persistent rules file. 'Skills' package reusable recipes (prompting, tools, scripts), best created by doing a task end-to-end and asking the agent to reframe it. Pi is a minimalist harness for fair model comparison; sub-agents are costly, and agent swarms show promise but carry risks like the Hugging Face hack.

Moment by moment

TimeWhy it matters
8:53RAG defined: retrieve, augment, generate — the lecture's central pipeline
19:00The 'Cuddly vs Huggy' example showing why hybrid BM25 + semantic retrieval wins
35:16NDCG and Recall@k — how retrieval quality is actually scored
47:20The three-stage tool call that turns an LLM into an agent
1:23:08Harness definition and the REACT observe-plan-act loop

Do this next

  1. Rebuild the RAG evaluation chapter: take a small labeled query-document set and compute NDCG@k, Recall@k and reciprocal rank by hand for a mock ranking
  2. Sketch a hybrid retriever: run a BM25 and a bi-encoder search on the same corpus, then merge ranks and compare against either method alone
  3. Write one MCP-style tool with typed inputs, a structured output class and a docstring, then test how your LLM behaves with and without that documentation

Common questions

Why is stuffing everything into the context window not a viable alternative to RAG?

The lecture gives three reasons. Even GPT-6 Astra's roughly one-million-token context is too small for everything since the training cutoff, and the 'needle in a haystack' test shows performance degrades on long inputs, especially for facts near the top of documents. Additionally, pricing is per input token, so brute-force stuffing is expensive — retrieved tokens count as input cost.

What are the recommended hyperparameters for chunking documents?

Embedding size should be on the order of thousands, larger for nuanced documents. Chunk size should be on the order of hundreds of tokens. Chunk overlap is typically about 10%, which prevents information being lost at naive chunk boundaries and avoids chunks containing sentences without their preceding context. Retrieved candidate counts of roughly 100 chunks for the ranking stage are also cited.

Why combine BM25 with semantic similarity instead of picking one?

Each fails in opposite ways. A semantic query 'Where is Cuddly?' may wrongly retrieve similar-sounding chunks about 'Huggy' or 'Where is Paris located?' while missing the right ones; BM25's exact keyword matching fixes that. But BM25 alone misses documents that express the same meaning in different words. The lecture states hybrid retrieval combining both ranks usually outperforms either method alone.

How does a cross-encoder re-ranker differ from a bi-encoder?

A bi-encoder embeds query and chunk separately, letting chunk embeddings be precomputed for cheap candidate retrieval. A re-ranker passes query and chunk together through one encoder, with special tokens marking each part, so attention models token-to-token relationships — distinguishing 'red scarf and blue socks' from 'blue scarf and red socks'. A BERT-style CLS-token projection predicts 0–1 relevance per pair. This is only affordable on the ~100-candidate set.

What is MCP and what are its three standardized buckets?

MCP (Model Context Protocol) standardizes how tools connect to any supporting LLM provider, so a tool is implemented once instead of once per provider. It has a server holding tool implementation and business logic, and a client users interact with. Definitions fall into three buckets: tools (standardized argument/output templates), prompts (shortcuts into specific workflows), and resources (items the application layer feeds to tools), illustrated by a poetry teddy bear example.

What is 'context rot' and how do providers fight it?

Context rot is the degradation of tool-calling capability as the context window grows — even with non-overlapping tools and perfect prediction, too many tools in context hurt performance. Providers minimize context bloat by running a lightweight, low-latency routing model that selects a relevant subset of tools first, then placing only that subset into the LLM's context window for it to operate over.

How does prompt caching work for tool-heavy agent prompts?

Caching operates on keys and values, so fixed content must sit at the top of the prompt before variable parts like the per-query timestamp; otherwise the cache cannot be leveraged. Providers offer cached input up to an order of magnitude cheaper than regular input tokens, with time-to-live options such as 5 minutes or 1 hour. Changing a tool description invalidates the cache, but since descriptions change at most daily, re-heating costs stay small even at hundreds of requests per minute.

Why do coding agents skip traditional RAG?

Because code retrieval is about exact matches, not meaning. The lecture says grep — searching a codebase for a term via regular expressions — is extremely effective, since regexes predict user intent better than semantic retrieval in coding contexts. Semantic and keyword search are described as mostly applicable to natural-language problems, while coding agents combine the reason-plus-act loop with an execution environment touching the user's system.

Spot a mistake?

Every chapter summary above is hand-checked against the video, but a 100-minute lecture leaves room for slip-ups. If you spot an error in a timestamp, quote or explanation, please tell us so we can fix it.

More course guides