Chapter 9: Short-Term Memory: Session State and Conversation History

Learning Objectives

Part 1 — What Short-Term Memory Holds

Pre-Reading Check — Part 1

Why does an LLM need conversation history appended to resolve a phrase like "make that one blue instead"?

Because the model is inherently stateless and retains nothing from prior turns on its own Because color changes require a specialized fine-tuned model Because the model's weights are updated after each user message Because pronouns are stored permanently in the model's parameters

The chapter compares working memory to a chef's mise en place. What does that analogy emphasize?

That intermediate results are held within arm's reach for the current task and cleared when the shift ends That all session data is permanent, like a stocked pantry That conversation history should be discarded before every turn That working memory is slower to access than long-term memory

What is the defining property that makes short-term memory "short-term"?

It can only hold a fixed number of tokens at any moment It resets when the conversation ends, so anything worth keeping must be promoted out first It is always stored on the same machine as the model It is encrypted and therefore unreadable after the session

Key Points

Short-term memory is not one undifferentiated blob of text; it is a small set of distinct things, each with its own lifetime and purpose. The most obvious content is the conversation history — the ordered record of what the user said and what the assistant replied. Because the LLM is stateless, this transcript is the only reason the assistant can resolve "the same time tomorrow" or "the second one." In production, history is not merely logged; it is reconstituted and prepended to the next model call.

Short-term memory is also working memory: the immediate context needed right now to complete the current task. When an agent processes "Find flights to Paris, then recommend hotels near the Louvre," the flight results become working state that the hotel step must consult. This is more than a transcript — it is a scratchpad of intermediate results, open tasks, and partial plans.

Ephemeral vs. Durable Session Data

TypeExamplesTreatment
EphemeralCurrent results page, half-composed draft, intermediate reasoning for the current stepExpire quietly when the session ends
Durable-within-sessionConversation history, confirmed intermediate resultsSurvive across turns and reconnects, but still belong to this session

The defining property of all short-term memory is impermanence: working memory resets when the conversation ends, making it insufficient for learning from past sessions on its own. That reset is a feature — it keeps sessions bounded — but it means anything worth keeping forever must be deliberately promoted out before the reset. Production systems layer memory types: thread-scoped short-term memory for the current session, and cross-session long-term memory for persistent knowledge.

[Animation slot: three labeled bins — "Turn-by-turn history," "Working state / open tasks," "Ephemeral scratch" — with items flowing in during a session, then the ephemeral bin emptying at session end while durable items get flagged for promotion.]
Post-Reading Check — Part 1

Why does an LLM need conversation history appended to resolve a phrase like "make that one blue instead"?

Because the model is inherently stateless and retains nothing from prior turns on its own Because color changes require a specialized fine-tuned model Because the model's weights are updated after each user message Because pronouns are stored permanently in the model's parameters

The chapter compares working memory to a chef's mise en place. What does that analogy emphasize?

That intermediate results are held within arm's reach for the current task and cleared when the shift ends That all session data is permanent, like a stocked pantry That conversation history should be discarded before every turn That working memory is slower to access than long-term memory

What is the defining property that makes short-term memory "short-term"?

It can only hold a fixed number of tokens at any moment It resets when the conversation ends, so anything worth keeping must be promoted out first It is always stored on the same machine as the model It is encrypted and therefore unreadable after the session

Part 2 — Storing Session State

Pre-Reading Check — Part 2

Why is a pure in-memory (process RAM) session store considered fine for development but fatal for production?

Its data is lost when the program stops, so a routine deploy or crash would wipe every active conversation It cannot store more than one conversation at a time It requires a vector database that developers rarely install It always exposes user data to other tenants

What does a TTL (time-to-live) operationalize for a session store?

The maximum number of tokens allowed in the context window The "resets when the conversation ends" property, by letting abandoned sessions age out automatically The encryption strength applied to stored messages The number of tool calls an agent may make per turn

On reconnect, how does the checkpointer pattern let an assistant "pick up where it left off"?

It re-runs every prior turn from scratch to regenerate the state It loads the most recent checkpoint for that thread ID and rebuilds the state from the saved snapshot It asks the user to re-summarize the conversation so far It queries the LLM's weights for the stored transcript

Key Points

