Agents, middleware and memory
- Advanced
- 40 min
- Lesson 2 of 7 in LangChain ecosystem
- Last verified
Select text in the lesson first to keep it with your note. With the keyboard, move focus here and press the button: the note goes with the section you are reading.
In this module
On this page
Before you start
- Completed:The LangChain map and Runnables
- Completed:Agentic patterns: ReAct, planning and memoryTools and agents
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.
# 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_agentandafter_agent(once per invocation),before_modelandafter_model(every model turn). - Wrap-style hooks surround a call and decide whether it runs:
wrap_model_callaround each model call andwrap_tool_callaround each tool call. The wrapped handler can run zero times (to short-circuit), once (the normal case) or several times (a retry).
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.
| Job | Hook that fits | Why there |
|---|---|---|
| Load the user’s profile once | before_agent | Once per invocation, before anything runs |
| Trim or summarise history | before_model | Runs before every model call, when the message 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 one tool | wrap_tool_call | Sees each tool call and its result |
| Block a reply that leaks a secret | after_model | Sees the model’s output before tools or the user do |
| Write an audit record | after_agent | Runs once at the end |
Writing one is short. The decorator style fits a single hook, and a class fits several hooks or configuration.
# 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 NoneBuilt-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.
| Control | What it does |
|---|---|
| Model call limit, tool call limit | Cap calls per run or per thread; exit behaviour is configurable. A per-thread limit needs a checkpointer |
| Model retry, tool retry | Retry with exponential backoff; the docs list a default of 2 retries |
| Model fallback | Try alternative models in order when the primary fails |
| Summarization | Replace older messages with a summary near a trigger, keeping recent ones |
| Context editing | Clear older tool outputs when the token limit is reached |
| Human in the loop | Pause tool calls for approve, edit or reject; the docs state it requires a checkpointer |
| PII | Detect and block, redact, mask or hash personal data in input, output or tool results |
| Tool error | Turn tool exceptions into error messages the model can read (the page gives a minimum version) |
| LLM tool selector | Use a model to pick relevant tools before the main call |
| To-do list | Add a planning tool for multi-step tasks |
| Shell and file search | Give 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_failuredefaults tocontinue, which turns its final failure into a message, so a fallback outside it never sees an error unless you seton_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 atafter_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 retry | The primary is retried first, then the next model is tried with its own retries (with on_failure="error") |
| Retry, then fallback | The whole fallback sequence is retried as one unit |
# 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.
State, context and memory: four places
An agent has four places to keep things, and mixing them up is a frequent design error.
| Place | Mechanism | Lives for | Use for |
|---|---|---|---|
| State | The agent’s state: messages, plus extra fields from a state_schema | One thread, saved by the checkpointer | A plan so far, counters, flags |
| Short-term memory | A checkpointer plus a thread_id in the run config | One conversation | Continuity across turns |
| Runtime context | A context_schema, passed as context= on each call | One invocation, read-only | User id, tenant, locale |
| Long-term memory | A store with namespaces | Across threads | Preferences, learned facts |
# 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.
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_mode | What arrives | Good for |
|---|---|---|
updates | State changes after each step | A progress line on a tool-heavy run |
messages | Model tokens as they are generated | Chat |
custom | Anything 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.
| Pattern | How it works | Cost the docs call out |
|---|---|---|
| Subagents | A main agent calls specialist agents as tools; all routing goes through it | An extra model call per request; control stays central, and subagents can run in parallel |
| Handoffs | Control moves between agents by tool call, driven by state | Sequential, so weaker for tasks that span domains |
| Skills | One agent loads specialised prompts and knowledge when needed | Loaded text stays in context and is re-read on every later call |
| Router | A routing step classifies the input and sends it to one or more agents | Stateless; every request pays a routing call |
| Custom workflow | A LangGraph graph mixing fixed steps and agents | More code |
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.
| Old | New or next step |
|---|---|
create_react_agent from langgraph.prebuilt | create_agent from langchain.agents |
prompt= | system_prompt= (a dynamic prompt uses a middleware) |
pre_model_hook, post_model_hook | before_model and after_model middleware |
| Summarising by hand | The summarisation middleware |
| Tool approval by hand | The human-in-the-loop middleware |
Legacy chains such as LLMChain, older retrievers, the hub | langchain-classic, as a bridge |
AgentExecutor, memory classes | No 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_agentis just a prompt wrapper.” It builds a loop on a graph runtime, with persistence and approval available.
Related
Resources & Further Reading
Checked sources to go deeper. The essential ones come first in each group.
Official documentation
Middleware overview (LangChain documentation) (opens in a new tab)Essential
A short overview of what middleware is for, read before the built-in and custom pages.
Memory overview (LangGraph documentation) (opens in a new tab)
Separates short-term from long-term memory in the runtime that create_agent uses, which is the basis of the four places.
Further reading
Context Engineering (opens in a new tab)
A broader view of what each agent or step should see, the design question beneath trimming, summarising and splitting.
Building effective agents (opens in a new tab)
Supports the advice to start with one agent and add structure only when it is measured to help.
Timeouts, retries, and backoff with jitter (opens in a new tab)
The reasoning behind backoff with jitter and the warning about retrying side effects, relevant to the retry and fallback controls.
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.
Keyboard: arrow keys move between options. Space or Enter selects the focused option.