liveBook · Manning

Chapter 6: Adding memory to your agent

What you will learn in chapter 6 of Build an AI Agent (From Scratch)

The chapter introduces why agents need memory and defines the context-growth problem that memory management must address.

After this chapter you will be able to

What it builds on

Section by section

Introduction

The chapter introduces why agents need memory and defines the context-growth problem that memory management must address.

Key terms: memory, stateless tool, context explosion, context window

6.1 The anatomy of agent memory

The section introduces why memory matters to an agent, while previewing the memory distinctions explained later.

Key terms: memory, previous conversations, experiences

6.1.1 Limitations of the current memory architecture

This section explains why the agent’s raw ExecutionContext fails to manage information during long tasks and across sessions.

Key terms: ExecutionContext, context, window limit, memory management

6.1.2 Three challenges of the current memory architecture

This section defines sessions and short- and long-term memory, then explains three limits of the current agent architecture: growing context, broken conversation continuity, and knowledge that does not persist across sessions.

Key terms: session, short-term memory, long-term memory, ExecutionContext.events, context explosion, tool calls, compress context, conversation continuity, session management, session_id

6.1.3 Context engineering and memory

The section connects three memory patterns to context-engineering strategies and distinguishes managing context within a run, across a session, and after a session.

Key terms: in-run context management, continuous execution, long-term memory, run(), session, reduce, write, retrieval, sliding window, compaction

6.2 Managing context during execution

6.2.1 Separating storage from presentation

This section explains how to preserve an agent’s complete execution history while tailoring each LLM request through callbacks.

Key terms: ExecutionContext.events, LlmRequest.contents, ground truth, computed projection, before_llm_callback, ExecutionContext, LlmRequest, LlmResponse, create_optimizer_callback, closure pattern

6.2.2 Sliding-window strategy

This section explains how a sliding window limits an agent’s context by preserving the original question and retaining only recent subsequent items, then shows why message-count limits are imperfect.

Key terms: sliding-window strategy, window_size, original question, context-explosion problem, message count, token counts

6.2.3 Token counting

This section explains how to measure an agent’s context in tokens and why to keep it focused even when it fits within the model’s context window.

Key terms: token count, message count, context management, tiktoken, LlmRequest, build_messages, tool definitions, context bloat, context window, lost in the middle

6.2.4 Compaction strategy

This section explains how compaction keeps an agent’s context lean by replacing processed tool data with references, and when its costs justify using it.

Key terms: compaction, scope by default, lightweight references, ToolCall, ToolResult, write operations, read operations, TOOLCALL_COMPACTION_RULES, TOOLRESULT_COMPACTION_RULES, LLM tokens

6.2.5 Summarization strategy

Explains how to summarize older parts of an agent’s conversation when compaction is insufficient, while preserving the task and recent messages.

Key terms: summarization, intermediate process, user’s original question, keep_recent, summary message, context.state, last summarization position, compaction, deterministic, semantic

6.2.6 Hierarchical context management

This section presents a cost-aware order for managing context size and shows how to run those checks through an agent callback.

Key terms: token count, threshold, compaction, summarization, prompt-caching benefits, ContextOptimizer, __call__, before_llm_callback

6.3 Continuous execution: Session and state management

This section explains why sessions are needed to preserve conversations across agent runs and how saved execution state allows tool approval without blocking the agent.

Key terms: ExecutionContext, run(), Session, session_id, intermediate execution state, HITL, input(), tool approval

6.3.1 The Session class

This section defines a Session as persistent storage across agent runs, distinguishes it from a single-run ExecutionContext, and explains its fields.

Key terms: session, ExecutionContext, run(), conversation history, execution state, Session class, session_id, user_id, events, state

6.3.2 Managing sessions with SessionManager

This section separates session data from session management, defines a shared asynchronous manager interface, and shows how an in-memory implementation behaves.

Key terms: Session, SessionManager, session_id, get_or_create, Abstract class, get, create, async, asynchronous interface, InMemorySessionManager

