Agents, middleware and memory

  • Advanced
  • 40 min
  • Lesson 2 of 7 in LangChain ecosystem
  • Last verified

Open slides(33 slides)

Before you start

You will be able to

  • Trace one create_agent call through the agent loop and name the middleware hook that fits a given job: limit, redaction, retry, summarising or approval.
  • Predict the order in which a list of middleware runs for before, wrap and after hooks, and place limits, retries, redaction and approval sensibly.
  • Separate agent state, short-term memory, runtime context and long-term memory by lifetime and mechanism, and say which features need a checkpointer.
  • Choose between subagents, handoffs, skills, a router and a custom graph for a scenario, and justify starting with one agent.
  • Map pre-1.0 patterns to their 1.x replacements and describe a safe migration method.

Vihaan’s job is simple: look up, check, act. But the checks are tangled into the job itself, and when one fails the whole job fails.

Ananya wants a count of steps before he starts, a second look at anything above ₹5,000, and a note of what he did when he finishes.

“Right away,” says Vihaan. He asks where in the job each one goes.

Where does each check belong?

Concept

LangChain offers a ready-made agent like Vihaan: in LangChain, the agent returned by create_agent. This lesson takes it apart. You will follow one call through the loop, see the hooks where middleware attaches, learn the four places an agent keeps information, and compare the multi-agent patterns the docs name. The last section covers moving old code to the current style.

Everything here is from the 1.x docs read on 2026-10-21. The parameter and class names are the part most likely to move, so the lesson teaches the shape and treats the code as illustrative.

Why It Matters

An agent that works in a demo fails in production on things the model did not cause: a loop that never stops, a tool that fails once and takes the run down, an email address sent to a log, a refund issued without anyone looking, a conversation that grows until it overflows. Each of those is a control that belongs around the model. Middleware is how this framework lets you add such controls without rewriting the loop. If you read what is an agent harness?, middleware is where the harness’s enforcement family becomes code in this stack.

Mental Model

Think of a single job as a route with hooks on posts along it. Before the job starts. Before each trip to the model. Around the trip itself. Around each tool pickup. After the model answers. After the job ends. Each check hangs on the post where it has what it needs to act: a trip counter before the model call, a second look around a heavy lift, a tally at the end.

The agent loop

The docs define an agent as a model calling tools in a loop until the task is complete. create_agent builds that loop for you: call the model, run the tools it asks for, add the results to the conversation, and stop when the model answers without asking for a tool. It runs on the LangGraph runtime, which is where persistence and human approval come from.

Diagram: create_agent builds a simple loop.

yes

no

User message and thread_id

Call the model

Did it ask for tools?

Run the tools it asked for

Add the results to the conversation

Return the final message

Checkpointer saves state per thread

Diagram summary: create_agent builds a simple loop. The model is called, any tools it asks for are run, their results are added to the conversation, and the loop repeats until the model answers without asking for a tool. A checkpointer, keyed by thread id, saves the state so a conversation can continue.

Python

# Illustrative: parameter names are from the docs read on 2026-10-21; model names change.
from langchain.agents import create_agent

agent = create_agent(
    model="provider:model-name",
    tools=[search_kb, issue_refund],
    system_prompt="You are a support agent. Cite sources. Escalate if unsure.",
    middleware=[...],
    checkpointer=checkpointer,
)

result = agent.invoke(
    {"messages": [{"role": "user", "content": "How do I reset SSO?"}]},
    config={"configurable": {"thread_id": "t-42"}},
)
print(result["messages"][-1].content)

The parameters the docs name on the agent page are model, tools, system_prompt, middleware, response_format, state_schema, context_schema, checkpointer and name. A long-term store appears elsewhere in the docs (tools reach it through their runtime object), and you pass it when you build the agent.

Where middleware attaches

Middleware has two styles of hook, from the custom-middleware page:

  • Node-style hooks run in sequence at fixed points and may return updates to state: before_agent and after_agent (once per invocation), before_model and after_model (every model turn).
  • Wrap-style hooks surround a call and decide whether it runs: wrap_model_call around each model call and wrap_tool_call around each tool call. The wrapped handler can run zero times (to short-circuit), once (the normal case) or several times (a retry).
Diagram: One invocation starts with before_agent, then repeats a loop of before_model, the model call, after_model and any tool calls, and ends with...

yes

