Overview

6 Adding memory to your agent

Memory turns an agent from a stateless responder into something that can preserve progress, recover from interruptions, and adapt over time. This chapter frames memory as a practical engineering problem: without it, complex runs can overflow the model’s context window, conversations break across separate calls, and useful facts disappear between sessions. To solve that, the chapter separates memory into short-term, session-bound context and long-term, cross-session knowledge, then connects both to broader context-engineering ideas such as reducing, writing, and retrieving information at the right time.

For short-term memory, the chapter focuses on managing context during execution with a hierarchical strategy. It starts with simple sliding windows, then moves to token counting so decisions are based on real prompt size rather than message count. When context still grows too large, compaction replaces bulky tool call inputs and outputs with lightweight references, and summarization compresses older reasoning into a compact synthetic record. These techniques are applied through callbacks before LLM calls, with the general rule being: do nothing if context is small, compact first if possible, and summarize only as a last resort.

The second half extends memory across sessions by introducing a Session and SessionManager for persistent conversation continuity, plus an asynchronous human-in-the-loop flow that can pause on sensitive tool calls and resume later with stored state. Finally, the chapter builds long-term memory using structured extraction and vector search: important execution histories are distilled into typed records, checked for duplicates, stored in ChromaDB, and later retrieved to inform new runs. Together, these patterns let the agent remember recent work, continue interrupted conversations, safely request approval, and accumulate reusable knowledge over time.

Book structure overview: Chapter 6 in focus.
Without Session (left), each run() creates a new ExecutionContext that's discarded after completion. With Session (right), multiple run() calls share the same Session, maintaining conversation continuity.
Long-term memory enables information sharing across sessions. Each run() creates an ExecutionContext, multiple runs form a Session, and important information from sessions is extracted and stored for future use.
Context management strategy decision flow.
Relationship between session and ExecutionContext.
Internal features vs external extensions in agent architecture.
Overall flow of the pause and resume mechanism.
The role of MemoryManager.

Summary

  • Memory transforms an agent from a stateless tool into an intelligent assistant that learns and adapts across interactions.
  • The three usage patterns address different challenges: Pattern 1 (One-off Execution) manages context within a single run, Pattern 2 (Continuous Execution) maintains conversation across multiple runs, and Pattern 3 (Long-term Memory) preserves knowledge across sessions.
  • Context management strategies follow a hierarchical approach: measure tokens first, apply Compaction for tool results, and use Summarization as a last resort. The key principle is separating storage from presentation—ExecutionContext remains immutable while LlmRequest is optimized for each call.
  • Session and SessionManager enable multi-turn conversations by persisting events and state across run() calls. The same architecture supports asynchronous Human-in-the-Loop workflows, where execution pauses for user approval and resumes when confirmation arrives.
  • Long-term memory combines Write and Retrieval strategies: structured information is extracted from execution history, checked for duplicates, stored in a vector database, and retrieved when relevant to new tasks.
  • Memory retrieval can be implemented as an explicit tool the agent calls on demand, or as automatic injection via process_llm_request() that adds relevant context before every LLM call.

FAQ

What is the role of memory in an LLM agent?Memory lets an agent remember past events within a task, continue conversations across turns and sessions, and retain useful knowledge over time. Without it, every interaction starts from scratch, which forces users to repeat context and prevents the agent from improving.
What are the three memory-related challenges this chapter addresses?The chapter focuses on three challenges: context explosion during a single execution, lack of conversation continuity across multiple run() calls, and lack of persistent knowledge across different sessions. Each challenge maps to a different memory pattern and solution.
What is the difference between short-term memory and long-term memory?Short-term memory stores everything that happens within one session, such as conversation history, tool calls, and intermediate reasoning. Long-term memory stores selected information that survives after the session ends and can be retrieved in future sessions.
Why is separating storage from presentation important for context management?It keeps ExecutionContext.events as the immutable ground truth while allowing LlmRequest.contents to be optimized for the LLM. This makes debugging easier and preserves original tool outputs and reasoning for later reference.
How does the sliding window strategy help control context growth?Sliding window keeps the user’s original question and only the most recent N messages after it. This reduces context size in a simple, predictable way, though it can still lose important older details if the window is too small.
Why is token counting better than counting messages for context optimization?Message count does not reflect actual model usage because one message may contain very few tokens or many thousands. Token counting gives a much more accurate measure of how close the request is to the model’s context limit.
What is compaction in agent memory management?Compaction replaces already-processed large content with lightweight references. For example, file contents or search results can be removed from context and replaced with a short note saying the data was processed and can be re-fetched if needed.
How does summarization differ from compaction?Compaction is deterministic and reversible because the original data can often be retrieved again from the tool. Summarization is semantic and irreversible because an LLM condenses the history into a shorter form, which means the original reasoning is lost.
What is the purpose of Session and SessionManager?They preserve conversation continuity across multiple run() calls by storing session events and state externally. Using the same session_id lets the agent continue a conversation or resume paused work later.
How does long-term memory work across sessions?At the end of a session, important information is extracted and stored in external vector memory. In a new session, the agent retrieves relevant memories through vector search so it can recall facts, past approaches, or previous outcomes even after the original session has ended.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Build an AI Agent (From Scratch) ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Build an AI Agent (From Scratch) ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Build an AI Agent (From Scratch) ebook for free