LangChain 1.5 middleware explained: hooks, limits, tool errors and the new routers
LangChain 1.5 adds two beta middlewares, a model router and an auto mode risk check, on top of the middleware system that now shapes every create_agent agent. This guide runs the whole stack offline with a scripted model and shows what each hook does.
- Reading time
- 15 min
- Sections
- 8
- Code examples
- 7
- Tables
- 1
- Sources
- 6
- Published
- 23 Nov 2026
- What changed
- LangChain 1.5.0 adds a model router and an auto mode check
- Why it matters
- The middleware list is now the real specification of a LangChain agent.
- What to do
- Pin the versions
LangChain's agent story is now one function, create_agent, plus a list of middleware. The function builds a small LangGraph graph: a model node, a tools node and the loop between them. Middleware is how you change that loop without rewriting it. You add a retry here, a call limit there, a human approval step before a risky tool.
LangChain 1.5.0 shipped on PyPI on 11 November 2026 and the current patch is 1.5.2. Comparing the middleware exports of 1.4.10 and 1.5.2 shows exactly two new classes: ModelRouterMiddleware and AutoModeMiddleware. Both are marked beta, and both are built on the langchain_core.decisions module for "decision models" that return probabilities instead of text.
This article explains how the middleware system works, runs a complete agent offline with a scripted fake model, and shows the trace each hook produces. Every code sample here was run against langchain==1.5.2 and langchain-core==1.8.4 on Python 3.13.
What happened
LangChain 1.5.0 adds a model router and an auto mode check (11 November 2026)
The 1.5.0 release added ModelRouterMiddleware, which classifies the latest user message once per run and picks a model from a set of named ModelChoice options, and AutoModeMiddleware, which asks a decision model whether each call to a listed tool is risky. Calls with a risk probability of 0.5 or more are blocked and returned to the model as an error ToolMessage. Both docstrings carry the warning "This middleware is in beta. Its API may change without notice."
LangChain 1.5.1 and 1.5.2 patch releases (18 November 2026)
Two patch releases landed on the same day. We did not audit their individual fixes; what we checked is that the public middleware list in 1.5.2 differs from 1.4.10 only by the two beta additions above.
langchain-core 1.8.4 (19 November 2026)
The newest core package, installed alongside langchain 1.5.2 in our tests, is 1.8.4. It contains the decisions module, with BaseDecisionModel, the question types Noul, Choice, Score and Box, and their typed answers.
How create_agent and middleware fit together
Think of create_agent as a factory assembly line with fixed stations: "call the model" and "run the tools". Middleware are inspectors you can place before, after or around a station. They do not replace the line; they watch it, change what passes through, or stop it.
There are two kinds of hooks.
Node-style hooks run as their own steps in the graph:
before_agentandafter_agentrun once per invocation.before_modelandafter_modelrun around every model call.
They receive the agent state (mainly messages) and a runtime. They can return a dict of state updates, or None to change nothing. With can_jump_to they can also jump to "model", "tools" or "end".
Wrap-style hooks wrap a call like a decorator:
wrap_model_call(request, handler)wraps each model call.wrap_tool_call(request, handler)wraps each tool execution.
You call handler(request) to run the real thing. You can call it zero times (block), once (observe or modify), or several times (retry).
Order matters. For wrap hooks, the first middleware in the list is the outermost layer, like the outer skin of an onion. Our trace below shows this: a logging wrapper placed after ToolErrorMiddleware never saw the result of a failing call, because the exception passed through it before the error middleware turned it into a message.
The built-in classes in 1.5.2 cover most production needs:
| Middleware | Hook type | What it does |
|---|---|---|
ModelCallLimitMiddleware |
before and after model | Stops after run_limit or thread_limit model calls |
ToolCallLimitMiddleware |
after model | Caps calls per tool or overall; default exit_behavior="continue" blocks extra calls |
ModelRetryMiddleware / ToolRetryMiddleware |
wrap | Retries with exponential backoff: defaults max_retries=2, initial_delay=1.0, backoff_factor=2.0, max_delay=60, jitter on |
ModelFallbackMiddleware |
wraps model | Tries alternative models in order on errors |
ToolErrorMiddleware |
wraps tools | Turns chosen exceptions into ToolMessage(status="error") |
SummarizationMiddleware |
before model | Summarises old messages when a trigger is hit; keeps the last 20 messages by default |
HumanInTheLoopMiddleware |
after model, wraps tools | Pauses for approve, edit, reject or respond decisions |
PIIMiddleware |
before and after | Detects email, credit card, IP, MAC address and URL; strategies block, redact, mask, hash |
ModelRouterMiddleware (beta) |
before agent, wraps model | Picks a model per run with a decision model |
AutoModeMiddleware (beta) |
wraps tools | Blocks tool calls a decision model rates as risky |
Running an agent offline with a scripted model
You do not need an API key to learn how the loop behaves. GenericFakeChatModel in langchain_core replays a list of messages. Real chat models implement bind_tools; the fake one does not, so we add a one-line subclass that returns itself.
pip install "langchain==1.5.2"
from langchain.agents import create_agent
from langchain.agents.middleware import (
ModelCallLimitMiddleware, ToolCallLimitMiddleware, ToolErrorMiddleware,
before_model, wrap_tool_call,
)
from langchain.tools import tool
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessage
class ScriptedModel(GenericFakeChatModel):
"""Replays scripted AIMessages; accepts tools like a real chat model."""
def bind_tools(self, tools, **kwargs):
return self
@tool
def lookup_order(order_id: str) -> str:
"""Look up the status of an order by its ID."""
if not order_id.startswith("A-"):
raise ValueError("unknown order id format")
return f"Order {order_id}: shipped on 2026-11-20, 2 items."
@before_model
def log_turn(state, runtime):
print(f"[before_model] messages so far: {len(state['messages'])}")
return None
@wrap_tool_call
def time_tool(request, handler):
print(f"[wrap_tool_call] -> {request.tool_call['name']}({request.tool_call['args']})")
result = handler(request)
print(f"[wrap_tool_call] <- status={getattr(result, 'status', '?')}")
return result
def on_error(exc, request):
if isinstance(exc, ValueError):
return f"{request.tool_call['name']} failed with ValueError; check the ID format (A-123)."
return None # anything else propagates and stops the run
script = [
AIMessage(content="", tool_calls=[{"name": "lookup_order", "args": {"order_id": "123"}, "id": "c1"}]),
AIMessage(content="", tool_calls=[{"name": "lookup_order", "args": {"order_id": "A-123"}, "id": "c2"}]),
AIMessage(content="Order A-123 shipped on 20 November with 2 items."),
]
agent = create_agent(
ScriptedModel(messages=iter(script)),
tools=[lookup_order],
system_prompt="You answer order questions. Use lookup_order.",
middleware=[
log_turn,
ModelCallLimitMiddleware(run_limit=5, exit_behavior="end"),
ToolCallLimitMiddleware(tool_name="lookup_order", run_limit=3),
ToolErrorMiddleware(on_error),
time_tool,
],
)
result = agent.invoke({"messages": [{"role": "user", "content": "Where is order 123?"}]})
for msg in result["messages"]:
extra = getattr(msg, "tool_calls", None) or getattr(msg, "status", "")
print(f"{type(msg).__name__:12} {str(msg.content)[:70]!r} {extra}")
The output, unedited:
[before_model] messages so far: 1
[wrap_tool_call] -> lookup_order({'order_id': '123'})
[before_model] messages so far: 3
[wrap_tool_call] -> lookup_order({'order_id': 'A-123'})
[wrap_tool_call] <- status=success
[before_model] messages so far: 5
HumanMessage 'Where is order 123?'
AIMessage '' [{'name': 'lookup_order', 'args': {'order_id': '123'}, 'id': 'c1', 'type': 'tool_call'}]
ToolMessage 'lookup_order failed with ValueError; check the ID format (A-123).' error
AIMessage '' [{'name': 'lookup_order', 'args': {'order_id': 'A-123'}, 'id': 'c2', 'type': 'tool_call'}]
ToolMessage 'Order A-123: shipped on 2026-11-20, 2 items.' success
AIMessage 'Order A-123 shipped on 20 November with 2 items.'
Read the trace step by step:
- Turn 1.
before_modelsees one message, the user question. The model asks forlookup_order("123"). - Tool step. The tool raises
ValueError.time_toolprinted the arrow in but never the arrow out, because the exception unwound through it.ToolErrorMiddleware, one layer further out, caught it and produced an errorToolMessage. - Turn 2. The model now sees three messages, including the error text, and retries with
A-123. This time both arrows print. - Turn 3. Five messages in context, and the model gives a final answer with no tool calls. The loop ends because the last AI message has no tool calls.
Three model calls, two tool calls. Both limits were far away.
What happens without the error middleware
Remove ToolErrorMiddleware and run the same script. On 1.5.2 the run does not continue: the ValueError propagates out of agent.invoke and you get a stack trace that ends "During task with name 'tools'". The docstring explains the design choice: handling is opt-in "so arbitrary internal exceptions are never serialized to the model or end user unless you choose to surface them". Argument validation errors are different. Those are caught earlier, by the tools node, and returned to the model as error messages before the tool even runs.
The practical rule: decide which exceptions are the model's problem (bad input it can fix) and which are yours (a database outage). Return a short, safe message for the first kind. Let the second kind fail loudly.
Hitting a limit on purpose
Set ModelCallLimitMiddleware(run_limit=1, exit_behavior="end") and give the model a script that needs two calls. The agent makes the first model call, runs the tool, and then, instead of calling the model again, ends with an AI message whose text is Model call limits exceeded: run limit (1/1). With exit_behavior="error" it raises instead. The "end" mode is friendlier for chat products; the "error" mode is better in batch jobs where you want a failed status.
Limits are the cheapest guardrail you can add. A model stuck in a loop of near-identical tool calls burns tokens on every turn because each turn re-sends the growing history. The agent loop token cost simulation shows how fast that grows.
Retries, fallbacks and the order of layers
Retries are where order matters most. The ToolErrorMiddleware docstring gives the recommended composition: put ToolRetryMiddleware inside the error middleware and set on_failure="error" on the retry, so that an exception still reaches the error handler after the last retry.
from langchain.agents.middleware import ToolRetryMiddleware
middleware = [
ToolErrorMiddleware(on_error), # outer: final translation
ToolRetryMiddleware(max_retries=2, on_failure="error"), # inner: retry first
]
A worked number for the default backoff: initial_delay=1.0, backoff_factor=2.0, max_retries=2. The tool is tried three times. The waits before attempts two and three are about 1 second and 2 seconds, plus random jitter of up to 25 percent either way. With max_retries=5 the waits would be 1, 2, 4, 8 and 16 seconds, 31 seconds in total before jitter, and every later wait would be capped at max_delay=60. That is fine for a flaky HTTP API and too slow for an interactive chat. The retries and exponential backoff simulation lets you change these values and see the timeline.
For models, ModelFallbackMiddleware("provider:model-a", "provider:model-b") tries other models in order when the primary fails. The ModelRefusalMiddleware, already present before 1.5, raises a ModelRefusalError when a response contains a standard refusal block; its docstring says to list it after ModelFallbackMiddleware so that the fallback can catch the error.
Continue learning
How this article connects
7 pages link to or from it. Drag to turn, click a dot to open it.
- LLM routing
- LangGraph
- Agentic AI frameworks explained: the Lang family and every major alterna
- LangSmith
- Agentic RAG explained: agents that decide when, where and how to retriev
- Tutorial: build a read-only SQL data agent with LangChain 1.5 and test i
- Agent memory explained: threads, long-term stores, trimming and summarie
The new decision models: router and auto mode
The two beta middlewares share one idea. Instead of asking a chat model for free text and parsing it, you ask a decision model a typed question and get a probability back.
langchain_core.decisions defines four question types:
Noul: a yes-or-no question answered with the probability of yes.Choice: pick one label; the answer keeps the full probability distribution and a confidence.Score: an expected level on a rubric.Box: a location in an image as fractions of height and width.
You implement a decision model by subclassing BaseDecisionModel and writing _classify(state, questions), which returns a ClassifierResponse.
AutoModeMiddleware wraps the tools you list. Before each listed tool runs, it sends the proposed call, the tool description and up to 30 recent messages to the classifier with a default question that starts "Would executing tool_call be risky or insufficiently authorized based on messages?" If the probability is 0.5 or more, the tool does not run and the model gets an error message. Unlisted tools skip the check. It blocks; it does not ask a human.
Here is a toy classifier that flags a few dangerous words. A real one would be a trained model.
import json
from langchain.agents.middleware import AutoModeMiddleware
from langchain_core.decisions import BaseDecisionModel, ClassifierResponse
class KeywordRiskModel(BaseDecisionModel):
model: str = "keyword-risk-v0"
@property
def _provider(self) -> str:
return "local"
def _classify(self, state, questions):
text = json.dumps(state, default=str).lower()
risky = any(w in text for w in ("delete", "drop", "rm -rf", "password"))
return ClassifierResponse(
model=self.model,
answers={q: {"type": "noul", "noul": 0.92 if risky else 0.04} for q in questions},
)
auto_mode = AutoModeMiddleware(tools=["run_shell"], classifier=KeywordRiskModel())
With a script that calls read_file, then run_shell("ls -la"), then run_shell("rm -rf build/"), the tool messages were:
read_file status=success 'contents of notes.txt: hello'
run_shell status=success 'ran: ls -la'
run_shell status=error 'The tool call `run_shell` was blocked because it was classified as risky (probability: 0.92). ...'
ModelRouterMiddleware classifies the latest human message once, before the run, stores the full ChoiceAnswer in state and uses the chosen model for every model call in that run. The docstring example routes between a "fast" and a "powerful" choice with the instruction "Choose the least costly model suited to the task." Classifier failures stop the run; it never silently falls back. The LLM routing page covers the trade-offs of routing in general.
What it means in practice
The middleware list is now the real specification of a LangChain agent. Two agents with the same model and tools can behave very differently: one stops after five model calls and tells the model about bad inputs, the other crashes on the first exception and loops forever on a confused model. Code review should treat the middleware list with the same care as the prompt.
The beta decision models point to a design trend: use small, cheap classifiers with explicit thresholds for control decisions, and keep the large model for reasoning. A probability is easier to log, alert on and tune than a paragraph of model text.
Middleware runs inside a LangGraph graph, so all of it shows up in LangSmith traces, and anything that pauses (human approval) needs a checkpointer. If you want the graph itself, not the factory, see the frameworks overview.
What to do now
- Pin the versions. Install
langchain==1.5.2and recordlangchain-core(1.8.4 at the time of writing) in your lock file; patch releases arrive often. - Add a model call limit to every agent. Start with
ModelCallLimitMiddleware(run_limit=15, exit_behavior="end")and tune from traces. - Decide your tool error policy. Write an
on_errorthat returns short, safe messages for input errors and returnsNonefor everything else. - Compose retries inside error handling. Use
ToolRetryMiddleware(on_failure="error")insideToolErrorMiddleware, and keep total backoff under your latency budget. - Test with a scripted model. Use
GenericFakeChatModelplus abind_toolsstub in unit tests so loop logic runs in CI without network calls. - Gate dangerous tools twice. Use
HumanInTheLoopMiddlewarefor irreversible actions and considerAutoModeMiddlewareas an automatic first filter, not a replacement. - Try routing on a copy. If you test
ModelRouterMiddleware, log the storedChoiceAnswerand compare cost and quality before and after. - Read middleware order out loud. Write a comment above the list that says which layer is outermost and why.
Risks and open questions
Beta means the API can move. Both new middlewares say their API may change without notice. Wrap them behind your own small adapter so a rename does not ripple through your code.
A classifier is a new failure point. Auto mode and the router both propagate classifier errors and stop the run. That is safe, but it means your classifier needs the same uptime and monitoring as your main model.
Thresholds are fixed in auto mode. The 0.5 cut-off is a constant in the 1.5.2 source. If your classifier is poorly calibrated, it will block too much or too little, and you cannot move the threshold without your own wrapper.
Keyword checks are not security. Our toy classifier is easy to dodge with r''m -rf. Real protection needs sandboxes and permissions, covered in the guardrails simulation.
Watch next: whether the decision-model interface leaves beta, which providers ship BaseDecisionModel implementations, and whether the threshold becomes configurable.
Frequently asked questions
Do I still need LangGraph if I use create_agent?
create_agent builds a LangGraph graph for you, so LangGraph is installed and running underneath. You need to write LangGraph directly only when your control flow is not a simple model-tools loop, such as fixed pipelines or several agents with shared state.
Which middleware runs first?
Node-style hooks such as before_model run in list order. Wrap-style hooks nest, with the first middleware in the list as the outermost layer. In our run, a logger listed after ToolErrorMiddleware did not see the result of the failing call.
Why did my agent crash on a tool exception?
In 1.5.2, exceptions raised inside a tool propagate unless you add ToolErrorMiddleware with an on_error that returns content. Validation errors on tool arguments are already turned into error messages before the tool runs.
Can I unit test an agent without an API key?
Yes. Subclass GenericFakeChatModel, add a bind_tools method that returns self, and pass a list of AIMessage objects with the tool calls you want. The full loop, including middleware, runs locally.
Is AutoModeMiddleware a replacement for human approval?
No. Its docstring says it blocks calls and does not request human approval. Use it to reduce how often a person is interrupted, and keep human approval for actions that cannot be undone.
Summary
LangChain 1.5 keeps the create_agent plus middleware design and adds two beta middlewares built on typed decision models: a router that picks a model per run and an auto mode that blocks risky tool calls when a classifier's probability reaches 0.5. The bigger lesson from running the stack offline is that middleware order and policy decide how an agent behaves under stress. Add call limits, choose which tool errors the model may see, nest retries inside error handling, test with a scripted model, and treat the new beta features as experiments behind your own adapter.
Sources
Cite this article
Kelahmet, Ö. C. (2026, November 23). LangChain 1.5 middleware explained: hooks, limits, tool errors and the new routers. Özer Cem KELAHMET. https://www.ozercemkelahmet.com/articles/langchain-1-5-agent-middleware-guide
BibTeX
@online{kelahmet2026langchain,
author = {Kelahmet, {\"O}zer Cem},
title = {{LangChain 1.5 middleware explained: hooks, limits, tool errors and the new routers}},
year = {2026},
month = {nov},
url = {https://www.ozercemkelahmet.com/articles/langchain-1-5-agent-middleware-guide}
}Version historyfirst version
- Published
Factual corrections are listed here with what changed. Wording and formatting edits are not listed.