Slides · LangChain ecosystem

Agents, middleware and memory

Agents, middleware and memory

Take the ready-made agent apart: the loop, the hooks where controls attach, the four places an agent keeps information, and when to split into several agents.

By the end you can trace one call through the loop, order middleware sensibly, place state by lifetime, choose a multi-agent pattern, and migrate pre-1.0 code safely.

Concept

Where does each check belong?

  • A simple job (look up, check, act) has its checks tangled into the job itself, and one failing check fails everything.
  • A manager now wants a step counter before it starts, a second look at anything large, and a note of what was done at the end.
  • Each of those is a control that belongs around the model, not inside the prompt. A prompt is advice the model can miscount or ignore; code that runs around the model holds whatever the model does.
  • Middleware is how this framework lets you add such controls without rewriting the loop.

Concept

Mental model: a route with hooks on posts

  • Picture one job as a route with hooks on posts along it: before the job starts, before each trip to the model, around the trip, around each tool pickup, after the model answers, after the job ends.
  • Each check hangs on the post where it has what it needs: a trip counter before the model call, a second look around a heavy lift, a tally at the end.
  • The route repeats model-and-tool trips until the model stops asking for tools.

Diagram

What create_agent builds

Diagram: The agents page defines an agent as a model calling tools in a loop until the task is complete.

yes

no

User message, thread id

Call the model

Tools requested?

Run the tools

Add results to messages

Return final message

Diagram summary: The agents page defines an agent as a model calling tools in a loop until the task is complete. The release notes describe the loop as: call the model, run the tools it chose, and finish when it chooses none. Results are appended to the conversation and the model is called again.

Sources1 Agents (LangChain documentation)2 LangChain v1 release notes (LangChain documentation)

Code

The call and its parameters

Python

agent = create_agent(
    model="provider:model-name",
    tools=[search_kb, issue_refund],
    system_prompt="You are a support agent. Escalate if unsure.",
    middleware=[...],
    checkpointer=checkpointer,
)
result = agent.invoke(
    {"messages": [{"role": "user", "content": "How do I reset SSO?"}]},
    config={"configurable": {"thread_id": "t-42"}},
)

The agents page names model, tools, system_prompt, middleware, response_format, state_schema, context_schema, checkpointer and name. It does not list store, yet the installed create_agent (langchain 1.4.7, checked 2026-10-24) has a store parameter. Parameter names are the part most likely to move, so learn the shape and check the page for the rest.

Source1 Agents (LangChain documentation)

Compare

Two styles of hook

StyleHooksWhen they runCan do
Node-stylebefore_agent, after_agentonce per invocationread state, return updates
Node-stylebefore_model, after_modelevery model turnread state, return updates
Wrap-stylewrap_model_callaround each model callchange the request, retry, short-circuit
Wrap-stylewrap_tool_callaround each tool callauthorise, retry, reshape an error
  • A wrapped handler can be called zero times (short-circuit), once (normal) or several times (retry).
  • A node hook can also exit early by returning a jump target (end, tools or model) that it declared with can_jump_to.

Source3 Custom middleware (LangChain documentation)

Diagram

Where the hooks sit in one invocation

Diagram: One invocation starts with before_agent, then repeats before_model, the model call, after_model and any tool calls until the model asks for...

yes

no

before_agent (once)

before_model

wrap_model_call

after_model

Tool calls?

wrap_tool_call

after_agent (once)

Diagram summary: One invocation starts with before_agent, then repeats before_model, the model call, after_model and any tool calls until the model asks for none, and ends with after_agent once. Wrap hooks surround the model call and each tool call.

Source3 Custom middleware (LangChain documentation)

Compare

Pick the hook for the job

JobHook that fitsWhy there
Load the user’s profile oncebefore_agentonce, before anything runs
Trim or summarise historybefore_modelruns before every call, when the 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 a toolwrap_tool_callsees each call and its result
Block a reply that leaks a secretafter_modelsees output before tools or the user do
Write an audit recordafter_agentruns once at the end

Source3 Custom middleware (LangChain documentation)

Worked example

Worked example: how often does each hook run

