Video summary

Stanford CME295 Transformers & LLMs | Autumn 2026 | Lecture 6 - AI Agents

Main summary

Key takeaways

Educational

Lecture 6: AI Agents — Summary

The lecture explains how LLM-based systems develop from text generators into agents that can retrieve information, use tools, take actions, and manage longer tasks. It focuses on retrieval-augmented generation (RAG), tool use, agent workflows, and coding agents.

Why Agents Are Useful

A basic LLM has two important limitations:

  • Limited or outdated knowledge: It can only rely on information available during training, so it may not know about recent events, private files, or a user’s codebase.
  • No ability to act: On its own, it generates responses but cannot, for example, check a user’s location, search a live service, run code, or send an email.

Simply adding more information to the prompt is not always a good solution. Context windows have limits, model performance can decline when input grows very large, and processing more tokens costs more. Agents address these constraints by selectively retrieving information and using tools.

Retrieval-Augmented Generation (RAG)

RAG supplements a user’s question with relevant information retrieved from an external knowledge base. The LLM then generates an answer using both the question and the retrieved material.

Basic RAG Workflow

  1. Retrieve: Search a knowledge base for documents or passages relevant to the user’s query.
  2. Augment: Add the selected material to the prompt, commonly marking it as retrieved context.
  3. Generate: Ask the LLM to answer using the augmented prompt.

Retrieval quality is central to RAG. The goal is to include useful information without overwhelming the model or needlessly increasing token costs.

Preparing a Knowledge Base

  • Gather documents relevant to the task.
  • Divide documents into smaller passages called chunks.
  • Convert each chunk into an embedding vector for semantic search.
  • Choose key configuration settings:
    • Embedding size: Larger embeddings may help represent nuanced material.
    • Chunk size: Chunks are commonly hundreds of tokens; very large chunks add unnecessary context.
    • Chunk overlap: Overlap—often around 10%—can preserve context when a passage is split mid-sentence or across a key piece of information.

Chunks can also be given additional context from their source document so they make more sense when retrieved on their own.

Candidate Retrieval and Reranking

Retrieval is commonly performed in two stages:

  1. Candidate retrieval

    • Search a large collection efficiently and retrieve a broad set of likely matches.
    • A bi-encoder embeds the query and each document separately. Document embeddings can be computed in advance, making this approach relatively inexpensive at query time.
    • Approximate nearest-neighbor search can help search large embedding collections.
    • Semantic similarity is useful when the wording of a query differs from the wording of relevant documents.
    • BM25 ranks documents using keyword matches. It can help when exact terms matter but may miss paraphrases.
    • A hybrid approach combines semantic and keyword-based rankings, often improving on either alone.
    • Retrieval can be improved by rewriting complex queries into smaller questions or by creating a hypothetical document from the query and searching with that.
  2. Reranking

    • Examine the smaller candidate set more carefully and order it by relevance.
    • A cross-encoder processes the query and a candidate passage together. Because their tokens can interact through attention, it can capture finer relationships than comparing separately generated embeddings.
    • This is more computationally expensive than candidate retrieval, but practical when applied to a limited set of candidates.
    • The system can then add the top-ranked passages to the prompt, often in relevance order.

For coding tasks, semantic retrieval is not always the best fit. Developers often need exact references to symbols or strings, so agents frequently use fast text-search tools such as grep.

Evaluating Retrieval

Evaluation typically uses labeled query–document examples, identifying which passages are actually relevant. Common metrics include:

  • NDCG@K (normalized discounted cumulative gain): Rewards placing relevant documents near the top of the first K results. A score closer to 1 indicates a better ranking.
  • MRR (mean reciprocal rank): Measures how highly the first relevant result appears; higher is better.
  • Recall@K: Measures how many of the relevant documents appear among the top K results.
  • Precision@K: Measures what proportion of the top K results are relevant.

Tools and Tool Calling

Tools let an LLM interact with external systems or perform operations that are more reliable than text generation alone. Examples include web search, weather or stock queries, codebase search, calculators, code execution, GPS lookup, and sending email.

Typical Tool-Use Cycle

  1. The LLM interprets the request and selects a tool, supplying its arguments.
  2. The system executes the tool outside the LLM.
  3. The result is returned to the LLM, which uses it to respond to the user or decide what to do next.

A tool is generally exposed to the model through an API description—not by showing the model the tool’s underlying implementation. Tool descriptions and schemas should make inputs and outputs clear. Structured types, such as enums, can help make results easier for the model to interpret.

For some operations, tools are preferable because they are deterministic. For example, a calculator is more dependable than asking an LLM to produce arithmetic results by predicting tokens.

