How to Stream, Save and Rewind a Long Deep Agent Run

8 min read

A deep agent can run for many minutes. It plans, calls tools, starts subagents and writes files. If all your app does is wait for invoke() to return, three things go wrong. The user stares at a spinner with no idea what is happening. A crash at minute nine throws away all nine minutes. And the conversation keeps growing until it no longer fits in the model's context window.

LangGraph fixes all three, and create_deep_agent gives you that for free. This part opens the box. You will see the real graph a deep agent compiles to, stream its events four different ways, save and rewind a run with a checkpointer, and watch summarization shrink what the model sees.

All output below was captured from real runs of the code in code/part11/. If you are new to the series, Part 3 builds the first agent and Part 6 covers subagents.

A deep agent is a compiled LangGraph graph

create_deep_agent builds a middleware stack and hands it to LangChain's create_agent. What comes back is a LangGraph CompiledStateGraph. You can print its nodes:

python
from deepagents import create_deep_agent

agent = create_deep_agent(model="anthropic:claude-sonnet-4-6")
print(type(agent).__name__)
print(list(agent.nodes))
for e in agent.get_graph().edges:
    print(e.source, "->", e.target, "(conditional)" if e.conditional else "")

Here is the output with the default stack:

text
type: CompiledStateGraph
nodes:
   __start__
   model
   tools
   _ParentNotifierMiddleware.after_agent
   PatchToolCallsMiddleware.before_agent
edges:
   PatchToolCallsMiddleware.before_agent -> model
   __start__ -> PatchToolCallsMiddleware.before_agent
   model -> _ParentNotifierMiddleware.after_agent (conditional)
   model -> model (conditional)
   model -> tools (conditional)
   tools -> model (conditional)
   _ParentNotifierMiddleware.after_agent -> __end__
config defaults: {'recursion_limit': 9999}

The heart is a two-node loop: model and tools. The model either asks for tools, which sends the run to tools and back, or it answers, which ends the run. Middleware with before_agent or after_agent hooks adds its own nodes, named {Middleware}.{hook}. Most of the stack (filesystem, subagents, summarization, prompt caching) works by wrapping the model call, so it adds no nodes at all. Note the recursion limit too. A deep agent sets it to 9,999 steps, because long tasks need many loop turns.

The deep agent graph: a model and tools loop, with a checkpoint saved after every step

flowchart LR
    S([start]) --> P[PatchToolCalls]
    P --> M[model]
    M -->|tool calls| T[tools]
    T -->|results| M
    M -->|answer| N[ParentNotifier]
    N --> E([end])
    T -.-> SA[subagent graph]

Knowing these names matters, because streams are keyed by them.

Streaming: four views of one run

To test streaming, we built an agent with one subagent called counter. It has a tool that reports progress with get_stream_writer():

python
from langchain_core.tools import tool
from langgraph.config import get_stream_writer

@tool
def count_lines(text: str) -> str:
    """Count lines in text, reporting progress as it goes."""
    writer = get_stream_writer()
    lines = text.splitlines()
    for i, _ in enumerate(lines, 1):
        writer({"progress": f"{i}/{len(lines)}"})
    return f"{len(lines)} lines"

agent = create_deep_agent(
    model="anthropic:claude-sonnet-4-6",
    subagents=[{"name": "counter", "description": "Counts lines in text.",
                "system_prompt": "You count lines.", "tools": [count_lines]}],
)

The main agent hands the work to counter with the task tool, counter calls its tool, and the answer flows back.

sequenceDiagram
    participant U as your app
    participant M as main agent
    participant C as counter subagent
    participant T as count_lines
    U->>M: How many lines?
    M->>C: task tool call
    C->>T: count_lines
    T-->>U: custom progress 1/3, 2/3, 3/3
    T-->>C: 3 lines
    C-->>M: There are 3 lines.
    M-->>U: final answer

updates: what each node just did

stream_mode="updates" sends one chunk per node step. With subgraphs=True, each chunk also carries a namespace that says which graph made it:

python
for ns, update in agent.stream(msg, stream_mode="updates", subgraphs=True):
    for node, val in update.items():
        print(ns, node)