A scripted model asks for one tool on its first reply, then answers. One middleware class logs every hook. Run on langchain 1.4.7, 2026-10-24.

HookTimes it ranReason
before_agent, after_agent1 eachonce per invocation
before_model, wrap_model_call, after_model2 eachtwo model turns: ask for the tool, then answer
wrap_tool_call1one tool call
  • The model ran twice because a tool result must be shown to it before it can finish.
  • Counting hooks is how you know where a cap or a log line will actually fire.

Check yourself

Check: count the hook runs

In one invocation the model answers three times. Its first reply requests two tools at once, its second reply requests one tool, and its third reply is a final answer. How many times does each of before_agent, before_model, wrap_tool_call and after_agent run?

Answer

before_agent 1, before_model 3 (once per model call), wrap_tool_call 3 (once per tool call, so 2 + 1), after_agent 1. This was checked by running a scripted model: the hooks ran 1, 3, 3 and 1 times.

Compare

Built-in controls

ControlWhat it doesNote from the page
Model and tool call limitsCap calls per run or per threadthread_limit needs a checkpointer
Model and tool retryExponential backoffdefault max_retries is 2
Model fallbackTry other models in ordertakes a first model plus more
SummarizationReplace old messages with a summaryno automatic trigger unless one is set
Human in the loopPause tool calls for a personrequires a checkpointer
PIIBlock, redact, mask or hash personal datastrategy defaults to redact; output and tool results are not covered unless apply_to_output and apply_to_tool_results are set (both default off)
Context editing, tool selector, to-do list, shellClear old tool output, pick tools, plan, run commandsthe shell’s default policy runs with full host access; the page lists Docker and sandbox policies
  • Parameter names change, so use the table to learn what exists and read the page for the rest.

Source4 Built-in middleware (LangChain documentation)

Worked example

Defaults that surprise, tested

Scripted models on langchain 1.4.7 (2026-10-24).

SettingWhat happened
ToolRetryMiddleware(max_retries=2) on a tool that fails twicetool executed 3 times; the model was called twice and saw “ok”
Same, max_retries=1, tool always failsexecuted 2 times; the model received a failure message after 2 attempts
ModelCallLimitMiddleware(run_limit=3), model keeps asking for toolsexactly 3 model calls, then a “limit exceeded” message
SummarizationMiddleware with no trigger, 8 turns0 summary calls; 15 messages sent on the last call
Same with trigger=("messages", 10), keep=("messages", 4)1 summary call; 9 messages sent on the last call
  • max_retries counts retries after the first attempt, so the tool ran retries plus one times.
  • A summariser with no trigger is installed but never fires.

Source4 Built-in middleware (LangChain documentation)

Concept

The order rule: first in the list is outermost

  • With [m1, m2, m3], the custom-middleware page gives: before_* hooks run first to last, wrap_* hooks nest with the first middleware wrapping all others, and after_* hooks run last to first.
  • So list position means outer to inner, not a top-to-bottom script.
  • That decides how controls interact: whether a limit counts retries depends on whether it wraps them, and redaction has no single safe position (next slide).
  • Rules of thumb: approve only tools that write, spend or send; test any order you rely on.
  • Redaction: input redaction first protects later hooks; output redaction and tracing need separate handling (next slide).

Source3 Custom middleware (LangChain documentation)

Worked example

Worked example: where does redaction go?

Email redaction with apply_to_output=True, plus a logging middleware that records at before_model, wrap_model_call and after_model. The model’s reply contains an email. Without apply_to_output=True (default off, as is apply_to_tool_results) the final answer was “contact bob@corp.com now”: the reply is not redacted at all.

Logger recordPII first, then loggerLogger first, then PII
before_model inputredactedraw
wrap requestredactedredacted
wrap responseraw replyraw reply
after_model outputraw replyredacted
Final answer to userredactedredacted
  • Measured on langchain 1.4.7, 2026-10-24, with a scripted model. The user always sees redacted text; the leak is in what gets stored.
  • Input redaction listed first protects every later hook’s input. Output redaction runs at after_model, after all wrap hooks have returned, so a wrap-hook logger always sees the raw reply. Only an after_model logger listed before PII sees redacted output.
  • A tracing callback is not safe either: in a test it recorded the raw reply and the raw invocation input. Redact at the sink as well, for example LangSmith’s input and output masking or an anonymizer.