If short-term memory resets at session end but must survive within it, it needs a home outside the stateless model: the session store. The first decision is where state physically lives, a trade-off along a durability spectrum.

BackendWhere state livesDurabilityBest for
InMemorySaverProcess RAMLost when the program stopsDevelopment, prototyping
SqliteSaverLocal fileSurvives restarts on one machineLocal apps, single-node tools
PostgresSaverProduction databaseSurvives restarts and long periodsProduction, multi-node
Redis / CouchbaseFast external storeConfigurable persistence + TTLHigh-throughput sessions

Latency compounds across an agent's reasoning steps: if a query fans out into eight tool calls and each fetches and updates session state, a slow store multiplies that slowness eight times over. (A real gotcha: langgraph dev can silently ignore checkpointer config and force in-memory storage — always verify the durability you configured is the durability you get.)

Session Keys and Expiry

A session store is key-value, so every session needs a key encoding who and which conversation — e.g., Redis hashes keyed mysession:UserName:entry_id, or a composite thread_id such as customer_{customer_id}_session_{session_id}. The second essential property is expiry via a TTL. Think of the TTL as the parking meter of memory: while it runs, the space stays reserved; when it expires, the space is freed. Anything you want to keep, you take with you before the meter runs out.

Reconstructing Context on Reconnect

The dominant production pattern is checkpointers plus thread IDs. The checkpointer saves a snapshot of state at every super-step. On reconnect, the system loads the most recent checkpoint for that thread_id and reconstructs the full state — including accumulated message history — so the agent picks up where it left off. Crucially, state is rebuilt from the last checkpoint rather than replayed from scratch.

sequenceDiagram participant User participant App as "Assistant App" participant Store as "Session Store (Checkpointer)" participant LLM User->>App: Turn 1 message App->>LLM: Prompt with history LLM-->>App: Response App->>Store: "Write checkpoint (thread_id)" Note over User,App: Connection drops mid-conversation User->>App: Reconnect and resume App->>Store: "Load latest checkpoint for thread_id" Store-->>App: "Restored state + message history" User->>App: "book the second hotel" App->>LLM: "Prompt with rebuilt history" LLM-->>App: Resolves reference correctly App-->>User: Continues where it left off

Worked example. Maria books a Boston→Paris trip: the agent writes a checkpoint for customer_maria_session_0708 after finding flights, another after finding hotels. Her train enters a tunnel and the connection drops. Ten minutes later she reopens the app, the system loads the latest checkpoint, rebuilds the full flight-and-hotel context, and Maria simply types "book the second hotel." Without datastore-backed state, the tunnel would have cost her the whole booking.

[Animation slot: durability-spectrum slider from "RAM (volatile)" to "Redis / Postgres (durable)"; then a reconnect timeline showing checkpoints being written per turn, a dropped connection, and the latest checkpoint being loaded to restore state.]
Post-Reading Check — Part 2

Why is a pure in-memory (process RAM) session store considered fine for development but fatal for production?

Its data is lost when the program stops, so a routine deploy or crash would wipe every active conversation It cannot store more than one conversation at a time It requires a vector database that developers rarely install It always exposes user data to other tenants

What does a TTL (time-to-live) operationalize for a session store?

The maximum number of tokens allowed in the context window The "resets when the conversation ends" property, by letting abandoned sessions age out automatically The encryption strength applied to stored messages The number of tool calls an agent may make per turn

On reconnect, how does the checkpointer pattern let an assistant "pick up where it left off"?

It re-runs every prior turn from scratch to regenerate the state It loads the most recent checkpoint for that thread ID and rebuilds the state from the saved snapshot It asks the user to re-summarize the conversation so far It queries the LLM's weights for the stored transcript

Part 3 — Session Memory and the Window

Pre-Reading Check — Part 3

What is the core distinction between the session store and the context window?

The store may hold the complete history, while the window receives only a curated slice of it The window holds everything permanently, while the store is discarded each turn They are two names for the same buffer The store is limited to the model's token limit, while the window is unlimited

What is the blunt failure mode of a pure sliding-window (last-N) buffer?

Once a turn slides out of the last N, its information is gone from the prompt even if the user refers back to it later It stores turns in random order, corrupting references It can never keep any turn verbatim It requires a vector store to function at all

