Skip to content

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).

System + toolsfixedSummarycompacted historyRecent stepslast N in fullRetrievedrunbooks, memoriesTaskcurrent goalOlder stepscompactedBig outputsfiles + referencesLong-term memoryper user / serviceRunbookspgvectorWhat goes into each model callStored outside the windowsummariseretrieve
Treat the context window as a budget. Decide what stays verbatim, what is summarised and what is fetched on demand.

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.

Agent memory and context compactionEvery step resends the whole context. Big tool outputs pile up fast. The final answer needs the four facts marked ★.
★★★★

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
  1. 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?
  2. 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?
  3. Summarise older steps without pinned facts, then with them. What must a compaction prompt say so the summary keeps what matters?
  4. 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.

Common misconception: “More memory makes a smarter agent.” Stale or wrong memories are worse than none: the agent trusts them. Store less, scope it, and let it expire.

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.

In production: Log the exact context sent at each step (or a hash and a sample). When an agent ‘forgets’, the trace shows whether the fact was never stored, compacted away or simply ignored.

Hands-on: coding window

The coding window and the full VS Code lab are available after you sign in.

Sign in to code

Labs

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

Further reading

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

1. A 12,000-token log dump is returned by a tool. Best handling?
2. What is the main risk of compaction?
3. Two memories say the DB pool is 50 and 80. Best design?
4. Why scope memories per service or user?
5. How do you know your memory policy works?

Interview questions

  1. How do you manage context in an agent that runs for 50 steps?
  2. Design long-term memory for an ops assistant. What do you store, and how do you retrieve it?
  3. Your agent forgot a key finding after compaction. How do you debug and fix it?
  4. When would you use RAG inside an agent, and how do you evaluate it?
  5. 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).