17  Memory & Long Conversations

A doc-bot that answers one question at a time is a search box. The moment a user asks a second question — “what are the pitfalls?” — the bot has to know what “the” refers to, and the moment the same user comes back next week it should remember how they like their answers. Two user scenarios hide behind the word “memory,” and they need different tools. In the first, a user returns to a conversation and expects the bot to still be in it. In the second, a user opens a new conversation and expects the bot to remember that they write Python and never Java. The checkpointer from Chapter 8 already covers the first:

There are two different memories. A checkpoint remembers this conversation — the full state, filed under a thread_id. A Store remembers this user across conversations — distilled facts, filed under a namespace, readable from any thread. Conversation memory is the checkpoint you already have; long-term memory is a Store you write to on purpose.

17.1 Connecting a model

Same connection as every model-backed Part II chapter: a model served locally (Chapter 12) behind an OpenAI-compatible endpoint that ChatOpenAI speaks.

from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    base_url="http://localhost:1234/v1",  # your local server, not the OpenAI cloud
    api_key="lm-studio",                   # the local server ignores the key
    model="qwen/qwen3.8-27b",              # a capable open model that follows instructions
    temperature=0,                         # 0 = as reproducible as a real model gets
    reasoning_effort="none",               # Qwen3.8 thinks by default; off for now
)

17.2 What we’re building

The graph is almost nothing this time — a single chat node that answers from the conversation so far. The memory is not in the diagram; it is the checkpointer wrapped around the graph, as in Chapter 8, storing the history after each turn.

%%{init: {'securityLevel': 'loose', 'flowchart': {'diagramPadding': 24}, 'themeCSS': 'foreignObject{overflow:visible}span.bot{display:flex;justify-content:flex-start;align-items:flex-start;width:100%;height:0;overflow:visible;line-height:0}span.bot img{display:block!important;width:18px!important;height:18px!important;padding:2px;background:#fff;border-radius:50%;box-shadow:0 0 0 1px #999}span.bot.r img{margin:0;transform:translate(-24px,-24px)}span.bot.d{justify-content:center}span.bot.d img{margin-top:-50%;transform:translateY(-24px)}'}}%%
flowchart LR
    START(["START"]) --> chat("<span class='bot r'><img src='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiMzMzMiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48cGF0aCBkPSJNMTIgOFY0SDgiLz48cmVjdCB3aWR0aD0iMTYiIGhlaWdodD0iMTIiIHg9IjQiIHk9IjgiIHJ4PSIyIi8+PHBhdGggZD0iTTIgMTRoMiIvPjxwYXRoIGQ9Ik0yMCAxNGgyIi8+PHBhdGggZD0iTTE1IDEzdjIiLz48cGF0aCBkPSJNOSAxM3YyIi8+PC9zdmc+'/></span>chat") --> END(["END"])

We build up in three moves. First, a bare chat node whose only memory is the checkpointer — that alone is a full multi-turn conversation. Then we handle a conversation that grows too long by summarizing its older turns. Finally we add a Store beside the checkpointer for facts that cross conversations.

17.3 A conversation is a thread

Ask the doc-bot “What are the pitfalls?” on a thread that has never heard of Kafka, and this is what comes back:

  [conv-2] user: What are the pitfalls?
  [conv-2] bot:  Pitfalls refer to potential problems or hazards that could lead to failure or difficulty in a given situation. They can include ...

(The reply is shown by excerpt: first line, trimmed — Chapter 12. It is a different run from the transcript under Running it, which is why conv-2 answers the same question two ways in this chapter.)

It defined the word. On another thread, seconds earlier, the same question got a list about batch sizes and offsets, because that thread had just been asked about Kafka batch consumers. The model did not change between the two answers; what changed is which history it was shown — and “which history” is exactly what a thread is.

The state is a single field, the running list of messages, and the one piece of wiring that matters is its reducer.

from typing import Annotated, TypedDict
from langgraph.graph.message import add_messages


class ChatState(TypedDict):
    # the built-in message reducer: appends (merging by id) instead of overwriting
    messages: Annotated[list, add_messages]

Without a reducer, a node that returns {"messages": [...]} would replace the list and every turn would start blank. add_messages (the id-aware append reducer from Section 14.5) is what accumulates the history.

The node hands the model the whole history and returns only the new reply. One more message goes along, and it is the first SystemMessage in the book: the application’s standing instructions to the assistant, which have no place in a conversation between a person and a model but every place in what the model is shown. Watch where it is added — at call time, in front of the history, in the node’s local variable — and where it is not: the node returns only the reply, so the instructions never land in state["messages"] and are never checkpointed. What the model is sent on a turn can be more than what the thread keeps. That distinction is this chapter’s, and it comes up again the moment there is something to trim.

from langchain_core.messages import HumanMessage, SystemMessage


def chat_node(state: ChatState) -> dict:
    system = SystemMessage(
        content="You are a documentation assistant. Answer concisely, "
        "in no more than three sentences."
    )
    reply = llm.invoke([system] + state["messages"])
    return {"messages": [reply]}

