Repository navigation
Module 3: Foundational Concepts
LLMs are trained on vast amounts of information, but that knowledge is frozen at training time and can't be updated without expensive retraining. This "frozen" knowledge is known as parametric memory, permanantly encoded in the the model weights during training.
For tasks that require current or very specialized information, that frozen knowledge isn't enough. Models will hallucinate: generating answers that sound confident but are factually wrong or outdated.
Non-parametric memory solves this by storing knowledge outside the model, in documents, databases, or files that can be updated, verified, and tailored to a specific domain or organization. Unlike parametric memory, it can be regularly updated with new information the model was never trained on.
Retrieval-Augmented Generation (RAG) introduced by Lewis at al. is one of the most widely used forms of non-parametric memory in production AI systems, in which relevant documents are retrieved from an external knowledge store at the moment a question is asked and passed to the model as context — so answers are grounded in current, verifiable evidence.
| Parametric Memory | Non-Parametric Memory | |
|---|---|---|
| Summary | • Knowledge is encoded in the model's weights during training and frozen at cutoff • Broad but shallow in specialized domains; updating requires retraining |
• Knowledge is stored externally in documents, databases, or APIs • Scoped to your domain and updated without retraining |
| How reliable it is | • Cannot be directly audited; sources cannot be traced to a specific document • Failure mode: hallucination — confident generation of plausible but incorrect content |
• Fully auditable — retrieved documents can be cited, inspected, and their provenance verified • Failure modes: retrieval failure — correct documents not retrieved; context overflow — too much irrelevant context |
| When to use it | Suitable for general reasoning, language tasks, and domains where training data is comprehensive and current | Required for organizational knowledge bases, recent information, proprietary data, and compliance-sensitive domains |
Bommasani et al. (2021), in the Stanford CRFM foundation models report, provide the broader theoretical context: the capabilities and limitations of foundation models are deeply shaped by the training data distribution and the model's capacity to generalize from it. RAG is, in their framing, an architectural strategy for extending a foundation model's effective knowledge boundary beyond what can be efficiently encoded in parameters — a particularly important capability for the specialized, proprietary, or dynamic knowledge that characterizes professional deployment environments.
Note
Every organization that deploys AI agents in knowledge-intensive contexts faces the same core problem: the agent's parametric knowledge does not include the organization's internal documents, policies, proprietary data, or recent developments. RAG is the current production- standard solution to this problem.
- Lewis, P., Perez, E., Piktus, A., Petroni, F., Karpukhin, V., Goyal, N., ... & Kiela, D. (2020). Retrieval-augmented generation for knowledge-intensive nlp tasks. Advances in neural information processing systems, 33, 9459-9474.
- Bommasani, R., Hudson, D. A., Adeli, E., Altman, R., Arora, S., von Arx, S., ... & Liang, P. (2021). On the opportunities and risks of foundation models. arXiv preprint arxiv:2108.07258.
Video 1: "What is Retrieval-Augmented Generation (RAG)?" - IBM Technology (~6 min)
- Watch focus: RAG concept and how RAG is used with LLMs.
b. Chapter 2: The Six-Stage RAG Pipeline — Architecture, Design Decisions, and Downstream Consequences
Gao et al. (2023), in their survey of the RAG literature, identify three evolutionary RAG paradigms — Naive RAG, Advanced RAG, and Modular RAG — that represent increasing sophistication in pipeline design. However, all three paradigms share the same six functional stages. Understanding these stages and the design decisions made at each is the foundation for diagnosing failures in any RAG system.
In the lab, Stages 5 and 6 are implemented as an agent: a retriever is wrapped as a tool, as in Module 2, and the agent decides when to search the documents and writes the grounded answer. This approach, often called agentic RAG, replaces the older RetrievalQA chain, which is no longer part of LangChain 1.x.
- Lewis, P., Perez, E., Piktus, A., Petroni, F., Karpukhin, V., Goyal, N., ... & Kiela, D. (2020). Retrieval-augmented generation for knowledge-intensive nlp tasks. Advances in neural information processing systems, 33, 9459-9474.
- Gao, Y., Xiong, Y., Gao, X., Jia, K., Pan, J., Bi, Y., ... & Wang, H. (2023). Retrieval-augmented generation for large language models: A survey. arXiv preprint arxiv:2312.10997, 2(1), 32.
- LangChain Documentation — Retrieval Guide, Document Loaders, Text Splitters, Vector Stores, Retrievers
Video 2: "RAG Explained For Beginners" - KodeKloud (~10 min)
- Watch focus: The full RAG pipeline - document ingestion, text splitting, embedding generation, vector store indexing, semantic retrieval, and augmented generation.
Reading 1: Langchain Retrieval Documentation
- Take note of the different building blocks LangChain provides for RAG (document loaders, text splitters, embedding models, vector stores, retrievers) and map them to the stages of the RAG pipeline.
Language models are stateless: each call sees only the messages sent with it. An agent therefore has no memory of earlier turns unless the system keeps the conversation and sends the relevant part back with every new message. Memory design is the set of decisions about what to keep, how to represent it, and where to store it.
Consider a customer support agent. A user says "I want to return the blue jacket I ordered last week." Three turns later they ask "What's the refund timeline for that item?" Without memory, the agent has no idea what "that item" refers to. It would have to ask again, breaking the conversation.
In Module 2 you built agents with create_agent. The agent's state is a list of messages: every user message, model reply, tool call, and tool result. Memory comes from two pieces:
-
A checkpointer saves the state after every step. Each conversation has its own
thread_id, so one agent can serve many users without mixing their histories. - Middleware (optional) decides how much of that history the model actually sees, for example by dropping or summarizing older messages.
With only a checkpointer, the agent remembers everything in the thread:
from langchain.agents import create_agent
from langgraph.checkpoint.memory import InMemorySaver
agent = create_agent(
model="openai:gpt-4o-mini",
tools=[search_policies], # the retrieval tool from the lab
checkpointer=InMemorySaver(),
)
config = {"configurable": {"thread_id": "customer-42"}}
agent.invoke({"messages": [{"role": "user", "content": "I want to return the blue jacket."}]}, config)
agent.invoke({"messages": [{"role": "user", "content": "What's the refund timeline for that item?"}]}, config)No single pattern is best. Each one trades token cost against context fidelity:
| Pattern | How it works | Token cost | Best use case | Implementation with create_agent
|
|---|---|---|---|---|
| Buffer | Keeps every message verbatim | Grows with each turn | Short conversations (fewer than about 10 turns) where full fidelity matters — e.g., medical record review, compliance dialogue | Checkpointer only (as above) |
| Window | Keeps only the last k turns; drops older messages | Stable once the window is full | Customer support, coding assistants — recent context matters most | A small @before_model middleware that trims old messages (example below) |
| Summary | Replaces older messages with an LLM-written summary | Low and stable | Long, multi-session discussions where decisions must persist but exact wording need not |
SummarizationMiddleware keeping very few recent messages |
| Hybrid | Rolling summary of older turns + verbatim recent turns | Low to moderate | Long, dense conversations (debugging, iterative drafting) needing both recency and long-range context — a sensible default for production |
SummarizationMiddleware keeping a larger recent buffer |
Window memory: keep only the most recent messages
from langchain.agents.middleware import before_model
from langchain.messages import RemoveMessage
from langgraph.graph.message import REMOVE_ALL_MESSAGES
from langchain_core.messages.utils import trim_messages
@before_model
def window_memory(state, runtime):
"""Keep roughly the last three turns (six messages)."""
recent = trim_messages(
state["messages"], max_tokens=6, token_counter=len, # count messages, not tokens
strategy="last", start_on="human", include_system=True,
)
if len(recent) == len(state["messages"]):
return None
return {"messages": [RemoveMessage(id=REMOVE_ALL_MESSAGES), *recent]}
agent = create_agent(model="openai:gpt-4o-mini", tools=[search_policies],
middleware=[window_memory], checkpointer=InMemorySaver())Summary and Hybrid memory: summarize older turns
from langchain.agents.middleware import SummarizationMiddleware
hybrid = SummarizationMiddleware(
model="openai:gpt-4o-mini", # the model that writes the summary
trigger=("tokens", 3000), # summarize once the history exceeds ~3,000 tokens
keep=("messages", 10), # Hybrid: keep the 10 most recent messages verbatim
) # Summary: use a much smaller keep, e.g. ("messages", 2)
agent = create_agent(model="openai:gpt-4o-mini", tools=[search_policies],
middleware=[hybrid], checkpointer=InMemorySaver())Summarization has a cost of its own: the summary is written by an LLM, so specific details such as names, numbers, and exact wording can be lost or distorted over many rounds (semantic drift). Test that the details your application depends on survive summarization.
InMemorySaver keeps memory only while the program runs. To keep conversations across restarts, use a database-backed checkpointer. The interface is the same:
import sqlite3
from langgraph.checkpoint.sqlite import SqliteSaver # pip install langgraph-checkpoint-sqlite
conn = sqlite3.connect("agent_memory.db", check_same_thread=False)
agent = create_agent(model="openai:gpt-4o-mini", tools=[search_policies],
checkpointer=SqliteSaver(conn))Production systems typically use a server database such as PostgreSQL in the same way. Storing conversations also creates data governance questions — what is kept, for how long, and who can read it — which Module 5 addresses.
create_agent is built on LangGraph, so the message state you used here is already a LangGraph state. In Module 4 you will extend that state with your own typed fields and share it among several agents. The memory patterns from this chapter carry over unchanged.
Note
MEMORY PATTERN SELECTION IS A COST-QUALITY TRADE-OFF
A medical record review agent needs complete fidelity (Buffer) and will accept higher token cost. A customer support bot serving thousands of long conversations a day cannot sustain unbounded token growth, so Window or Hybrid memory keeps costs manageable at the expense of some lost context.
Tip
Older code. Tutorials written before LangChain 1.0 often implement memory with RunnableWithMessageHistory or with classes such as ConversationBufferMemory and ConversationSummaryMemory. The four patterns are the same; only the mechanism differs. New work in this course uses checkpointers and middleware, as shown above.
- LangChain Documentation — Short-term memory: checkpointers, trimming, deleting, and summarizing messages.
- LangChain Documentation — Built-in middleware:
SummarizationMiddlewareand related options. - LangChain Documentation — Agents: how
create_agentmanages state. - Gao, Y., Xiong, Y., Gao, X., Jia, K., Pan, J., Bi, Y., ... & Wang, H. (2023). Retrieval-augmented generation for large language models: A survey. arXiv preprint arXiv:2312.10997.
The context window of an LLM backbone is a finite resource. Every token consumed by retrieved context is a token unavailable for the user's query, prior conversation history, system instructions, and the model's own generated response. Managing this finite resource — deciding what to include, at what granularity, and through what retrieval strategy — is the optimization discipline that separates high-quality RAG systems from low-quality ones. Module 3 addresses this through two complementary optimization dimensions: chunking strategy selection and retrieval method selection.
Chunking Strategy Selection
Chunking is the most consequential single decision in RAG pipeline design (Gao et al., 2023). The chunk size and overlap parameters, and the splitting logic used, determine the granularity of information available to the retriever. Four primary chunking strategies exist:
Retrieval Method Selection and Context Compression
Beyond chunking, two further optimization levers determine context quality:
- Similarity Search vs. Maximum Marginal Relevance (MMR): Standard similarity search retrieves the k chunks most semantically similar to the query — but if the corpus contains near- duplicate content (e.g., the same policy statement repeated across multiple documents), all k retrieved chunks may be near-identical, providing redundant context. MMR balances similarity to the query with dissimilarity to already-retrieved chunks, producing a diverse set of relevant context. MMR is preferred whenever the corpus has significant redundancy or whenever diverse perspectives on a query are desirable.
- Metadata Filtering: Vector store metadata (document date, author, category, section header) can be used as pre-retrieval filters: 'retrieve only from documents tagged as Policy documents published after 2023.' Metadata filtering dramatically reduces the search space and improves precision for queries with implicit temporal or categorical constraints that are not captured in the query embedding.
- Re-ranking: Post-retrieval re-ranking applies a cross-encoder model (more accurate but more expensive than the bi-encoder used for initial retrieval) to re-score and re-order the initially retrieved chunks before context injection. Re-ranking is an Advanced RAG technique that significantly improves retrieval precision at the cost of additional inference time.
- Context Compression (LLMLingua): Context compression tools such as LLMLingua use a small LLM to compress each retrieved chunk by removing sentences that are not relevant to the specific query, before injecting into the generation context. This reduces context tokens while preserving information density — a particularly valuable optimization for chunks retrieved from long documents where only a portion of the chunk content is relevant to the specific query.
Note
Practitioner tip:
When optimizing RAG, vary one parameter at a time (chunk size, retrieval method). Hold all others constant, and measure the impact on RAGAS metrics (covered in Chapter 5).
If you vary multiple
parameters simultaneously, you cannot attribute performance changes to specific design decisions.
- Gao, Y., Xiong, Y., Gao, X., Jia, K., Pan, J., Bi, Y., ... & Wang, H. (2023). Retrieval-augmented generation for large language models: A survey. arXiv preprint arxiv:2312.10997, 2(1), 32. Sections 5 (Advanced RAG patterns)
- LangChain Expression Language LCEL Documentation
- Es, S., James, J., Anke, L. E., & Schockaert, S. (2024, March). RAGAS: Automated evaluation of retrieval augmented generation. In Proceedings of the 18th conference of the european chapter of the association for computational linguistics: system demonstrations (pp. 150-158) (for optimization feedback loops)
Es et al. (2024) introduced RAGAS (Retrieval Augmented Generation Assessment) to address a persistent problem in RAG development: evaluation was subjective, slow, and hard to reproduce. Instead of relying on human judges, RAGAS uses a language model as a judge to score each answer automatically, which makes evaluation fast and repeatable enough to run after every change to a pipeline.
The original paper defines three metrics: faithfulness (are the answer's claims supported by the retrieved context?), answer relevance (does the answer address the question?), and context relevance (how focused is the retrieved context on the question?). The open-source RAGAS library has since added further metrics. This module uses four of them: faithfulness and answer relevance, which evaluate the generation stage, and context precision and context recall, which evaluate the retrieval stage and refine the paper's idea of context relevance. Context recall compares the retrieved context with a reference answer, so it requires a test set with reference answers.
Metrics as implemented in the RAGAS library.
The Three Principal RAG Failure Modes
RAGAS metrics map systematically to three classes of RAG system failure, each with a distinct diagnostic signature and a distinct remediation strategy:
- Es, S., James, J., Anke, L. E., & Schockaert, S. (2024, March). RAGAS: Automated evaluation of retrieval augmented generation. In Proceedings of the 18th conference of the european chapter of the association for computational linguistics: system demonstrations (pp. 150-158)
- Gao, Y., Xiong, Y., Gao, X., Jia, K., Pan, J., Bi, Y., ... & Wang, H. (2023). Retrieval-augmented generation for large language models: A survey. arXiv preprint arxiv:2312.10997, 2(1), 32.
Reading 5 — Es et al. (2024): RAGAS Framework [~15 min]
- Es, S., James, J., Espinosa-Anke, L., & Schockaert, S. (2024). RAGAS: Automated evaluation of retrieval augmented generation. Proceedings of the 18th Conference of the European Chapter of the Association for Computational Linguistics: System Demonstrations, 150–158.
- Read: Abstract and Sections 1–3.
- Extract: How does the paper measure faithfulness, answer relevance, and context relevance? Which one captures the failure of an answer that sounds plausible but contradicts the retrieved documents?
- Then compare: how do the library's context precision and context recall, as described in the four-metric table above, divide the job that context relevance does in the paper?
Created: 05/10/2026 (C. Lizárraga)
Updated: 08/10/2026 (M. Yung)
2026.
Arizona Institute for Artificial Intelligence (AI2S).
Office of Responsible Artificial Intelligence. The University of Arizona.
AI Automation and Agents (v2)
Table of Contents
📂 Preparing your Portfolio in Github
MODULE 1
- 1.1 Module Overview
-
1.2 Foundational Concepts /
1.2 Addendum - 1.3. Module Activities
- 1.4. Additional Resources
Summary and Key Takeaways:
MODULE 2
- 2.1 Module Overview
-
2.2 Foundational Concepts /
2.2 Addendum - 2.3 Activities
- 2.4 Additional Resources
MODULE 3
- 3.1 Module Overview
-
3.2 Foundational Concepts /
3.2 Addendum - 3.3 Activities
- 3.4 Additional Resources
MODULE 4
MODULE 5