How does a SemanticSessionManager differ from a fixed last-N buffer?

It uses vector similarity to return only the turns most relevant to the current query, not just the most recent ones It stores every turn verbatim forever with no token cost It deletes older turns instead of retrieving them It moves session state into the model's weights

Key Points

This section connects directly to Chapter 3. Session memory and context management are two sides of one coin: session memory stores the conversation, but the context window constrains how much of it the model can consume on any turn. Because LLMs have token limits, the memory layer stores the last N interactions and "slides" that window into the prompt. The distinction to internalize: the store may hold the complete history (subject to TTL), while the window receives only a curated slice.

A pure sliding window has a blunt failure mode: once a turn slides out of the last N, its information is gone from the prompt, even if the user refers back to it twenty turns later. The remedy is summarization. The practical recipe is a hybrid:

Three Presentation Strategies

StrategyWhat it presentsStrengthWeakness
Verbatim buffer (last N)Most recent N turns, word-for-wordPerfect fidelity for recent contextOld-but-relevant turns lost entirely
Running summaryCompressed digest of older turns + recent verbatimLarge token savings; long horizonLossy; can drop specifics
Semantic selectionTurns most similar to the current querySurfaces relevant old turns; token-efficientDepends on embedding quality; adds a retrieval step

Whichever strategy you choose, the obligation is the same: because each request is independent, the system carries state itself. On every turn the pipeline (1) loads session state by key, (2) assembles the window — verbatim recent turns plus a summary or semantically selected turns plus working state, (3) calls the model, and (4) writes updated state back as a new checkpoint. The window is a keyhole; the session store is the room behind the door.

[Animation slot: a growing transcript in the "store" panel; a fixed-size "window" keyhole showing recent turns verbatim while older turns collapse into a one-line running summary; toggle to "semantic selection" mode that highlights and pulls forward the turn most similar to the current query.]
Post-Reading Check — Part 3

What is the core distinction between the session store and the context window?

The store may hold the complete history, while the window receives only a curated slice of it The window holds everything permanently, while the store is discarded each turn They are two names for the same buffer The store is limited to the model's token limit, while the window is unlimited

What is the blunt failure mode of a pure sliding-window (last-N) buffer?

Once a turn slides out of the last N, its information is gone from the prompt even if the user refers back to it later It stores turns in random order, corrupting references It can never keep any turn verbatim It requires a vector store to function at all

How does a SemanticSessionManager differ from a fixed last-N buffer?

It uses vector similarity to return only the turns most relevant to the current query, not just the most recent ones It stores every turn verbatim forever with no token cost It deletes older turns instead of retrieving them It moves session state into the model's weights

Part 4 — Boundaries and Handoff

Pre-Reading Check — Part 4

In the checkpointer model, how is the session vs. long-term boundary architecturally expressed?

Checkpointers persist within-thread (session) state; a separate cross-thread Store holds long-term memory Both session and long-term memory share one checkpointer with no distinction Long-term memory lives in the model weights; session memory lives in the prompt Session memory is stored across threads while long-term memory is per-thread

The chapter contrasts Mem0 and Letta/MemGPT along the axis of "predictability vs. intelligence." Which statement fits that contrast?

Mem0 extracts passively outside the reasoning loop (predictable, cheap); Letta self-edits memory during reasoning (intelligent, consumes inference tokens) Mem0 self-edits during reasoning while Letta extracts passively afterward Both extract memories identically; only the storage backend differs Letta is predictable and cheap; Mem0 is intelligent and expensive

Why does a well-designed session teardown "promote before you purge"?

Because working memory resets at session end, so the last chance to save durable facts is before teardown Because promotion is only legal after the TTL has already expired Because purging must happen first to free space for promotion Because long-term memory is wiped whenever a session closes

Key Points

In the checkpointer model, checkpointers persist within-thread (session) state; for data shared across threads/sessions — long-term memory — the system provides a separate mechanism: application-defined key-value Stores. This split maps directly onto short-term versus long-term memory.

DimensionShort-Term (Session)Long-Term
ScopeA single conversation / threadAcross all of a user's sessions
LifetimeResets when session ends (TTL)Survives restarts; weeks-to-months
Persistence mechanismCheckpointer (within-thread)Store (cross-thread)
ContentsTurn-by-turn history, working statePreferences, stable facts, past episodes
Failure if lostThis conversation resetsThe assistant "forgets" the user entirely