Now the graph. It is the one-node shape from the overview, compiled with a checkpointer — the single line that turns a stateless call into a continuous conversation (Chapter 8). The usual InMemorySaver caveat (Chapter 8) extends to the InMemoryStore later in this chapter: both remember only within one running process.

from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import StateGraph, START, END

builder = StateGraph(ChatState)
builder.add_node("chat", chat_node)
builder.add_edge(START, "chat")
builder.add_edge("chat", END)

graph = builder.compile(checkpointer=InMemorySaver())

%%{init: {'securityLevel': 'loose', 'flowchart': {'diagramPadding': 24}, 'themeCSS': 'foreignObject{overflow:visible}span.bot{display:flex;justify-content:flex-start;align-items:flex-start;width:100%;height:0;overflow:visible;line-height:0}span.bot img{display:block!important;width:18px!important;height:18px!important;padding:2px;background:#fff;border-radius:50%;box-shadow:0 0 0 1px #999}span.bot.r img{margin:0;transform:translate(-24px,-24px)}span.bot.d{justify-content:center}span.bot.d img{margin-top:-50%;transform:translateY(-24px)}'}}%%
flowchart TD
    START(["START"]) --> chat("<span class='bot r'><img src='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiMzMzMiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48cGF0aCBkPSJNMTIgOFY0SDgiLz48cmVjdCB3aWR0aD0iMTYiIGhlaWdodD0iMTIiIHg9IjQiIHk9IjgiIHJ4PSIyIi8+PHBhdGggZD0iTTIgMTRoMiIvPjxwYXRoIGQ9Ik0yMCAxNGgyIi8+PHBhdGggZD0iTTE1IDEzdjIiLz48cGF0aCBkPSJNOSAxM3YyIi8+PC9zdmc+'/></span>chat") --> END(["END"])

The last piece is how we send a turn. Each turn passes only the new user message. The checkpointer supplies the accumulated history and add_messages appends to it, so we never re-send the past ourselves:

def send(thread_id: str, text: str) -> None:
    config = {"configurable": {"thread_id": thread_id}}
    result = graph.invoke({"messages": [HumanMessage(content=text)]}, config=config)
    print(f"  [{thread_id}] user: {text}")
    print(f"  [{thread_id}] bot:  {excerpt(result['messages'][-1].content)}")  # first line, trimmed

(the bot: lines are excerpt again — the trace only needs to show what the bot said, and whether it remembered.)

17.4 Running it

Two conversations on two thread_ids. On conv-1 we ask a question, then a follow-up that only makes sense in context (“What are the pitfalls?” — of what?), then a question that reaches all the way back. On conv-2, a brand-new thread, we ask that same context-dependent follow-up cold.

########## multi-turn chat (checkpointer = conversation memory) ##########

===== conversation conv-1 =====
  [conv-1] user: How do I configure Kafka batch consumers in Spring Boot?
  [conv-1] bot:  To configure batch consumers in Spring Boot, set the `spring.kafka.listener.batch-listener` property to `true` in your ...

  [conv-1] user: What are the pitfalls?
  [conv-1] bot:  The primary pitfall is that a failure in any single record within a batch causes the entire batch to be retried or sent to the dead-letter ...

  [conv-1] user: What did I ask about first?
  [conv-1] bot:  You first asked how to configure Kafka batch consumers in Spring Boot.

===== conversation conv-2 (a fresh thread - no shared context) =====
  [conv-2] user: What are the pitfalls?
  [conv-2] bot:  The term "pitfalls" is too broad to answer without specific context, as it applies to fields ranging from programming to project ...

===== history accumulated on conv-1 =====
  user: How do I configure Kafka batch consumers in Spri
  bot : To configure batch consumers in Spring Boot, set
  user: What are the pitfalls?
  bot : The primary pitfall is that a failure in any sin
  user: What did I ask about first?
  bot : You first asked how to configure Kafka batch con
  6 messages (3 turns = 3 questions + 3 answers)

This is one representative run (Chapter 12). What the code controls is which history the model sees. On conv-1 the checkpointer replayed the whole transcript into the node, so “the pitfalls” and “What did I ask first?” had the Kafka turn in front of them. The resolving is still the model’s; the code only decides what context it gets. On conv-2 the history was empty, so the model asked for a context rather than connecting the question to Kafka — the word could mean anything from programming to project management. A thread_id it had never seen gave it nothing to bind “pitfalls” to.

The conversation memory here is the checkpoint from Chapter 8. In LangGraph, “multi-turn chat history” is not a separate feature; it is a messages list accumulated by add_messages and persisted per thread_id by the checkpointer you already met. A conversation is a thread.

NoteDeep Dive: what actually got saved on the thread

Print graph.get_state({"configurable": {"thread_id": "conv-1"}}) after conv-1 and you see the checkpoint is holding the entire message list — all six messages, in order. (The run above prints only a truncated 48-character preview of each, but the checkpoint keeps them in full.) That is the checkpoint being true to its nature from Chapter 8: automatic and lossless, the full state after every superstep. Nobody decided those six messages were “worth remembering” — the checkpointer saved everything, because that is what a checkpoint does.

