Slides · LangChain ecosystem
Agents, middleware and memory
1 / 33
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
Sources[1] 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.
Compare
Two styles of hook
| Style | Hooks | When they run | Can do |
|---|---|---|---|
| Node-style | before_agent, after_agent | once per invocation | read state, return updates |
| Node-style | before_model, after_model | every model turn | read state, return updates |
| Wrap-style | wrap_model_call | around each model call | change the request, retry, short-circuit |
| Wrap-style | wrap_tool_call | around each tool call | authorise, 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,toolsormodel) that it declared withcan_jump_to.
Diagram
Where the hooks sit in one invocation
Compare
Pick the hook for the job
| Job | Hook that fits | Why there |
|---|---|---|
| Load the user’s profile once | before_agent | once, before anything runs |
| Trim or summarise history | before_model | runs before every call, when the list is about to be sent |
| Switch model, edit the request, retry a model call | wrap_model_call | can change the request or run the call again |
| Authorise, retry or reshape the error of a tool | wrap_tool_call | sees each call and its result |
| Block a reply that leaks a secret | after_model | sees output before tools or the user do |
| Write an audit record | after_agent | runs once at the end |
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.
| Hook | Times it ran | Reason |
|---|---|---|
before_agent, after_agent | 1 each | once per invocation |
before_model, wrap_model_call, after_model | 2 each | two model turns: ask for the tool, then answer |
wrap_tool_call | 1 | one 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
| Control | What it does | Note from the page |
|---|---|---|
| Model and tool call limits | Cap calls per run or per thread | thread_limit needs a checkpointer |
| Model and tool retry | Exponential backoff | default max_retries is 2 |
| Model fallback | Try other models in order | takes a first model plus more |
| Summarization | Replace old messages with a summary | no automatic trigger unless one is set |
| Human in the loop | Pause tool calls for a person | requires a checkpointer |
| PII | Block, redact, mask or hash personal data | strategy 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, shell | Clear old tool output, pick tools, plan, run commands | the 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.
Worked example
Defaults that surprise, tested
Scripted models on langchain 1.4.7 (2026-10-24).
| Setting | What happened |
|---|---|
ToolRetryMiddleware(max_retries=2) on a tool that fails twice | tool executed 3 times; the model was called twice and saw “ok” |
Same, max_retries=1, tool always fails | executed 2 times; the model received a failure message after 2 attempts |
ModelCallLimitMiddleware(run_limit=3), model keeps asking for tools | exactly 3 model calls, then a “limit exceeded” message |
SummarizationMiddleware with no trigger, 8 turns | 0 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_retriescounts retries after the first attempt, so the tool ran retries plus one times.- A summariser with no trigger is installed but never fires.
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, andafter_*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).
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 record | PII first, then logger | Logger first, then PII |
|---|---|---|
before_model input | redacted | raw |
| wrap request | redacted | redacted |
| wrap response | raw reply | raw reply |
after_model output | raw reply | redacted |
| Final answer to user | redacted | redacted |
- 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 anafter_modellogger 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.
Sources[4] 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).
| Step | Order observed |
|---|---|
| Start | m1.before_agent, m2.before_agent |
| Before the call | m1.before_model, m2.before_model |
| Around the call | m1.wrap in, m2.wrap in, the model runs, m2.wrap out, m1.wrap out |
| After the call | m2.after_model, m1.after_model |
| End | m2.after_agent, m1.after_agent |
- Before hooks go first to last, wraps nest, after hooks go last to first, exactly as documented.
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_failure | Primary calls | Backup calls | User gets |
|---|---|---|---|---|
| fallback, retry | default (continue) | 3 | 0 | “failed after 3 attempts” message |
| fallback, retry | error | 3 | 1 | the backup’s answer |
| retry, fallback | default | 1 | 1 | the 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_failurewith a default ofcontinueand, for tools, advises placing retry inner (later in the list) withon_failure="error"so exceptions reach the error handler; it gives no model-retry versus fallback advice, so that interaction comes from the test.
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 checkpointer | the first call returns an interrupt |
| Same, then resume with an approve decision | RuntimeError: Cannot use Command(resume=...) without checkpointer |
Same with InMemorySaver, then approve | the 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.
Compare
State, memory and context: four places
| Place | Mechanism | Lives for | Use for |
|---|---|---|---|
| State | messages plus fields from state_schema | one thread, saved by the checkpointer | plan so far, counters, flags |
| Short-term memory | checkpointer plus thread_id in the config | one conversation | continuity across turns |
| Runtime context | context_schema, passed as context= per call | one invocation, read-only | user id, tenant, locale |
| Long-term memory | a store with namespaces | across threads | preferences, 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.
Sources[6] Short-term memory (LangChain documentation)[7] Tools (LangChain documentation)[1] Agents (LangChain documentation)
Diagram
Four places by lifetime
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.
| Setup | Messages seen on call 2 |
|---|---|
| No checkpointer | 1 (only the new message) |
InMemorySaver, same thread_id | 3 (first question, first answer, new question) |
Two different users sent to the same thread_id | the 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.
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.
Sources[6] 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.
| Pattern | How it works | Cost the page calls out |
|---|---|---|
| Subagents | a main agent calls specialists as tools | an extra model call; control stays central |
| Handoffs | agents pass control by tool call, driven by state | sequential, so weak across domains |
| Skills | one agent loads specialist prompts on demand | loaded text stays in context for later calls |
| Router | a routing step classifies and dispatches | stateless; a routing call every request |
| Custom workflow | a LangGraph graph mixing steps and agents | more code (this deck’s judgment) |
Diagram
Who answers the user: subagents versus handoffs
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.
| Pattern | Turn 1 calls | Turn 2 calls | Two-turn total |
|---|---|---|---|
| Subagents | 4 | 4 | 8 |
| Handoffs | 3 | 2 | 5 |
| Skills | 3 | 2 | 5 |
| Router | 3 | 3 | 6 |
- 4+4=8, 3+2=5 and 3+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.
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 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.
Compare
Migrating pre-1.0 code: the map
| Old | New or next step |
|---|---|
create_react_agent from langgraph.prebuilt | create_agent from langchain.agents |
prompt= | system_prompt= |
prompt= as a callable | a dynamic-prompt middleware |
pre_model_hook | before_model middleware |
state_modifier (the older name of prompt) | system_prompt= for a string, a dynamic-prompt middleware for a callable |
post_model_hook | after_model middleware |
Legacy chains such as LLMChain, retrievers, the hub | langchain-classic, as a bridge |
AgentExecutor, memory classes | the 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 onAgentState, and the streamed node nameagentis nowmodel.
Process
A safe migration method
- Pin the versions you run today.
- Write evaluations that capture current behaviour on real tasks, before touching code.
- Port one chain or agent at a time.
- Compare traces and scores after each port.
- Remove the
langchain-classicbridge 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 fromcreate_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)
Agents (LangChain documentation) (opens in a new tab)
LangChain2026Documentation
https://docs.langchain.com/oss/python/langchain/agents
Used for The agent definition, the create_agent parameters the page names, and that store is not listed there.
LangChain v1 release notes (LangChain documentation) (opens in a new tab)
LangChain2026Documentation
https://docs.langchain.com/oss/python/releases/langchain-v1
Used for The basic agent loop of calling the model, running chosen tools and finishing when none is chosen.
Custom middleware (LangChain documentation) (opens in a new tab)
LangChain2026Documentation
https://docs.langchain.com/oss/python/langchain/middleware/custom
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.
Built-in middleware (LangChain documentation) (opens in a new tab)
LangChain2026Documentation
https://docs.langchain.com/oss/python/langchain/middleware/built-in
Used for Built-in middleware names, defaults such as max_retries, which controls need a checkpointer, and the summarisation trigger.
Prevent logging of sensitive data in traces (LangSmith documentation) (opens in a new tab)
LangChain2026Documentation
https://docs.langchain.com/langsmith/mask-inputs-outputs
Used for Masking inputs and outputs, and anonymizers, at the tracing sink.
References
References & Sources (2 of 2)
Short-term memory (LangChain documentation) (opens in a new tab)
LangChain2026Documentation
https://docs.langchain.com/oss/python/langchain/short-term-memory
Used for Checkpointer and thread_id for short-term memory, the production saver advice, and trimming, deleting and summarising messages.
Tools (LangChain documentation) (opens in a new tab)
LangChain2026Documentation
https://docs.langchain.com/oss/python/langchain/tools
Used for What a tool's runtime carries: state, context, store and the call id.
Multi-agent (LangChain documentation) (opens in a new tab)
LangChain2026Documentation
https://docs.langchain.com/oss/python/langchain/multi-agent
Used for When multi-agent is worth it, the five patterns, their costs and the call counts for the example scenario.
Migrate to LangChain v1 (LangChain documentation) (opens in a new tab)
LangChain2026Documentation
https://docs.langchain.com/oss/python/migrate/langchain-v1
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.
Keys: ← → move, Home End first and last, F full screen.