no

start

before_agent

before_model

wrap_model_call

after_model

tool calls?

wrap_tool_call

after_agent

end

Diagram summary: One invocation starts with before_agent, then repeats a loop of before_model, the model call, after_model and any tool calls, and ends with after_agent once the model stops asking for tools.

A hook can also exit early by returning a jump instruction (to the end, to the tools or back to the model), but it must declare which targets it may use.

JobHook that fitsWhy there
Load the user’s profile oncebefore_agentOnce per invocation, before anything runs
Trim or summarise historybefore_modelRuns before every model call, when the message list is about to be sent
Switch model, edit the request, retry a model callwrap_model_callCan change the request or run the call again
Authorise, retry or reshape the error of one toolwrap_tool_callSees each tool call and its result
Block a reply that leaks a secretafter_modelSees the model’s output before tools or the user do
Write an audit recordafter_agentRuns once at the end

Writing one is short. The decorator style fits a single hook, and a class fits several hooks or configuration.

Python

# Illustrative, adapted from the custom-middleware page.
from langchain.agents.middleware import before_model, hook_config, AgentState
from langgraph.runtime import Runtime

@before_model
@hook_config(can_jump_to=["end"])
def cap_history(state: AgentState, runtime: Runtime):
    if len(state["messages"]) > 20:
        return {"jump_to": "end"}
    return None

Built-in middleware

The built-in page lists these controls. Parameter names change, so use the table to know what exists and check the page for the rest.

ControlWhat it does
Model call limit, tool call limitCap calls per run or per thread; exit behaviour is configurable. A per-thread limit needs a checkpointer
Model retry, tool retryRetry with exponential backoff; the docs list a default of 2 retries
Model fallbackTry alternative models in order when the primary fails
SummarizationReplace older messages with a summary near a trigger, keeping recent ones
Context editingClear older tool outputs when the token limit is reached
Human in the loopPause tool calls for approve, edit or reject; the docs state it requires a checkpointer
PIIDetect and block, redact, mask or hash personal data in input, output or tool results
Tool errorTurn tool exceptions into error messages the model can read (the page gives a minimum version)
LLM tool selectorUse a model to pick relevant tools before the main call
To-do listAdd a planning tool for multi-step tasks
Shell and file searchGive the agent a persistent shell, or glob and grep tools. The shell does not work with interrupts

Deep Agents adds its own middleware for a virtual filesystem, a subagent delegation tool and a self-grading rubric. Those belong to the harness product, not to create_agent.

A shell tool deserves one extra line: it is a remote code execution surface. Run it in a sandbox, as the harness lesson on enforcement argues.

Ordering

With a list [m1, m2, m3], the docs give the order:

  • before_* hooks run first to last: m1, m2, m3.
  • wrap_* hooks nest like function calls: m1 is outermost and wraps m2, which wraps m3, which wraps the model or tool.
  • after_* hooks run last to first: m3, m2, m1.

So the first item in the list is the outermost layer. That decides behaviour:

  • A fallback outside a retry: the primary is retried first, then the next model is tried with its own retries. Swap them and the whole fallback sequence is retried as one unit. Both are legal and they cost differently. One default changes this: retry’s on_failure defaults to continue, which turns its final failure into a message, so a fallback outside it never sees an error unless you set on_failure="error" (tested on langchain 1.4.7, 2026-10-24).
  • A limit should count the calls you actually pay for. Whether it sits outside a retry decides whether retries count against it. Check the documented behaviour and test it.
  • Redaction has no single safe position. Listed first, PII middleware protects inputs from later hooks. Output redaction needs apply_to_output=True (default off) and runs at after_model, after every wrap hook has returned, so wrap-hook loggers and tracing callbacks still see the raw reply. Redact at the sink too, for example LangSmith’s input and output masking (tested on langchain 1.4.7, 2026-10-24).
  • Approval belongs on the tools that write or spend, not on every tool. Approving a search teaches people to click without reading.
Layout (outermost first)What happens when the primary model fails
Fallback, then retryThe primary is retried first, then the next model is tried with its own retries (with on_failure="error")
Retry, then fallbackThe whole fallback sequence is retried as one unit
Diagram: With middleware listed as m1, m2, m3, the before hooks run first to last, the wrap hooks nest with m1 outermost, and the after hooks run...

Coming out: after_* last to first

m3.after