Hold onto that word lossless. It is why a checkpoint makes a good conversation memory (you want every turn, in order) and a poor long-term memory (you do not want every word of every past session forever). Keep piling turns onto one thread and the history only grows. The next section is what you do when it grows too far, and the section after that is the different tool for the different job.

17.5 When the history gets too long

There is a cost buried in “the model sees the WHOLE history”: every turn re-sends every previous turn. Ten turns in, each new question drags nine turns of context along with it; a hundred turns in, you are paying to re-read a small book on every message, and eventually you blow past the model’s context window entirely. The lossless checkpoint is still doing its job perfectly — the problem is that we are feeding all of it to the model every time.

The standard fix is to stop sending the old turns verbatim and send a summary of them instead. We add a summarize node that runs before chat: when the history is longer than a few recent messages, it compresses the older ones into a running summary string and deletes them from the state with RemoveMessage, so the live message list it re-sends each turn stays small.

from typing import NotRequired
from langchain_core.messages import RemoveMessage

KEEP_RECENT = 4   # keep roughly the last 4 messages verbatim (rounded up to a
                  # whole turn); fold older ones into summary


class SummaryState(TypedDict):
    messages: Annotated[list, add_messages]
    summary: NotRequired[str]   # running summary of dropped turns (absent on turn 1)


def summarize_node(state: SummaryState) -> dict:
    msgs = state["messages"]
    # Walk the cutoff back to a turn boundary (a HumanMessage) so we only ever
    # fold COMPLETE user/assistant turns and never orphan an answer in the window.
    cutoff = max(0, len(msgs) - KEEP_RECENT)
    while cutoff > 0 and not isinstance(msgs[cutoff], HumanMessage):
        cutoff -= 1
    old = msgs[:cutoff]   # whole turns only, ready to compress away
    if not old:
        return {}   # nothing complete to fold yet

    old_text = "\n".join(
        f"{'User' if isinstance(m, HumanMessage) else 'Assistant'}: {m.content}"
        for m in old
    )
1    prev = state.get("summary", "")
    prompt = (
        "Compress the conversation below into a short summary that keeps the key "
        "facts and conclusions.\n"
        f"Existing summary: {prev or '(none)'}\n"
        f"New turns to fold in:\n{old_text}\n\n"
        "Updated summary:"
    )
    new_summary = llm.invoke(prompt).content.strip()

2    removals = [RemoveMessage(id=m.id) for m in old]
    print(f"      (summarize: folded {len(old)} old message(s) into the summary; "
          f"kept the recent turns verbatim)")
    return {"summary": new_summary, "messages": removals}
1
The summary is cumulative: each pass folds the newly-old turns into whatever summary already existed, carrying the previous one forward, although compression can still discard detail.
2
The same add_messages reducer working in reverse: hand it a normal message and it appends; hand it a RemoveMessage carrying an existing id and it removes that message. The ids come for free; add_messages assigned them when the messages were first appended.

The chat node then feeds that summary back to the model as background, so the turns we deleted still shape the answer:

def summary_chat_node(state: SummaryState) -> dict:
    system_text = ("You are a documentation assistant. Answer concisely, "
                   "in no more than two sentences.")
    if state.get("summary"):
        system_text += f"\n\nEarlier conversation summary: {state['summary']}"
    reply = llm.invoke([SystemMessage(content=system_text)] + state["messages"])
    return {"messages": [reply]}

The graph gains one node in front of chat — compress first, then answer:

builder = StateGraph(SummaryState)
builder.add_node("summarize", summarize_node)
builder.add_node("chat", summary_chat_node)
builder.add_edge(START, "summarize")
builder.add_edge("summarize", "chat")
builder.add_edge("chat", END)
graph = builder.compile(checkpointer=InMemorySaver())

%%{init: {'securityLevel': 'loose', 'flowchart': {'diagramPadding': 24}, 'themeCSS': 'foreignObject{overflow:visible}span.bot{display:flex;justify-content:flex-start;align-items:flex-start;width:100%;height:0;overflow:visible;line-height:0}span.bot img{display:block!important;width:18px!important;height:18px!important;padding:2px;background:#fff;border-radius:50%;box-shadow:0 0 0 1px #999}span.bot.r img{margin:0;transform:translate(-24px,-24px)}span.bot.d{justify-content:center}span.bot.d img{margin-top:-50%;transform:translateY(-24px)}'}}%%
flowchart TD
    START(["START"]) --> summarize("<span class='bot r'><img src='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiMzMzMiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48cGF0aCBkPSJNMTIgOFY0SDgiLz48cmVjdCB3aWR0aD0iMTYiIGhlaWdodD0iMTIiIHg9IjQiIHk9IjgiIHJ4PSIyIi8+PHBhdGggZD0iTTIgMTRoMiIvPjxwYXRoIGQ9Ik0yMCAxNGgyIi8+PHBhdGggZD0iTTE1IDEzdjIiLz48cGF0aCBkPSJNOSAxM3YyIi8+PC9zdmc+'/></span>summarize") --> chat("<span class='bot r'><img src='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiMzMzMiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48cGF0aCBkPSJNMTIgOFY0SDgiLz48cmVjdCB3aWR0aD0iMTYiIGhlaWdodD0iMTIiIHg9IjQiIHk9IjgiIHJ4PSIyIi8+PHBhdGggZD0iTTIgMTRoMiIvPjxwYXRoIGQ9Ik0yMCAxNGgyIi8+PHBhdGggZD0iTTE1IDEzdjIiLz48cGF0aCBkPSJNOSAxM3YyIi8+PC9zdmc+'/></span>chat") --> END(["END"])

