Courses / Agentic AI / Module 4
Module 4: Memory and retrieval for agents: short-term, long-term, context compaction
10 h · theory 3 · hands-on 4 · project 2 · revision 1
You will be able to
- Manage the context window across long runs
- Summarise and compact history safely
- Store and recall long-term memories
- Retrieve runbooks with RAG inside the agent
Capstone increment: Runbook retrieval and per-incident memory with context compaction.
Job-description skills: Memory and context management, RAG for agents · Lab tools: pgvector, mem0ai, sentence-transformers
1. The context window is a budget
Every model call sends the whole context: system prompt, tool definitions, history and tool results. In long runs it fills with log dumps and old steps, costs grow with every step, and quality drops as the model has more to attend to. Context engineering is deciding what goes in each call.
Think in kinds of memory: working memory (this run’s recent steps), episodic memory (what happened in past runs), semantic memory (facts about services and users) and procedural memory (runbooks and instructions).
2. Long runs: trim, offload, compact
Three tools, usually used together. Offload big tool outputs: write them to a file or store and keep a short excerpt plus a reference the agent can read again. Trim: keep the last few steps verbatim. Compact: when the context passes a threshold, summarise older steps into a running summary.
Compaction is where agents quietly lose facts. Tell the summariser exactly what to keep (findings, decisions, open questions, ids) and test it: replay long runs and check the final answer still has every finding. Try the policies below.
Largest context 91,200 tokens · overflows the 64k window at step 14 · input tokens for the whole run 12,70,700 (≈ ₹318) · facts still available at the end 4 of 4
- ✓ 5xx errors began at 14:02
- ✓ v2.3 deployed at 14:00
- ✓ DB connection pool exhausted
- ✓ Rollback to v2.2 fixes staging
Guided experiments
- Keep everything. At which step does the run overflow the window? Turn on “store big tool outputs in a file”. Why does that one change fix it and halve the cost?
- Try “last N steps only” with N = 6. The context stays small, but how many facts survive? Why is a sliding window dangerous for investigations?
- Summarise older steps without pinned facts, then with them. What must a compaction prompt say so the summary keeps what matters?
- Combine compaction, pinned facts and capped outputs. Compare the cost with “keep everything”. Which of these would you turn on first in production?
3. Long-term memory
Long-term memory stores facts that outlive a run: “payments’ DB pool max is now 80”, “Arjun is the escalation contact for payments”. Decide what is worth remembering (a write policy), scope every memory (per user, service or tenant), retrieve by relevance with recency and importance, and update conflicting facts instead of storing both.
Libraries such as Mem0, LangMem and Letta handle extraction and retrieval; you still own the policy. Memory is personal data when it is about people: support deletion and don’t remember what you wouldn’t want in a log.
4. RAG inside the agent: runbooks
Most ops knowledge is in runbooks and past incident reports. Give the agent a search_runbooks tool backed by the retrieval pipeline from the RAG Systems course: chunk runbooks by procedure, keep their version and owner, filter by service, and return short excerpts with ids the agent can cite.
Retrieval quality matters as much here as in any RAG system. Build a small golden set of incident-to-runbook pairs and measure recall before blaming the agent for picking the wrong procedure.
5. Measure memory
Write eval scenarios that need memory: a finding from step 3 that decides step 15, a fact from last week’s incident, a runbook that applies only to one service. Track facts recalled at the end, tokens per run and cost per run for each memory policy.
Re-run these scenarios whenever the compaction prompt, the memory write policy or the model changes.
Hands-on: coding window
The coding window and the full VS Code lab are available after you sign in.
Sign in to codeLabs
Lab 4.1: Runbook retrieval
Index 20 runbooks in pgvector with service and version metadata, expose search_runbooks as a tool and measure recall@3 on 15 incident-to-runbook pairs.
Expected: A tool returning cited runbook excerpts and a recall number.
Lab 4.2: Compaction, tested
Add output offloading and compaction to the LangGraph agent. Replay 5 long incidents and compare tokens, cost and facts recalled with and without it.
Expected: A table per policy and the compaction prompt you settled on.
Lab 4.3: Per-incident memory (capstone increment)
Store findings per incident and durable facts per service with scope, importance and update-by-key; add a delete endpoint by scope.
Expected: A follow-up incident on the same service recalls last week’s cause; deleting a scope removes it.
Go deeper
Videos
- Context Engineering for Agents · LangChain · ~22 min. Context engineering for agents: write, select, compress and isolate context, with examples.
- How we solved Context Management in Agents — Sally-Ann Delucia · AI Engineer · ~16 min. How one team solved context management in production agents.
- Agent Memory Explained in 5 Minutes · KodeKloud · ~5 min. Short-term versus long-term agent memory in five minutes.
Further reading
- Paper MemGPT: Towards LLMs as Operating Systems · Packer et al., 2023. Paging memory in and out of the context window, like virtual memory.
- Paper Generative Agents: Interactive Simulacra of Human Behavior · Park et al., 2023. Memory streams scored by recency, importance and relevance: the scoring idea behind agent memory retrieval.
- Article Effective context engineering for AI agents · Anthropic. Compaction, structured notes and sub-agents as ways to keep long runs inside the window.
- Docs Memory · LangGraph docs. Short-term memory per thread and long-term memory in a store, with code.
GitHub repositories
- mem0ai/mem0: How memories are extracted, updated and searched; read the update logic for conflicting facts.
- langchain-ai/langmem: Memory tools for LangGraph agents: hot-path writes versus background memory managers.
- letta-ai/letta: Agents with self-editing memory blocks, from the MemGPT research.
- pgvector/pgvector: Filtered vector search for scoped memories and runbooks.
Checkpoint quiz
Interview questions
- How do you manage context in an agent that runs for 50 steps?
- Design long-term memory for an ops assistant. What do you store, and how do you retrieve it?
- Your agent forgot a key finding after compaction. How do you debug and fix it?
- When would you use RAG inside an agent, and how do you evaluate it?
- How do you handle privacy and deletion for agent memory?
Ask the professor
Sign in to ask questions about this module.
Discussion
Community discussion appears here once giscus is configured (see README).