m2.after

m1.after

wrap_*: nested, m1 outermost

m1 wraps

m2 wraps

m3 wraps

model or tool call

Going in: before_* first to last

m1.before

m2.before

m3.before

Diagram summary: With middleware listed as m1, m2, m3, the before hooks run first to last, the wrap hooks nest with m1 outermost, and the after hooks run last to first. The first item in the list is the outermost layer, which decides how retries, fallbacks and limits interact.

Python

# Illustrative: parameter names follow the built-in page, 2026-10-21.
agent = create_agent(
    model="provider:model-name",
    tools=[search_kb, issue_refund],
    middleware=[
        PIIMiddleware("email", strategy="redact", apply_to_output=True),
        ModelCallLimitMiddleware(run_limit=8),
        ToolRetryMiddleware(max_retries=2),
        SummarizationMiddleware(model="provider:small-model", trigger=("tokens", 6000), keep=("messages", 12)),
        HumanInTheLoopMiddleware(interrupt_on={"issue_refund": True}),
    ],
    checkpointer=checkpointer,
)

Read it as a design. Redact inputs first, and handle tracing separately. Cap model calls at eight per run so a loop ends. Retry failing tools twice. Summarise when history passes a token trigger. Pause only for the refund tool. The checkpointer is there because approval needs it.

Diagram: The example stack reads as a design in order.

Input

1 PII redaction

2 Model call limit: 8 per run

3 Tool retry: 2 retries

4 Summarisation near a token trigger

5 Human approval, only for issue_refund

Agent loop

Checkpointer: needed for approval

Diagram summary: The example stack reads as a design in order. Redact inputs first so later hooks do not see them (output redaction and tracing are handled separately), cap model calls so a loop ends, retry failing tools twice, summarise when history grows, and pause for a person only on the tool that spends money. Approval needs a checkpointer to pause and resume.

State, context and memory: four places

An agent has four places to keep things, and mixing them up is a frequent design error.

PlaceMechanismLives forUse for
StateThe agent’s state: messages, plus extra fields from a state_schemaOne thread, saved by the checkpointerA plan so far, counters, flags
Short-term memoryA checkpointer plus a thread_id in the run configOne conversationContinuity across turns
Runtime contextA context_schema, passed as context= on each callOne invocation, read-onlyUser id, tenant, locale
Long-term memoryA store with namespacesAcross threadsPreferences, learned facts

Python

# Illustrative, after the tools and short-term-memory pages.
from dataclasses import dataclass

@dataclass
class Ctx:
    user_id: str
    tenant: str

agent = create_agent(model, tools, context_schema=Ctx, checkpointer=checkpointer)
agent.invoke(
    {"messages": [{"role": "user", "content": "Where is my order?"}]},
    config={"configurable": {"thread_id": "t-42"}},
    context=Ctx(user_id="u1", tenant="acme"),
)

Three facts to hold on to. The docs say conversation history by thread_id requires a checkpointer; without one, each call starts blank. For production the docs suggest a database-backed saver, not the in-memory one used in examples. And runtime context is where identity belongs: it is the same hidden channel lesson 1 used for tools.

Diagram: The four places differ by how long they live.

Across threads

Long-term memory
store with namespaces

One thread (a conversation)

State and short-term memory
messages, plan, counters

One invocation

Runtime context
user id, tenant, locale, read-only

Diagram summary: The four places differ by how long they live. Runtime context lasts for one invocation and is read-only, state and short-term memory last for one thread and are saved by the checkpointer, and long-term memory lives in a store across threads.

Long conversations. History grows until it no longer fits. The docs show three moves: trim (keep the first message and the latest few), delete chosen messages, or summarise older ones with the built-in middleware. Each can lose something the agent needs. Summarising is also an extra model call, so a cost that rises after you enable it is a known suspect. Measure before and after; the context lesson gives the general method.

A memory write policy is a design, not a feature. Decide what gets written (facts a user stated, or things inferred), who can read it (one namespace per user or tenant), how it is corrected or deleted, and how stale entries are found. Do not store secrets or sensitive categories you cannot justify.

Streaming for the person waiting

Streaming does not shorten the work. It shortens the wait that people feel. The docs list modes passed as stream_mode:

  • updates: state changes after each step. Good for a progress line on a tool-heavy run.
  • messages: tokens from the model as they are generated. Good for chat.
  • custom: data your own code writes through a stream writer, for example a tool reporting “reading file 3 of 9”.