Run five turns on one thread and watch the state size instead of the answers:

########## long conversation (summarize older turns) ##########

  user: How do I configure Kafka batch consumers?
  bot:  To configure Kafka batch consumers, set the `max.poll.records` property to define the maximum number of records returned in a single poll ...
  state now holds 2 message(s)

  user: What are the pitfalls?
  bot:  The primary pitfalls include increased end-to-end latency due to waiting for a full batch and the risk of data loss if the application ...
  state now holds 4 message(s)

  user: How do I configure a Redis connection pool?
  bot:  Configure a Redis connection pool by setting parameters like `maxTotal` (maximum connections), `maxIdle` (maximum idle connections), and ...
  state now holds 6 message(s)

      (summarize: folded 2 old message(s) into the summary; kept the recent turns verbatim)
  user: How do I optimize a slow MySQL query?
  bot:  Start by running `EXPLAIN` to identify missing indexes or inefficient join orders, then add appropriate indexes to the filtered columns. ...
  state now holds 6 message(s) | summary: To configure Kafka batch consumers, set the `max.poll.records` property to define batch size and ensure the entire batch is processed ...

      (summarize: folded 2 old message(s) into the summary; kept the recent turns verbatim)
  user: What was the very first topic we discussed?
  bot:  The first topic discussed was configuring Kafka batch consumers. This involved setting `max.poll.records` to define batch size and ...
  state now holds 6 message(s) | summary: To configure Kafka batch consumers, set `max.poll.records` to define batch size and process the entire batch before committing offsets to ...

Follow the state now holds N line. It climbs to 4, then to 6, and there it stops: however long the conversation runs, only whole recent turns stay verbatim and everything older is folded away. The first fold comes at turn 4, not at turn 3 where a plain len(msgs) > KEEP_RECENT would have fired, because at turn 3 the cutoff lands on an answer and walks back to zero. The role-aware cutoff never strands an answer without its question.

The dropped turns went into the summary, which is why the final turn still answers “the very first topic” correctly even though the opening Kafka messages left the state two turns ago.

What stays bounded is the verbatim window fed to the model each turn. The summary string itself keeps growing unless you cap it, and RemoveMessage trims the live state but does not erase the older checkpoint snapshots the checkpointer already wrote. The price is that the summary keeps conclusions, not wording: a question that needs the exact text of turn 1 gets the summary’s paraphrase of it.

There is a second cost in the same sentence, and summarizing happens to fix it too. Every turn re-sends the whole history to the model, and every turn also re-writes it to the checkpointer: the saver stores the list as it stands at the end of each step, so turn 100 writes a hundred turns to disk. Shortening the list shortens both. The next section is for when you cannot shorten it.

TipTry it: trim instead of summarize

Summarizing spends a model call to compress. A cheaper option, when you can afford to forget old turns, is to trim: keep the full history in the state but only send the most recent slice to the model. langchain_core.messages.trim_messages does this — swap the summarize node for a one-liner in chat that builds recent = trim_messages(state["messages"], max_tokens=4, strategy="last", token_counter=len, start_on="human") and invokes on recent instead of the whole list. One thing to read carefully: token_counter=len counts messages, so max_tokens=4 means “keep the last four messages,” not four tokenizer tokens — pass a real tokenizer as token_counter to budget by actual tokens. Re-run the five turns and ask “the very first topic” again: trimming has no summary to lean on, so the answer to that last question changes. Trim doesn’t delete anything from State — the full history is still saved (the line above keeps state["messages"]); it only narrows what this turn sends to the model. Summarize instead distills the old turns into a running note. Reach for trim when only the recent window matters, summarize when the whole conversation’s gist has to survive.

17.6 When you cannot delete

WarningDeltaChannel is beta on LangGraph 1.2.19

Everything below works and is measured on the pinned version, but the API and the on-disk representation may both still change. A thread written with it today is expected to stay readable; the shape it is written in is not settled. Reach for it to stop a saver from drowning, not to found an archive you must still be able to open in five years.

Summarize and trim both answer the same way: send less, and in the summarize case keep less. Some threads cannot take that answer. An audit trail, a run that has to be replayable exactly, a transcript someone may have to read back in a year — the record is the point, and nothing may be dropped from it.

The history then stays, and the cost of keeping it lands where the previous section said: on disk, growing with the square of the turns.