Sources4 Built-in middleware (LangChain documentation)5 Prevent logging of sensitive data in traces (LangSmith documentation)

Worked example

Worked example: two middleware, one model turn

Measured with [m1, m2], both defining every hook (the model turn only, before any tool).

StepOrder observed
Startm1.before_agent, m2.before_agent
Before the callm1.before_model, m2.before_model
Around the callm1.wrap in, m2.wrap in, the model runs, m2.wrap out, m1.wrap out
After the callm2.after_model, m1.after_model
Endm2.after_agent, m1.after_agent
  • Before hooks go first to last, wraps nest, after hooks go last to first, exactly as documented.

Source3 Custom middleware (LangChain documentation)

Worked example

Worked example: fallback and retry, order and defaults

Primary model always fails. The backup model works. Retry has max_retries=2. Counts are model calls.

List order (outermost first)Retry on_failurePrimary callsBackup callsUser gets
fallback, retrydefault (continue)30“failed after 3 attempts” message
fallback, retryerror31the backup’s answer
retry, fallbackdefault11the backup’s answer
  • With the default, the inner retry turns its final failure into a message, so a fallback outside it never sees an error.
  • Run on langchain 1.4.7 with scripted models. The built-in page lists on_failure with a default of continue and, for tools, advises placing retry inner (later in the list) with on_failure="error" so exceptions reach the error handler; it gives no model-retry versus fallback advice, so that interaction comes from the test.

Source4 Built-in middleware (LangChain documentation)

Check yourself

Check: predict the calls

The list is [fallback, retry]. Retry has max_retries=3 and its default on_failure. The primary model is down and the backup is healthy. How many primary calls and backup calls happen, and what does the user get? What one setting change would let the backup answer?

Answer

4 primary calls (1 attempt + 3 retries), 0 backup calls, and a “failed after 4 attempts” message. Setting retry’s on_failure to error lets the exception reach the fallback: the test gave 4 primary calls, then 1 backup call and the backup’s answer. Placing retry outside the fallback also works but changes the cost pattern.

Worked example

Approval needs somewhere to wait

Human-in-the-loop pauses a tool call for a person. The built-in page says it requires a checkpointer, and a test shows why.

Setup (scripted model asks for issue_refund)Result
Approval on issue_refund, no checkpointerthe first call returns an interrupt
Same, then resume with an approve decisionRuntimeError: Cannot use Command(resume=...) without checkpointer
Same with InMemorySaver, then approvethe tool runs: “refunded 900”
  • The pause itself does not fail without a checkpointer; the resume does, which makes the gap easy to miss in a demo.
  • Approve only the tools that write, spend or send. Approving a search teaches reviewers to click without reading.

Source4 Built-in middleware (LangChain documentation)

Compare

State, memory and context: four places

PlaceMechanismLives forUse for
Statemessages plus fields from state_schemaone thread, saved by the checkpointerplan so far, counters, flags
Short-term memorycheckpointer plus thread_id in the configone conversationcontinuity across turns
Runtime contextcontext_schema, passed as context= per callone invocation, read-onlyuser id, tenant, locale
Long-term memorya store with namespacesacross threadspreferences, learned facts
  • The memory page says to pass a checkpointer to get thread memory and advises a database-backed one for production, with a Postgres saver as its example.
  • The tools page lists state, context and store as what a tool’s runtime carries.

Sources6 Short-term memory (LangChain documentation)7 Tools (LangChain documentation)1 Agents (LangChain documentation)

Diagram

Four places by lifetime

Diagram: The places differ by how long they live.

Runtime context
one invocation, read-only

State and short-term memory
one thread

Long-term memory
across threads

Diagram summary: The 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 that outlasts any thread.

Worked example

Worked example: what a thread id does

Scripted model, two calls with the same thread_id, counting messages the model saw on the second call.