6.3.3 Integrating sessions into the agent

This section integrates sessions into the agent so conversation history and runtime state can carry across executions.

Key terms: ExecutionContext, Session, events, state, properties, backward compatibility, SessionManager, InMemorySessionManager, session_id, get_or_create()

6.3.4 Basic example: Multiturn conversation

Shows how reusing a session ID lets an agent retain conversational context across run() calls, while omitting or changing it keeps calls independent.

Key terms: session_id, Session, session.events, ExecutionContext, context.events, one-off tasks, GAIA benchmark problems

6.3.5 Data structures for tool confirmation

This section defines the data structures and session-state serialization needed to represent tool calls awaiting human approval.

Key terms: PendingToolCall, ToolCall, confirmation_message, ToolConfirmation, tool_call_id, approved, AgentResult, status, complete, pending_confirmation

6.3.6 Extending tools for confirmation

This subsection shows how tools declare whether they need user approval and how they produce an approval message before execution.

Key terms: BaseTool, requires_confirmation, @tool decorator, confirmation_message_template, get_confirmation_message(), PendingToolCall, {name}, {arguments}, {arguments[key]}

6.3.7 Implementing pause and resume in the agent

This section implements human approval of tool calls by pausing the agent before protected tools run, then resuming with the user's decisions visible to the LLM.

Key terms: _prepare_llm_request(), before_llm_callback, ToolResults, act(), requires_confirmation, PendingToolCall, context.state, ToolResult, run(), step()

6.3.8 Complete example: HITL workflow

This section demonstrates a complete human-in-the-loop file-deletion workflow, from pausing for approval to resuming the same session.

Key terms: HITL workflow, requires_confirmation, pending_confirmation, pending_tool_calls, ToolConfirmation, session_id

6.4 Long-term memory: Accumulating knowledge across sessions

This section explains how long-term memory carries useful information across sessions by storing it externally and retrieving it for later context.

Key terms: Session, SessionManager, session_id, long-term memory, write (storage), retrieval (search)

6.4.1 The structure of long-term memory

This section distinguishes session continuity from long-term memory and explains how selected information is stored, retrieved, and managed across sessions.

Key terms: SessionManager, MemoryManager, session_id, horizontal continuity, vertical continuity, storage (Write), retrieval, vector embeddings, information extraction, ADD

6.4.2 Information extraction: Structured output

This section shows how to extract structured problem-solving memories from an agent’s execution history, prepare them for retrieval, and check for duplicates before storage.

Key terms: structured memory, GAIA problem-solving records, Pydantic, TaskMemory, task_summary, approach, final_answer, is_correct, extraction prompt, execution history

6.4.3 Building a vector store with ChromaDB

Introduces ChromaDB collections and shows how they store and retrieve documents through automatic embedding and similarity search.

Key terms: collection, document text, embedding vectors, metadata, chromadb.Client(), get_or_create_collection(), embedding_function, add(), query_texts, query()

6.4.4 Implementing TaskMemoryManager

This section implements a TaskMemoryManager that turns agent execution history into structured GAIA task memories, avoids duplicates, stores and searches them in ChromaDB, and makes the manager available to agent tools.

Key terms: _format_execution_history(), _extract_memory(), response_format=TaskMemory, LlmClient, _is_duplicate, DuplicateCheckResult, result.decision, SKIP, save(), ChromaDB

6.4.5 Retrieving memories

This section shows how an agent can retrieve stored memories on demand or inject them automatically into LLM requests.

Key terms: MemoryTool, execute(), tool-based retrieval, process_llm_request(), automatic injection, BaseTool, tool_definition, _prepare_llm_request()

6.5 Summary

This chapter summary connects three uses of agent memory with the context, session, and long-term-memory mechanisms that support them.

Where this is used later

Concepts explained in this chapter

← Chapter 5: Building knowledge bases with RAG Chapter 7: Planning and reflection for complex tasks →

These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.