LangGraph has a channel for exactly that bind. A DeltaChannel holds the same list your reducer always held, and a node writes to it the same way — return the new messages, as always. What changes is what the checkpointer stores. Rather than saving the whole list at the end of every step, it saves that step’s addition, and assembles the list again when something reads the thread. Nothing is dropped; the same conversation comes back.

The program below runs one sixty-turn thread twice, once each way, deleting nothing, and prints what the saver wrote. Three things in it are worth watching: whether the two conversations really do come out identical, which column moves, and — the one that explains the rest — which column does not.

===== 60 turns on one thread, nothing deleted =====
   reducer         #msg   checkpoints    writes     total
   ------------    ----  ------------  --------  --------
   add_messages     120      3,138 KB     33 KB  3,172 KB
   DeltaChannel     120        101 KB     33 KB    135 KB

All three answers are in those two rows. The conversations are identical, a hundred and twenty messages each. The checkpoints column is the one that moves, by a factor of thirty. And the writes column does not move at all — 33 KB either way — which is what explains the other two: the per-turn additions always cost what they cost, and the only thing the second row stops paying for is re-copying everything that came before.

Thirty times is a strange-looking number until you watch it accumulate. The same program prints what each individual turn cost:

   what each turn cost, in the checkpoints column
    turn    add_messages    DeltaChannel
    ----    ------------    ------------
       1         2,100 B         1,400 B
       2         4,200 B         1,700 B
       3         5,900 B         1,700 B
     ...             ...             ...
      30        52,700 B         1,700 B
      59       103,000 B         1,700 B
      60       104,700 B         1,700 B

Turn 1 is nearly a tie. Turn 60 is not: one of them spends a hundred kilobytes to add two messages, because it is writing the other hundred and eighteen again as well. The left column is a staircase and the right column is a floor, and the two totals are those two shapes summed. Sixty turns is not even a long conversation — the gap goes on widening for as long as the thread does.

This is Joel Spolsky’s Shlemiel the painter, who gets slower every day because he keeps walking back to the paint can.1 A DeltaChannel is the painter carrying the can.

The change is to the annotation, not to any node:

class SummaryState(TypedDict):
    messages: Annotated[list, DeltaChannel(add_messages_batch,   # was: add_messages
                                           snapshot_frequency=1000)]

Three more things to know before reaching for it:

  • It asks more of the reducer than Section 10.3 did. The signature is not the same one: a DeltaChannel reducer is handed a batch of writes, reducer(state, [write1, write2, ...]) -> new_state. And it must be batching-invariant, which the documentation states outright:

    reducer(reducer(state, xs), ys) == reducer(state, xs + ys)

    Two batches folded separately must give what their concatenation gives in one go, because reconstructing the list is free to regroup the writes into larger batches than the run produced them. Section 10.3 asked for associativity (be warned: the runtime would not check it); here the channel takes you up on it. Folding one write at a time, as add_messages_batch does, satisfies the rule by construction.

  • Your checkpointer has to support it. SqliteSaver and AsyncSqliteSaver do. A saver of your own needs the two methods the base class added for it.

  • It is not deltas all the way down. Every so many updates the channel writes a full copy instead, so that reading a long thread does not mean replaying it from turn one. How often is snapshot_frequency, and its default moved from 1000 updates to 100 in LangGraph 1.2.18 — quicker reads, more bytes. That is why the annotation above passes it: pinned to 1000, the columns of the measurement are about deltas. Leave it at the default and this run, at two updates a turn, buys one full copy around turn 50: about 28 KB, enough to take the delta total from 135 KB to 163 KB and the headline from 23x to 19x. Still the right shape — a floor with one step in it rather than a staircase — but worth knowing which of the two you are measuring.

The order to try things in is the order of this chapter. Can you send less? Trim. Can you keep less? Summarize. Only when the answer to both is no does how the history is stored become your problem.

17.7 Long-term memory: the Store

Everything so far lives and dies with a thread_id. Start a fresh conversation and, as conv-2 showed, the bot knows nothing about you. That is correct for a checkpoint, whose job is one conversation, however many runs it spans. Now the second scenario: the user comes back next week, opens a new conversation, and expects the bot to know they work in Python and never Java, that they are new to the framework, that they told you their deployment target last time. Those are not “the state of a run”; they are facts about a user, and they belong in a different kind of memory: a Store.

A Store is a small key-value store scoped by a namespace — a tuple you choose, typically one per user. Its three operations are put, get, and search:

from langgraph.store.memory import InMemoryStore

store = InMemoryStore()
alice = ("memories", "u_alice")   # a namespace: one drawer per user
bob = ("memories", "u_bob")

# put(namespace, key, value): value is a dict whose shape you choose.
store.put(alice, "stack", {"text": "Works in Python, never Java"})
store.put(alice, "level", {"text": "New to LangGraph"})
store.put(bob, "stack", {"text": "Works in Go"})

store.get(alice, "stack")     # -> one Item; the payload is Item.value
store.search(alice)           # -> Items under alice's namespace (up to 10 by default)
########## the Store on its own (put / get / search) ##########