stream_modeWhat arrivesGood for
updatesState changes after each stepA progress line on a tool-heavy run
messagesModel tokens as they are generatedChat
customAnything your code writes through a stream writer“Reading file 3 of 9”

Pick by what the person needs to see. A long research run with a silent screen feels broken; a progress line feels alive.

Multi-agent patterns

The docs make a modest claim: multi-agent is optional, and a single agent with good tools and a good prompt often does the job. They name three reasons to go further: managing context, splitting development across teams, and running work in parallel. They name five patterns.

PatternHow it worksCost the docs call out
SubagentsA main agent calls specialist agents as tools; all routing goes through itAn extra model call per request; control stays central, and subagents can run in parallel
HandoffsControl moves between agents by tool call, driven by stateSequential, so weaker for tasks that span domains
SkillsOne agent loads specialised prompts and knowledge when neededLoaded text stays in context and is re-read on every later call
RouterA routing step classifies the input and sends it to one or more agentsStateless; every request pays a routing call
Custom workflowA LangGraph graph mixing fixed steps and agentsMore code
Diagram: In the subagent pattern a main agent calls specialists as tools and keeps control.

Router

Routing step classifies input

Agent X

Agent Y

Handoffs

tool call, driven by state

Agent 1

Agent 2

Agent 3

Subagents

Main agent

Specialist A

Specialist B

Diagram summary: In the subagent pattern a main agent calls specialists as tools and keeps control. In handoffs, control moves from one agent to the next by tool call, so it is sequential. In the router pattern a routing step classifies the input and sends it to one or more agents, paying a routing call on every request.

The design question underneath is context: what does each agent see? Starting with one agent and good tools, then splitting only when you can name the measured reason (context isolation, parallelism, independent evaluation), matches the guidance in multi-agent systems and the orchestration lesson.

Migrating pre-1.0 code

The migration page gives a short, concrete map. Where it gives no mapping, the table says to check.

OldNew or next step
create_react_agent from langgraph.prebuiltcreate_agent from langchain.agents
prompt=system_prompt= (a dynamic prompt uses a middleware)
pre_model_hook, post_model_hookbefore_model and after_model middleware
Summarising by handThe summarisation middleware
Tool approval by handThe human-in-the-loop middleware
Legacy chains such as LLMChain, older retrievers, the hublangchain-classic, as a bridge
AgentExecutor, memory classesNo mapping on the migration page; use create_agent, a checkpointer and the middleware above, and check the docs

A safe method: pin versions, write evaluations that capture current behaviour, port one chain at a time, compare traces and scores after each, then remove the bridge package.

Real-World Application

A support agent for ten tenants. Each tenant has its own documents and permissions. Identity (tenant, user) comes in as runtime context, read by tools and used to filter retrieval; the model never sees it as an argument. Short-term memory is a checkpointer keyed on a thread per conversation. A store holds each user’s stated preferences in a per-user namespace. The refund tool sits behind approval. A model-call limit ends loops; input redaction runs first, and output redaction and tracing are handled separately. The system starts as one agent. If the tool list grows past what the model chooses well, introduce a router, and only after an evaluation shows the single agent mis-choosing.

Interview Perspective

Expect: “Walk through one agent.invoke.”, “Where would you add a spend limit, redaction and refund approval?”, “What is the difference between state, memory and context?”, “Why did cost rise after you added summarisation?”, “How do you migrate an old agent?”

A strong answer names the hook for each control, says the first middleware is outermost, and says that approval and thread memory need a checkpointer. For the cost question, give hypotheses you can test from traces: the extra summary calls, an over-eager trigger, lost facts causing extra tool calls.

Common mistakes: one giant prompt where a limit or summariser belongs; approval without a checkpointer; no cap on model calls; letting the model choose the tenant; overlapping tool descriptions; thirty tools in one prompt; summarising away needed facts without a before-and-after evaluation.

Provenance: Common industry pattern. These are the questions this topic tends to draw for agent roles; none is verified for a named company.

Practice Questions

  • Basic: Name the four places an agent can keep information and one use for each.
  • Intermediate: Add tool retries, a cap of six model calls, email redaction and approval for refunds over a threshold. Which controls, in what order?
  • Advanced: Cost tripled after you enabled summarisation. Give three hypotheses and the trace evidence that would confirm each.
  • Product-Company: Design a support agent for ten tenants with per-tenant knowledge, memory and permissions.