SetupMessages seen on call 2
No checkpointer1 (only the new message)
InMemorySaver, same thread_id3 (first question, first answer, new question)
Two different users sent to the same thread_idthe second user’s call included the first user’s message
  • Without a checkpointer each call starts blank.
  • A thread id shared across users merges their histories. Derive it from an authenticated conversation, never from something a user can guess or choose.

Source6 Short-term memory (LangChain documentation)

Check yourself

Check: whose history is this?

A web handler builds thread_id from the customer’s first name. Two customers named Sam open chats an hour apart. What happens, and what is the fix?

Answer

Both chats use the same thread, so the second Sam’s model call receives the first Sam’s messages, a privacy leak and a quality bug; the test above showed exactly this merge for two users on one id. Build the thread id from an authenticated conversation or session id, and pass the customer through runtime context for tools that need identity.

Concept

Long conversations and the memory write policy

  • History grows until it stops fitting. The memory page shows 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, and the page warns that the remaining history must stay valid for the provider, for example tool calls kept paired with their results.
  • Summarising is an extra model call, so a cost that rises after you enable it is a known suspect; measure before and after.
  • A memory write policy is a design decision: what gets written (stated facts or inferred ones), one namespace per user or tenant, how entries are corrected or deleted, and how stale ones are found. Do not store secrets or sensitive data you cannot justify.

Sources6 Short-term memory (LangChain documentation)4 Built-in middleware (LangChain documentation)

Compare

Five multi-agent patterns

The multi-agent page says not every complex task needs several agents: a single agent with good tools and a good prompt can often match one. It names context management, distributed development and parallelisation as the reasons to go further.

PatternHow it worksCost the page calls out
Subagentsa main agent calls specialists as toolsan extra model call; control stays central
Handoffsagents pass control by tool call, driven by statesequential, so weak across domains
Skillsone agent loads specialist prompts on demandloaded text stays in context for later calls
Routera routing step classifies and dispatchesstateless; a routing call every request
Custom workflowa LangGraph graph mixing steps and agentsmore code (this deck’s judgment)

Source8 Multi-agent (LangChain documentation)

Diagram

Who answers the user: subagents versus handoffs

Diagram: In the subagent pattern the main agent calls the specialist as a tool, gets the result back and answers, so control stays central.
SpecialistMain or first agentUserSpecialistMain or first agentUseralt[Subagents][Handoffs]requestcall as a toolresultanswerrequesthand off controlanswer directly
Diagram summary: In the subagent pattern the main agent calls the specialist as a tool, gets the result back and answers, so control stays central. In a handoff, control passes to the specialist, which then talks to the user directly. A router differs again: a routing step classifies each request and dispatches it, paying a routing call every time.

Source8 Multi-agent (LangChain documentation)

Worked example

Worked example: model calls in the page’s own scenario

The page gives call counts for a one-shot request and for the same kind of request repeated on turn 2.

PatternTurn 1 callsTurn 2 callsTwo-turn total
Subagents448
Handoffs325
Skills325
Router336
  • 4+4=84 + 4 = 8, 3+2=53 + 2 = 5 and 3+3=63 + 3 = 6. Subagents cost 3 more calls than handoffs over two turns in that scenario.
  • These are the page’s illustrative figures for its example, not a law. Measure your own.
  • Calls are not the only cost: the page also notes that subagents suit parallel or large-context work.

Source8 Multi-agent (LangChain documentation)

Check yourself

Check: price a pattern from the page’s figures

A product answers 1,000 requests a day. Using the multi-agent page’s one-shot call counts (subagents 4, handoffs 3, skills 3, router 3), how many more model calls a day does the subagent design make than the router design if every request is one-shot? Name one reason the subagent design might still be chosen.

Answer

(4−3)×1,000=1,000(4 - 3) \times 1{,}000 = 1{,}000 extra model calls a day. These are the page’s figures for its own example scenario, so measure your own. Subagents may still win because the page says they suit parallel or large-context work and keep control central, which can matter more than one extra call.

Source8 Multi-agent (LangChain documentation)

Compare

Migrating pre-1.0 code: the map