get (alice, stack) -> {'text': 'Works in Python, never Java'}
everything known about u_alice:
    stack: Works in Python, never Java
    level: New to LangGraph
everything known about u_bob:
    stack: Works in Go

put files a fact; get fetches one back by key; search returns the items under a namespace prefix — up to ten by default, with limit/offset to page through more when a namespace holds many. The namespace is the boundary — an organizing one, not an access-control one: it decides where a fact is filed and what a search returns, but it enforces no isolation (any code holding the Store can read any namespace). Alice’s drawer and Bob’s drawer never touch, so search(alice) can never surface Bob’s facts. (get returns an Item whose .value is the dict you stored; search returns a list of them.)

search has a second gear this chapter does not use: search(namespace, query="…") ranks by meaning instead of listing by prefix — but only once the Store was built with an embedding index2. Without one the query is quietly ignored and you get the plain listing back with every score set to None, so check the index before you trust a ranking. Expiry is the other backend-dependent piece: put(..., ttl=…) is in the BaseStore contract, but InMemoryStore raises NotImplementedError on it — one more reason production wants a database-backed Store.

To use the Store inside the graph, you attach it at compile time next to the checkpointer, and read it inside a node off runtime.store. (There is also a module-level get_store() in langgraph.config, which digs the same object out of the run’s context — useful in a helper with no runtime parameter to hand. Where a node already declares runtime, as every node here does, reading the field is the plainer move.)

from dataclasses import dataclass
from langgraph.runtime import Runtime
from langgraph.store.base import BaseStore


@dataclass
class Context:
    user_id: str   # who this run is for - a per-run dependency, not State


class State(TypedDict):
    messages: Annotated[list, add_messages]


def chat_node(state: State, runtime: Runtime[Context]) -> dict:
    # facts are keyed by THIS user (runtime context), not this thread
1    store = runtime.store
2    namespace = ("memories", runtime.context.user_id)
    facts = [item.value["text"] for item in store.search(namespace)]
    print(f"  [chat] recalled {len(facts)} fact(s) about "
          f"{runtime.context.user_id}: {facts}")

    system_text = ("You are a documentation assistant. Answer concisely, "
                   "in no more than two sentences.")
    if facts:
        system_text += "\n\nKnown facts about this user: " + "; ".join(facts)
    reply = llm.invoke([SystemMessage(content=system_text)] + state["messages"])
    return {"messages": [reply]}
1
The Store is a compile-time dependency, not a state channel: you attach it once with compile(store=...) and the runtime hands it to every node. It is a field on the same runtime the next line reads the context from — one object, two of its fields.
2
The user_id is a per-run value, so it rides runtime context, as the model handle did in Section 14.8. Neither goes into State.

The Store does not flow through State turn to turn; it is wired in at build time and stands beside the checkpointer:

def build_store_graph(store):
    builder = StateGraph(State, context_schema=Context)
    builder.add_node("chat", chat_node)
    builder.add_edge(START, "chat")
    builder.add_edge("chat", END)
    # Two separate memories on one compiled graph: the checkpointer (per-thread
    # conversation history) and the Store (cross-thread facts).
    return builder.compile(checkpointer=InMemorySaver(), store=store)

Nothing writes to the Store on its own. A fact lands there when your code calls store.put:

def remember_fact(store: BaseStore, user_id: str, key: str, text: str) -> None:
    store.put(("memories", user_id), key, {"text": text})

One helper sends a turn. It carries the thread_id on config as before, and the new piece — the user_id — on context, so that runtime.context.user_id inside the node resolves to this user. That context=Context(...) is how the per-run identity reaches the node:

def ask(graph, thread_id: str, user_id: str, text: str) -> None:
    result = graph.invoke(
        {"messages": [HumanMessage(content=text)]},
        config={"configurable": {"thread_id": thread_id}},   # which conversation
        context=Context(user_id=user_id),                    # which user
    )
    print(f"  [{thread_id}] user: {text}")
    print(f"  [{thread_id}] bot:  {excerpt(result['messages'][-1].content)}")  # first line, trimmed

We record two facts about Alice once, then talk to her on two different threads, and to Bob on a third:

store = InMemoryStore()
graph = build_store_graph(store)

remember_fact(store, "u_alice", "stack", "Works in Python, never Java")
remember_fact(store, "u_alice", "level", "New to LangGraph")

ask(graph, "conv-A", "u_alice", "How should I read a config file?")
ask(graph, "conv-B", "u_alice", "How do I parse JSON?")   # a NEW thread, same user
ask(graph, "conv-C", "u_bob",   "How do I parse JSON?")   # a different user
########## the Store inside the doc-bot (recall across threads) ##########

----- conv-A: Alice -----
  [chat] recalled 2 fact(s) about u_alice: ['Works in Python, never Java', 'New to LangGraph']
  [conv-A] user: How should I read a config file?
  [conv-A] bot:  Since you work in Python, use the `json` module to load JSON files or the `configparser` library for INI files. For YAML configurations ...