Activity

Take one agent you know. Mark on the loop diagram where each of its controls lives today. For any control that is written into the prompt, move it to the hook where it belongs, and say what it can see there that it could not before.

Homework

Write a one-page design for an agent that must never email a customer without approval and must never spend more than a fixed amount per run. List the controls, the hook for each, the list order and why, what needs a checkpointer, and how you would test each control.

Quick Revision

  • The loop: call the model, run requested tools, repeat, stop when no tool is requested. It runs on LangGraph.
  • Node hooks: before_agent, before_model, after_model, after_agent. Wrap hooks: wrap_model_call, wrap_tool_call.
  • Order: before hooks first to last, wrap hooks nest with the first as outermost, after hooks last to first.
  • Approval and thread memory need a checkpointer.
  • Four places: state, short-term memory (checkpointer and thread), runtime context, long-term store.
  • Start with one agent. Split for a measured reason.
  • Migrate with pinned versions, evaluations and one port at a time.

Check yourself

  • Walk-through: Describe one invocation and name the hook for a call limit, redaction and refund approval.
  • Variation: Repeat it with a fallback model and a tool retry. Which wraps which?
  • Common misconception: “create_agent is just a prompt wrapper.” It builds a loop on a graph runtime, with persistence and approval available.

Resources & Further Reading

Checked sources to go deeper. The essential ones come first in each group.

Official documentation

Further reading

More for this module: LangChain ecosystem resources

Practice

Test what you just read. Quizzes and cards are grouped by module: LangChain ecosystem.

Check yourself12 questions on what this lesson set out to teach

Checking answers needs JavaScript. You can still read every question and option below.

0 of 12 answered

Keyboard: arrow keys move between options. Space or Enter selects the focused option.

ObjectiveTrace one create_agent call through the agent loop and name the middleware hook that fits a given job: limit, redaction, retry, summarising or approval.

  1. Question 1 of 12You need to stop an agent from making more than eight model calls in one run, so a loop cannot run away. Which approach fits the framework?

    Choose one answer.

  2. Question 2 of 12Which hook is the natural place to trim or summarise the message list before it is sent to the model on every turn?

    Choose one answer.

  3. Question 3 of 12A tool call fails once because of a network blip. Which hook can run the same tool call a second time, and what does the wrapped handler do?

    Choose one answer.

ObjectivePredict the order in which a list of middleware runs for before, wrap and after hooks, and place limits, retries, redaction and approval sensibly.

  1. Question 4 of 12An agent is built with middleware=[m1, m2, m3], each defining before_model, wrap_model_call and after_model. In what order do the three kinds of hook take effect?

    Choose one answer.

  2. Question 5 of 12Personal data must never reach logs, and a trace of each model call is stored. Where should the redaction middleware sit in the list?

    Choose one answer.

  3. Question 6 of 12A team wants human approval for every tool the agent can call, including read-only search. What is the main problem with that design?

    Choose one answer.

ObjectiveSeparate agent state, short-term memory, runtime context and long-term memory by lifetime and mechanism, and say which features need a checkpointer.

  1. Question 7 of 12Which feature of a create_agent agent needs a checkpointer? Select all that apply.

    Choose all that apply.

  2. Question 8 of 12A tool needs the current tenant to filter data. Where should the tenant value come from?

    Choose one answer.

  3. Question 9 of 12A user's stated language preference should apply in all of their future conversations. Where should the agent keep it?

    Choose one answer.

ObjectiveChoose between subagents, handoffs, skills, a router and a custom graph for a scenario, and justify starting with one agent.

  1. Question 10 of 12A support flow starts with a triage agent, then continues in a billing agent that keeps talking to the customer. Which pattern is closest?

    Choose one answer.

  2. Question 11 of 12A team plans five agents for a feature that has not shipped, because the diagram looks tidy. What is the best advice?

    Choose one answer.

ObjectiveMap pre-1.0 patterns to their 1.x replacements and describe a safe migration method.

  1. Question 12 of 12A legacy service calls langgraph.prebuilt.create_react_agent with prompt=..., pre_model_hook and a memory class. What is the safest first step in migrating it?

    Choose one answer.