OldNew or next step
create_react_agent from langgraph.prebuiltcreate_agent from langchain.agents
prompt=system_prompt=
prompt= as a callablea dynamic-prompt middleware
pre_model_hookbefore_model middleware
state_modifier (the older name of prompt)system_prompt= for a string, a dynamic-prompt middleware for a callable
post_model_hookafter_model middleware
Legacy chains such as LLMChain, retrievers, the hublangchain-classic, as a bridge
AgentExecutor, memory classesthe migration page gives no mapping
  • The page also says pre-bound models are no longer accepted by create_agent, agent state must be a typed dict based on AgentState, and the streamed node name agent is now model.

Source9 Migrate to LangChain v1 (LangChain documentation)

Process

A safe migration method

  1. Pin the versions you run today.
  2. Write evaluations that capture current behaviour on real tasks, before touching code.
  3. Port one chain or agent at a time.
  4. Compare traces and scores after each port.
  5. Remove the langchain-classic bridge only when nothing imports it.
  • A single large change gives no baseline, and any difference in behaviour is hard to trace.
  • Where the page has no mapping (AgentExecutor, memory classes), build the new version from create_agent, a checkpointer and middleware, and verify against your evaluations.

Check yourself

Check: translate three old lines

An old service passes state_modifier=trim_fn, post_model_hook=redact_fn and prompt=build_prompt (a function of the state). Where does each go in the 1.x style, and which one needs care about when it runs?

Answer

post_model_hook becomes an after_model middleware and a callable prompt becomes a dynamic-prompt middleware (per the migration page). state_modifier was the older name of prompt in langgraph (checked in the 0.2.70 source), so trim_fn changed only what the model saw. Moving it into before_model with message removal would delete history from the saved state, a behaviour change; to keep the old behaviour, trim inside wrap_model_call. The ordering care is for redact_fn: after-hooks run last to first, so its place in the middleware list decides what runs before it. Port one at a time and compare traces after each.

Summary

Recap

  • The loop: call the model, run the tools it asks for, repeat, stop when none is requested. It runs on LangGraph.
  • Node hooks (before_agent, before_model, after_model, after_agent) and wrap hooks (wrap_model_call, wrap_tool_call); the first middleware in the list is outermost.
  • Check defaults by test: retry counts retries, a summariser needs a trigger, and a retry that swallows its final error hides failures from a fallback.
  • Approval and thread memory need a checkpointer. Thread ids must never be shared between users.
  • Four places: state, short-term memory, 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.

References

References & Sources (1 of 2)

  1. Agents (LangChain documentation) (opens in a new tab)

    LangChain2026Documentation

    Used for The agent definition, the create_agent parameters the page names, and that store is not listed there.

  2. LangChain v1 release notes (LangChain documentation) (opens in a new tab)

    LangChain2026Documentation

    Used for The basic agent loop of calling the model, running chosen tools and finishing when none is chosen.

  3. Custom middleware (LangChain documentation) (opens in a new tab)

    LangChain2026Documentation

    Used for Node-style and wrap-style hooks, the execution order for several middleware, early exit and how many times a wrapped handler can run.

  4. Built-in middleware (LangChain documentation) (opens in a new tab)

    LangChain2026Documentation

    Used for Built-in middleware names, defaults such as max_retries, which controls need a checkpointer, and the summarisation trigger.

  5. Prevent logging of sensitive data in traces (LangSmith documentation) (opens in a new tab)

    LangChain2026Documentation

    Used for Masking inputs and outputs, and anonymizers, at the tracing sink.

References

References & Sources (2 of 2)

  1. Short-term memory (LangChain documentation) (opens in a new tab)

    LangChain2026Documentation

    Used for Checkpointer and thread_id for short-term memory, the production saver advice, and trimming, deleting and summarising messages.

  2. Tools (LangChain documentation) (opens in a new tab)

    LangChain2026Documentation

    Used for What a tool's runtime carries: state, context, store and the call id.

  3. Multi-agent (LangChain documentation) (opens in a new tab)

    LangChain2026Documentation

    Used for When multi-agent is worth it, the five patterns, their costs and the call counts for the example scenario.

  4. Migrate to LangChain v1 (LangChain documentation) (opens in a new tab)

    LangChain2026Documentation

    Used for The map from create_react_agent, prompt, the hooks and legacy chains to the 1.x style, and the items it does not cover.