----- conv-B: Alice again, a different thread -----
  [chat] recalled 2 fact(s) about u_alice: ['Works in Python, never Java', 'New to LangGraph']
  [conv-B] user: How do I parse JSON?
  [conv-B] bot:  Use Python's built-in `json` module by calling `json.loads()` to parse a JSON string or `json.load()` to read from a file.

----- conv-C: Bob, a different user -----
  [chat] recalled 0 fact(s) about u_bob: []
  [conv-C] user: How do I parse JSON?
  [conv-C] bot:  Use the `json` module in Python, specifically the `json.loads()` function, to parse a JSON string into a Python object. For example, `data ...

Read the three recalled ... fact(s) lines. conv-B is a brand-new thread — its checkpoint is empty, the bot has no conversation history there at all — and yet it recalls both of Alice’s facts and answers in Python, because those facts came from the Store, keyed by user, not by thread. conv-A (a different thread, same user) recalls them too.

conv-C is Bob: same code, same namespace scheme, but a different namespace, so search finds nothing. His answer still happens to come out in Python, and that is the part worth taking: the language of an answer does not demonstrate recall. The recalled lines do — two facts for Alice, on two different threads; none for Bob. The Store crossed the thread boundary that the checkpoint, by design, never crosses.

NoteDeep Dive: the save file and the notebook

A checkpoint is a game save file: full, automatic, lossless, tied to one playthrough. A Store is whatever you write into it, and what this chapter writes is a notebook: only what is worth keeping (“this boss has to be fought last”), in your own words, carried into a completely different playthrough. The rows below compare the checkpoint with that use of the Store, not with everything a Store can hold — nothing stops you from putting whole transcripts in one:

Checkpoint (Chapter 8) Long-term memory (this Store)
what the entire state, verbatim here, selected facts, distilled
how automatically, every superstep deliberately, when you choose
lossy? lossless (a full snapshot) here, lossy (only the conclusions)
scope one thread_id, many runs across threads, a namespace
purpose resume/replay this run recall what matters about a user

Mixing the two is the usual mistake, and it has a shape: reaching for an old thread_id to “remember” a user. That does not recall the user, it resurrects one stale conversation’s transcript — the anti-pattern Chapter 8 warned about. To remember the user, write a namespace.

17.8 The same shape elsewhere

Two stores, one keyed by conversation and one keyed by user, is the oldest layout in web development. The thread_id is a session id and the checkpoint is session state; the Store is the system of record. An application built on a session abstraction draws the same line when it treats the session as rebuildable — login and view state — and keeps the durable facts elsewhere, for the same reason: what you learn about a person should not vanish when they close the tab.

Where the parallel stops is worth knowing before you size anything. A session store used that way is a cache in front of the truth — lose Redis and the user signs in again. (Used another way it is not: Spring Session will persist any attribute you hand it, and an application whose only copy of something lives there has made the session the truth.) A checkpoint is never a cache: for that conversation it is the truth, and there is no origin to fall back to.

17.9 The operational rule

Two numbers to keep in mind from the runs above. A bare thread grows by two messages per turn with no ceiling. The summarizer held the live state at 6 messages from turn 3 onward, but the summary string kept growing and the older checkpoint snapshots kept every folded message. And the Store recalled 2 facts for Alice on a thread with an empty checkpoint and 0 for Bob on the same code: the namespace, not the thread, decided what the bot knew.

For the prebuilt create_agent of Section 13.5, LangChain 1.x packages the summarizer as SummarizationMiddleware, which compresses the history before each model call; the node you wrote is the mechanism behind that name.

Our doc-bot can now hold a conversation, keep it from overflowing, and remember a user across sessions. What it can’t yet do is feel responsive: every answer arrives all at once, after a pause, instead of streaming out word by word the way a real chat interface does. The next chapter fixes that — we stream the graph’s output token by token, and learn which parts of a run you can watch live versus which only the checkpoint can recover.

New pieces in this chapter

Piece Usage
Type
SystemMessage Langchain-core’s message type for system instructions. SystemMessage(content="You are a …"); prepended at call time — it never enters the state’s history here
RemoveMessage A deletion marker the add_messages reducer understands. RemoveMessage(id=m.id); trims the live state only — older checkpoint snapshots keep the message
InMemoryStore In-process key-value Store for long-term, cross-thread facts. store = InMemoryStore(); like InMemorySaver, it dies with the process — production wants a database-backed one
BaseStore The base type all Stores share, for annotations. def remember_fact(store: BaseStore, …); the namespace organizes — it does not enforce access control
API
add_messages A function used as the built-in message reducer; appends returned messages instead of overwriting. messages: Annotated[list, add_messages]; assigns missing ids and merges by id
DeltaChannel A state channel that stores each step’s addition rather than re-writing the whole value. Annotated[list, DeltaChannel(reducer)]; for a history you may not shorten. Its reducer takes a batch of writes, and it is beta on 1.2.19 — the on-disk shape may change (Section 17.6)
trim_messages() Send only the most recent slice of history instead of summarizing. trim_messages(msgs, max_tokens=4, strategy="last", token_counter=len, start_on="human"); forgets, doesn’t distill
store.put() Deliberately file a fact under a namespace and key. store.put(("memories", "u_alice"), "stack", {"text": …}); writing is deliberate, unlike a checkpoint
store.get() Fetch one fact back by key. store.get(alice, "stack"); returns an Item — the payload is Item.value
store.search() List the items under a namespace prefix. store.search(namespace); up to 10 by default — page with limit/offset
runtime.store The Store attached at compile time, handed to the node on its runtime. store = runtime.store; a compile-time dependency, not a state channel. langgraph.config.get_store() reaches the same object without a runtime parameter
compile(store=…) Keyword arg that attaches a Store to the compiled graph, beside the checkpointer. builder.compile(checkpointer=InMemorySaver(), store=store); two separate memories on one graph

Code in this chapter

File What it runs
code/ch15_memory.py Multi-turn chat on one thread, and the fold that summarises the history before it outgrows the window.
code/ch15_store.py A Store remembers a user across threads: distilled facts under a namespace that any later conversation can read.
code/ch15_delta_channel.py Sixty turns kept in full, stored two ways — what the checkpointer writes with add_messages against a DeltaChannel. No model: the replies are canned, because the thing measured is the saver.

Challenge

🥉 Bronze — prove the checkpoint doesn’t cross threads

Take the multi-turn chat (code/ch15_memory.py) and, on one thread_id, tell the bot a fact about yourself (“I only write Rust”), then ask it a coding question and watch it honor that. Now send the same coding question on a brand-new thread_id.

Then read the evidence rather than the prose. Call graph.get_state on both threads and compare the messages each one holds: the Rust sentence is in the first thread’s history and absent from the second’s. That is the proof — a second answer that happens not to mention Rust shows nothing, for the same reason the Store section gives when Bob’s answer comes out in Python anyway. You have just proved the checkpoint’s scope is one conversation — the exact gap the Store is built to fill.

office hours Worked solution with tests: code/answers/ch15_checkpoint_scope.py.

🥈 Silver — remember a fact the model was told, not one you hard-coded

Add a remember node (before or after chat) that notices when the user states a durable preference — “from now on, answer in Python” — and writes it to the Store itself with store.put, so a later thread can recall a fact the user gave in an earlier one.

The proof takes two conversations: state a preference on conv-A, then open conv-B, ask something the preference should govern, and see whether the answer honors a fact you never hard-coded.

Hints: in code/ch15_store.py the facts are written by remember_fact from outside the conversation — this closes that loop. Structured output gives you a typed field to branch on (Section 12.5). Think about which Store key lets a restated preference update one entry instead of piling up near-duplicates — real models rephrase. And a schema guarantees the shape, not the judgment — whether a sentence is actually worth saving is governed by your prompt, validation, and tests, not by the type (the shape-versus-choice lesson from Chapter 12).

office hours Worked solution with tests: code/answers/ch15_learned_facts.py.

🥇 Gold — ask the Store a question instead of listing it

Everything so far reads facts back by prefix: search(namespace) is a listing, and it has no idea what any of the facts say. Give the Store an embedding index so it can rank them by meaning instead — then take the index away and run the same query again, which is the half worth remembering.

Build two Stores over the same handful of facts about one user, one with index={…} and one without, and put the same natural-language question through both.

You’ve got it when the indexed Store returns the on-topic fact first, every hit carrying a real score, and the unindexed one returns the whole namespace with every score set to None — and neither call raises. Then write down the line of your own code that would have caught the second case in production, because nothing in the library will.

Hints: index takes three keys — embed, dims, fields. dims is the width of the model you pass, not the one in the guide’s example: the book’s embedding model is 768, not 1536, and a mismatch indexes into the wrong-shaped space. fields is a list of JSON paths, and ["$"] embeds the whole stored dict. This is the one Part II exercise that needs the embedding model from Chapter 2 — the chat model sits this one out. Keep the facts short but name their subject; with a small local embedder, short anonymous sentences score within a few hundredths of each other and the ranking stops being convincing.

If your log opens with “NumPy not found in the current Python environment”, that is InMemoryStore telling you it will do the cosine similarity in pure Python. It is a speed note, not an error, and the scores are the same either way — you can ignore it or pip install numpy. Part III’s chromadb brings NumPy along, which is why the warning only appears if you reach this exercise first.

office hours Worked solution with tests: code/answers/ch15_semantic_recall.py.


  1. Back to Basics, 2001: https://www.joelonsoftware.com/2001/12/11/back-to-basics/.↩︎

  2. An embedding index is what turns a Store from a filing cabinet you list into one you can ask a question of. Without it, search matches on the namespace prefix — the drawer — and on no part of the contents. With it, every item is also run through an embedding model on the way in and stored as a vector, so search(ns, query="…") embeds the query and ranks by distance: the same machinery Chapter 27 builds by hand, applied to remembered facts instead of documents. The Gold challenge builds one; the Stores guide has the full surface: https://docs.langchain.com/oss/python/langgraph/stores.↩︎