Promoting Facts to Long-Term Memory

Memory promotion moves durable, reusable facts out of ephemeral working memory into persistent long-term memory. It happens two ways in time — at session end (turns become "observations" — factual statements with references back to the dialog turns that produced them) and continuously when a salient fact surfaces. Pathways are automatic (extract-and-batch, e.g. ENABLE_DISCRETE_MEMORY_EXTRACTION=true) or manual (direct API / LLM tool). Extracted memory falls into semantic, episodic, and message types. Promotion must not create duplicates: hash-based plus semantic-similarity deduplication, with related memories merged by an LLM.

flowchart TD A["Working memory (session)"] --> B{"Durable, reusable fact?"} B -->|"No: transient detail"| C["Keep in session; expire with TTL"] B -->|"Yes"| D{"Promotion pathway"} D -->|Automatic| E["Extract and batch-process from working memory"] D -->|Manual| F["Create directly via API or LLM tool"] E --> G{"Duplicate check"} F --> G G -->|"Identical or similar exists"| H["Merge and consolidate via LLM"] G -->|New| I["Write to long-term store"] H --> I I --> J["Persistent long-term memory"]

Two philosophies of promotion. Mem0 extracts passively: add() triggers an extraction pipeline that reconciles facts with a vector store via add/update/delete/skip — running outside the agent's reasoning loop, so inference costs stay low and identical inputs yield identical memories (predictable). Letta / MemGPT agents self-edit memory during reasoning, managing three OS-inspired tiers: Core (in-context, like RAM), Recall (searchable history, like a disk cache), and Archival (cold storage via tool calls) — intelligent, but quality depends on the model and it consumes inference tokens. The rule of thumb: promote stable preferences, identity facts, and recurring goals (deduped); keep transient details like "what page am I on" in working memory to expire with the TTL.

Session Teardown

A well-designed teardown does two jobs in sequence: (1) promote before you purge — because working memory resets at session end, the last chance to save durable facts is before teardown; (2) then let session state expire via TTL. Even within a long session, checkpoints accumulate and can raise latency, so implement retention policies or periodic pruning. Like a hotel front desk at checkout: they don't shred your loyalty profile — they update it (you liked the top floor, you order decaf) and then clear the room. Promotion updates the profile; teardown clears the room.

stateDiagram-v2 [*] --> Created: "First message / new thread_id" Created --> Active: "Checkpoint written" Active --> Active: "Turn taken; state updated" Active --> Idle: "User goes quiet" Idle --> Active: "Reconnect; load latest checkpoint" Idle --> Expiring: "TTL elapses" Active --> Expiring: "Session closed" Expiring --> Teardown: "Promote durable facts first" Teardown --> [*]: "Purge transient state"
[Animation slot: a fact traveling from the session box across the short-term/long-term boundary — passing through a dedup gate that merges a near-duplicate — landing in the long-term store; meanwhile the session box's transient items fade out as the TTL meter reaches zero.]
Post-Reading Check — Part 4

In the checkpointer model, how is the session vs. long-term boundary architecturally expressed?

Checkpointers persist within-thread (session) state; a separate cross-thread Store holds long-term memory Both session and long-term memory share one checkpointer with no distinction Long-term memory lives in the model weights; session memory lives in the prompt Session memory is stored across threads while long-term memory is per-thread

The chapter contrasts Mem0 and Letta/MemGPT along the axis of "predictability vs. intelligence." Which statement fits that contrast?

Mem0 extracts passively outside the reasoning loop (predictable, cheap); Letta self-edits memory during reasoning (intelligent, consumes inference tokens) Mem0 self-edits during reasoning while Letta extracts passively afterward Both extract memories identically; only the storage backend differs Letta is predictable and cheap; Mem0 is intelligent and expensive

Why does a well-designed session teardown "promote before you purge"?

Because working memory resets at session end, so the last chance to save durable facts is before teardown Because promotion is only legal after the TTL has already expired Because purging must happen first to free space for promotion Because long-term memory is wiped whenever a session closes

Your Progress

Answer Explanations