text
  ns=()                           node=PatchToolCallsMiddleware.before_agent    keys=NoneType
  ns=()                           node=model                                    keys=['messages']
  ns=('tools:8b329a22-0bc0-93ea-9 node=PatchToolCallsMiddleware.before_agent    keys=NoneType
  ns=('tools:8b329a22-0bc0-93ea-9 node=model                                    keys=['messages']
  ns=('tools:8b329a22-0bc0-93ea-9 node=tools                                    keys=['messages']
  ns=('tools:8b329a22-0bc0-93ea-9 node=model                                    keys=['messages']
  ns=()                           node=tools                                    keys=['messages']
  ns=()                           node=model                                    keys=['messages']
  ns=()                           node=_ParentNotifierMiddleware.after_agent    keys=NoneType

An empty namespace () is the main agent. ('tools:<id>',) is a subagent started from the main agent's tools node. The subagent runs its own full loop inside that one main-agent step. This is how a UI can show "counter is working" in its own panel.

values: the whole state after each step

stream_mode="values" sends the full state each time. It is simple, but it gets heavy as state grows. Without subgraphs=True you only see the main graph:

text
  step 0: 1 messages, last=human
  step 1: 2 messages, last=ai
  step 2: 3 messages, last=tool
  step 3: 4 messages, last=ai

The subagent's four messages never show up here. The main agent only gets the subagent's final answer as one tool message. That is the context isolation from Part 6, seen from the outside.

messages: tokens and tool calls as they happen

stream_mode="messages" sends message chunks from every model call, plus metadata. With a real model you get token-by-token text. Our scripted model returns whole messages, so each line is one chunk:

text
  ns=()                           node=model  agent=None ai: [{'name': 'task', 'args': {'description': 'Count the lines i...
  ns=('tools:fe3a7872-c782-14e6-9 node=model  agent=counter ai: [{'name': 'count_lines', 'args': {'text': 'a b c'}, 'id': 'c...
  ns=('tools:fe3a7872-c782-14e6-9 node=tools  agent=counter tool: '3 lines'
  ns=('tools:fe3a7872-c782-14e6-9 node=model  agent=counter ai: 'There are 3 lines.'
  ns=()                           node=tools  agent=None tool: 'There are 3 lines.'
  ns=()                           node=model  agent=None ai: 'The counter subagent says: 3 lines.'

The metadata key lc_agent_name names the subagent (counter). The langgraph_node key says whether the chunk came from model or tools. Those two fields are enough to route text into the right part of a chat UI.

custom: your own progress events

Anything passed to get_stream_writer() comes out on the custom stream. When you ask for several modes, each chunk becomes a (namespace, mode, data) tuple:

python
for ns, mode, data in agent.stream(msg, stream_mode=["custom", "updates"], subgraphs=True):
    ...
text
  ...
  update ns=('tools:7fb40274-fe7e-8da5-2 nodes=['model']
  CUSTOM ns=('tools:7fb40274-fe7e-8da5-2 {'progress': '1/3'}
  CUSTOM ns=('tools:7fb40274-fe7e-8da5-2 {'progress': '2/3'}
  CUSTOM ns=('tools:7fb40274-fe7e-8da5-2 {'progress': '3/3'}
  update ns=('tools:7fb40274-fe7e-8da5-2 nodes=['tools']
  ...

The progress events arrive before the tool finishes, from inside the subagent. That is the right tool for progress bars on slow work like crawling or indexing.

One shape rule to remember, from the Deep Agents streaming docs: with subgraphs=True, one mode gives (namespace, data) and several modes give (namespace, mode, data). Without subgraphs, one mode gives data and several give (mode, data).

Checkpoints: save every step, resume any step

A checkpointer saves the graph state after every step. You pick a thread_id per conversation. The same id resumes the same conversation, and a new id starts fresh.

python
from langgraph.checkpoint.memory import InMemorySaver

agent = create_deep_agent(model="anthropic:claude-sonnet-4-6", checkpointer=InMemorySaver())
cfg = {"configurable": {"thread_id": "demo-1"}}

agent.invoke({"messages": [{"role": "user", "content": "Write a plan."}]}, cfg)
agent.invoke({"messages": [{"role": "user", "content": "What is step 1?"}]}, cfg)

The second call did not resend the first turn. The checkpointer loaded it, including the file the agent wrote:

text
turn 1: Plan saved to /plan.md.
turn 2: Step 1 is: outline. (8 messages in thread)
a different thread_id starts empty: []

latest checkpoint: 1f1eb349-9a0b-6acf-800c-6f9391ffcfb9
files in state: ['/plan.md']
next nodes: ()

InMemorySaver is for tests. In production use a database saver, such as the Postgres or SQLite checkpointers for LangGraph, so threads survive a restart. The agent's default StateBackend files live in state, so they are checkpointed with the thread.

History and time travel

get_state_history() lists every checkpoint in a thread, newest first:

text
  step= 12 source=loop   msgs= 8 next=()
  step= 11 source=loop   msgs= 8 next=('_ParentNotifierMiddleware.after_agent',)
  step= 10 source=loop   msgs= 7 next=('model',)
  step=  9 source=loop   msgs= 6 next=('tools',)
  step=  8 source=loop   msgs= 5 next=('model',)
  step=  7 source=loop   msgs= 5 next=('PatchToolCallsMiddleware.before_agent',)
  step=  6 source=input  msgs= 4 next=('__start__',)
  step=  5 source=loop   msgs= 4 next=()
  ...
  step= -1 source=input  msgs= 0 next=('__start__',)
checkpoints in thread: 14

Two short turns made 14 checkpoints. Each has a next field that says which node would run if you resumed from it. That makes time travel simple. Pick a checkpoint and invoke with None as input and that checkpoint's config:

python
history = list(agent.get_state_history(cfg))
target = next(s for s in history if s.metadata["step"] == 8)   # in our run: just before turn 2's model call
agent.invoke(None, target.config)
text
forking from step 8 checkpoint 1f1eb349-983c-6ca0-8008-39c5978da71d
fork answer: (replayed from a fork) Step 1 is still: outline.
checkpoints in thread after fork: 17

The run started again from step 8 and made a new branch. Nothing was deleted: the thread went from 14 to 17 checkpoints. This is how you retry a bad model call, test a new prompt on a real past state, or recover after a crash. It is also what makes the approvals in Part 8 work, since an interrupt is just a paused checkpoint.

Keeping context small

Checkpoints keep everything. The model cannot take everything. Deep agents use two built-in methods to keep what the model sees small, both from the Deep Agents context docs.

Offloading big tool inputs and results

When a tool result is bigger than 20,000 tokens, the agent saves it to the backend. The model gets a file path and a preview of the first 10 lines instead. It can read_file or grep the rest later. Big tool inputs are handled the same way. A write_file call holds the whole file in its arguments. Once the context passes 85% of the window, older calls like that are cut down to a pointer to the file.

Summarization

When offloading is not enough, SummarizationMiddleware steps in. It is in every create_deep_agent stack. In deepagents 0.7.42 its defaults come from the model's profile:

  • With a known max_input_tokens: trigger at 85% of the window, keep the newest 10%.
  • With no profile: trigger at 170,000 tokens, keep the last 6 messages.
  • If a model call fails with a context overflow error, it summarizes at once and retries.

To watch it work, we swapped in a version that triggers after just 6 messages and keeps 2. Passing a middleware with the same name replaces the default one. (You can also pass summarizer= to write summaries with a cheaper model.)

python
from deepagents.backends import StateBackend
from deepagents.middleware.summarization import SummarizationMiddleware

summ = SummarizationMiddleware(
    model="anthropic:claude-sonnet-4-6",
    backend=StateBackend(),
    trigger=("messages", 6),
    keep=("messages", 2),
)
agent = create_deep_agent(model="anthropic:claude-sonnet-4-6", middleware=[summ],
                          checkpointer=InMemorySaver())

The agent wrote three files and listed them. Here is what the model was sent on each call:

text
messages kept in state: 10
model call 1: sent 1 messages: ['human']
model call 2: sent 3 messages: ['human', 'ai', 'tool']
model call 3: sent 5 messages: ['human', 'ai', 'tool', 'ai', 'tool']
model call 4: sent 3 messages: ['human', 'ai', 'tool']
     first message is now the summary: You are in the middle of a conversation that has been summarized. |  | The full conversation history has been saved to /conversation_history/session_df3d82e9368e4d99b2b8c0be5a263d83.md should you need to refer back to it for details. |  | A condensed summary follows: |  | <summary> | SUMMARY: user asked for files; a.md and b.md written. | </summary>
model call 5: sent 5 messages: ['human', 'ai', 'tool', 'ai', 'tool']
Messages sent to the model per call (summarize after 6)
5.4msgs3msgs0.6msgs1msgscall 13msgscall 25msgscall 33msgscall 45msgscall 5
Data from the sources listed below.

On call 4 the request shrank from 5 messages to 3. The first message is now a summary, with a pointer to the full history. But state["messages"] still holds all 10 messages. Summarization changes what is sent, not what is stored. So your checkpoints, replays and evals still see the real history.

The evicted turns went to a file on the backend:

text
files: ['/a.md', '/b.md', '/c.md', '/conversation_history/session_df3d82e9368e4d99b2b8c0be5a263d83.md']
offloaded history /conversation_history/session_df3d82e9368e4d99b2b8c0be5a263d83.md: 2648 chars, first lines:
## Summarized at 2026-11-28T14:06:06.561137+00:00

<message type="human">Write a.md, b.md, c.md.</message>
<message type="ai">
  <tool_call id="w1" name="write_file">{"file_path": "/a.md", "content": "alpha alpha alpha alpha alpha alpha alpha alph

The summary is short, and the full text is one read_file away. If you want the agent to compact on its own, between tasks, add create_summarization_tool_middleware(model, backend). That gives it a compact_conversation tool. Automatic summarization stays on.

Summarization: state keeps every message, the model gets a summary plus recent turns, the old turns go to a file

Prompt caching

Every model call in a deep agent resends the same long system prompt and the same tool list. Prompt caching lets the provider reuse that work. In the 0.7.42 source, create_deep_agent always adds Anthropic's prompt caching middleware, set to quietly do nothing on other providers. It adds the Bedrock and Fireworks versions only when those packages are installed.

The LangChain Anthropic middleware docs describe the settings: a cache ttl of "5m" (the default) or "1h", and min_messages_to_cache, which defaults to 0. It marks the stable parts, the system prompt and tool definitions, so each new turn only pays full price for the new messages.

Caching and summarization pull in different directions. A cache hit needs the start of the prompt to stay the same. A summary rewrites the start. That is one reason the default trigger waits until 85% of the window: summarize rarely, and cache hard in between.

How this code was tested

Versions: deepagents 0.7.42, langchain 1.5.2, langchain-core 1.8.5, langgraph 1.2.24, langgraph-checkpoint 4.3.2. Every log in this part came from a scripted fake model that returns fixed tool calls and answers. That shows the graph, stream shapes, checkpoints and summarization exactly, but not real model text, token-by-token chunks or token counts. A planned run with Llama 4 Scout on Workers AI was not made, because the account hit a rate limit (HTTP 429) earlier the same day. The prompt caching section is based on the deepagents source and the LangChain docs, not on a measured cache hit.

Try this

bash
cd code/part11
python 01_graph.py           # print the compiled graph's nodes and edges
python 02_stream_modes.py    # updates, values, messages and custom streams with a subagent
python 03_checkpoints.py     # two turns on one thread_id, history, then fork from step 8
python 04_summarization.py   # force a summary after 6 messages and read the offloaded file

Then change trigger=("messages", 6) to ("messages", 4) in 04_summarization.py and see which call shrinks first. Or swap InMemorySaver for a SQLite checkpointer, stop the script halfway, and resume the same thread_id.

Up next, Part 12 uses these streams and checkpoints to debug and evaluate deep agents. The gVisor sandbox from Part 10 plugs into the same graph as a backend.

Sources