Tool Selection, Context, and Caching

Giving an agent too many tools can create problems:

  • Tools may overlap, causing ambiguity about which one fits a request.
  • A vague query may be interpreted differently by different tools—for instance, searching for a file about a teddy bear versus locating a real bear nearby.
  • A large set of tool descriptions consumes context and can reduce performance.

A tool-selection or routing system can narrow the available tools based on factors such as conversation history, user profile, past preferences, and which tools the user has enabled. A lightweight model may be sufficient for routing.

The lecture also highlights prompt caching as a way to reduce the cost of repeated instructions. Place stable content—such as reusable tool definitions—at the beginning of the prompt, before changing content such as the latest user query. Cached input can be cheaper when reused within its cache lifetime, although changing the fixed instructions may require caching them again.

MCP and Interoperability

The Model Context Protocol (MCP) provides a standardized way for applications and LLMs to work with tools and related context.

  • An MCP server provides tool implementations and their associated logic.
  • An MCP client connects to the server and makes its capabilities available to an application or user.
  • MCP standardizes categories including:
    • Tools: Actions with defined arguments and outputs.
    • Prompts: Reusable instructions or workflows.
    • Resources: Context or data made available to the application.

The benefit is that a tool can be implemented in a standard way and connected to compatible clients, rather than building a separate integration for every LLM provider.

Harnesses and the ReAct Pattern

A harness is the system around the model: tools, prompts, action order, memory, and context-management strategies. The lecture compares the model to an engine and the harness to the rest of the vehicle: both matter to the overall system’s performance.

The ReAct pattern combines reasoning and acting through an iterative cycle:

  1. Observe the current state.
  2. Plan what action could help.
  3. Act by calling a tool.
  4. Observe the result and repeat as needed.
  5. Return a response or stop once the goal is satisfied.

For example, an agent managing a thermostat might check the current temperature, compare it with the desired temperature, adjust the setting, and check again. Tool-using agents may also communicate with other agents; the lecture mentions A2A as a protocol for describing agent capabilities and interactions.

Context Compaction and Memory

Long agent sessions can exceed the context window. The lecture describes several ways to manage the conversation:

  • Remove tool outputs or other details that are no longer needed.
  • Use a sliding window that retains more recent conversation.
  • Summarize the interaction into structured categories—such as progress so far and work remaining—and continue using the summary.

The lecture distinguishes:

  • Short-term memory: The current context window and conversation.
  • Long-term memory: Information saved for use in later interactions, such as a user’s preferences or notes.

Long-term memory can be retrieved from past conversations using RAG or stored through a dedicated memory-saving tool. A compacted summary usually preserves the user’s goals and relevant history rather than the original reasoning trace.

Coding Agents

Coding agents use tools to interact with a software environment and can carry out multi-step programming tasks. Important design considerations include:

  • Safety: Proposed actions may need review. The lecture notes a shift from confirming every action manually toward automated checks that assess whether actions are safe.
  • Code search: Agents often rely on grep and other exact-match searches to locate functions, symbols, and references efficiently.
  • Project instructions: An AGENTS.md file can provide persistent rules and preferences for a coding agent.
  • Skills: Reusable task recipes can capture recurring workflows. They may include instructions, tool calls, or scripts, and can be derived from workflows an agent has already completed.
  • Subagents and agent swarms: A task may be delegated to subagents, or multiple agents may coordinate. These approaches can be costly because agents need their own context and interaction cycles, and greater autonomy can introduce risks.
  • Computer-use agents: Controlling a computer through screenshots and predicted actions is described as relatively inefficient compared with direct tools.

Speakers and Sources Mentioned

Speakers

  • Afshine Amidi — Presented the first portion of the lecture, covering RAG, retrieval, reranking, and evaluation.
  • Shervine Amidi — Presented the second portion, covering tools, MCP, harnesses, memory, and coding agents.
  • Students in the audience — Asked questions; they were not individually identified.

Named Protocols, Tools, and References

  • RAG, BM25, NDCG, MRR, grep, and ReAct
  • Model Context Protocol (MCP) and A2A
  • AGENTS.md and Pi, discussed in connection with coding agents
  • Hugging Face hack and the Model Assessment and Threat Research group, mentioned in a discussion of agent risks

Rate this summary

Your feedback will help improve summaries.

Improve this summary

Reprocess with a stronger model when the summary feels incomplete or inaccurate.

Pro

Translate summary in another language

Pro

Ask questions to this video

Chat for follow-up questions, clarifications, and source-backed answers.

Coming soon

Share this summary

Original video