LangChain Middleware API reference
In LangChain 1.x, Middleware is an important mechanism for extending Agent behavior.
Through Middleware, developers can execute custom code before or after model calls, control tool calls, adjust system prompts, log, handle exceptions, and even modify the Agent's execution flow.
For example, an intelligent customer-service Agent can use Middleware to:
- Check user input before the model call.
- Dynamically adjust available tools based on user identity.
- Set retries or a backup model for model calls.
- Log the time spent on model and tool calls.
- Check permissions when performing sensitive operations.
- Process the final answer after the Agent completes.
This section is based on LangChain 1.x and organizes AgentMiddleware the base class, all major Hooks, decorator parameters, ModelRequest, ModelResponse, ExtendedModelResponse, as well as Middleware execution order and state update methods.
I. How Middleware works
The execution process of a normal LangChain Agent is as follows:
用户消息
↓
调用模型
↓
是否需要工具?
├── 否 → 返回回答
└── 是 → 执行工具 → 再次调用模型
After adding Middleware, the flow becomes:
用户消息
↓
before_agent
↓
before_model
↓
wrap_model_call
↓
调用模型
↓
after_model
↓
是否需要工具?
├── 是
│ ↓
│ wrap_tool_call
│ ↓
│ 执行工具
│ ↓
│ 返回 before_model
│
└── 否
↓
after_agent
↓
返回结果
This is a simplified execution flow diagram; actual execution is also affected by configurations such as Middleware jumps, interrupts, structured output, and error handling.
There are two main types of Middleware:
| Type | Purpose | Common Scenarios |
|---|---|---|
| Node-style Hooks | Run logic before and after execution nodes | Checks, logging, state updates |
| Wrap-style Hooks | Wrap model or tool calls | Retries, exception handling, request modification |
II. AgentMiddleware base class
AgentMiddleware is the base class for custom Middleware.
Developers can inherit from it and override the Hooks they need.
from langchain.agents.middleware import AgentMiddleware
class MyMiddleware(AgentMiddleware):
def before_model(self, state, runtime):
return None
A Middleware does not need to implement all Hooks; it only needs to implement the methods actually used.
Main attributes of AgentMiddleware
| property | Description |
|---|---|
name |
The name of the Middleware |
state_schema |
Declare additional state fields |
tools |
Tools registered with the Middleware |
transformers |
Additional stream event transformers |
trace_policy |
Control the trace data recording policy of Middleware Hooks |
Among these, transformers and trace_policy are newer extension capabilities; note the actually installed LangChain version when using them.
III. All major Hooks of AgentMiddleware
AgentMiddleware provides synchronous and asynchronous Hooks.
| Hook | Function parameters | Execution Timing | Return Value |
|---|---|---|---|
before_agent |
state, runtime | Before the Agent starts | dict / Command / None |
abefore_agent |
state, runtime | Async before start | dict / Command / None |
before_model |
state, runtime | Before each model call | dict / Command / None |
abefore_model |
state, runtime | Async before model call | dict / Command / None |
wrap_model_call |
request, handler | Wrap model call | ModelCallResult |
awrap_model_call |
request, handler | Wrap async model call | ModelCallResult |
after_model |
state, runtime | After each model reply | dict / Command / None |
aafter_model |
state, runtime | Async after model reply | dict / Command / None |
wrap_tool_call |
request, handler | Wrap tool call | ToolMessage / Command |
awrap_tool_call |
request, handler | Wrap async tool call | ToolMessage / Command |
after_agent |
state, runtime | After the Agent ends normally | dict / Command / None |
aafter_agent |
state, runtime | Async after Agent ends | dict / Command / None |
Where:
before_agentandafter_agentLocated at the periphery of the Agent execution cycle.before_modelandafter_modelExecuted along with the model call loop, may run multiple times.wrap_model_callWrap the model request.wrap_tool_callWrap each tool execution.
**Note:** Synchronous and asynchronous Hooks need to be implemented correctly according to the execution mode. If a custom Middleware implements only synchronous logic, you should not directly assume all asynchronous operations will adapt automatically.
IV. Middleware decorator overview
Besides inheriting from AgentMiddleware, you can also create Middleware directly using decorators.
Decorators are more suitable for scenarios with relatively simple logic that need only a single Hook.
| Decorator | Main configuration parameters | Purpose |
|---|---|---|
@before_agent |
state_schema, tools, can_jump_to, name | Execute before the Agent starts |
@after_agent |
state_schema, tools, can_jump_to, name | Execute after the Agent ends |
@before_model |
state_schema, tools, can_jump_to, name | Execute before the model call |
@after_model |
state_schema, tools, can_jump_to, name | Execute after the model call |
@wrap_model_call |
state_schema, tools, name | Wrap model call |
@wrap_tool_call |
state_schema, tools, name | Wrap tool call |
@dynamic_prompt |
Dynamic prompt-related configuration | Generate the system prompt for the current model request |
@hook_config |
can_jump_to | Configure jump behavior for class-style Hooks |
Common import methods:
from langchain.agents.middleware import (
AgentMiddleware,
before_agent,
after_agent,
before_model,
after_model,
wrap_model_call,
wrap_tool_call,
dynamic_prompt,
hook_config
)
Among these, the supported range of decorator parameters may expand with version updates. The table lists the configurations most important for daily development.
V. before_agent: execute before the Agent starts
before_agent Used to execute preprocessing logic when the Agent starts running.
Common uses:
- Initialize custom state.
- Log request start information.
- Check input conditions at the application level.
- Prepare the data needed for this execution.
Example: log Agent startup
Example
from
langchain.
agents
.
middleware
import
before_agent
@
before_agent
def
log_agent_start
(
state
,
runtime
)
:
"""Print a log when the Agent starts executing."""
(
"[Middleware] Agent started executing"
)
(
"Current message count:"
,
len
(
state.
get
(
"messages"
,
[
]
)
)
)
return
None
Return None indicates no modification to the Agent State.
If a dict is returned, the corresponding state fields can be updated.
**Note:** before_agent is not suitable for replacing checks before each model call. When you need to check every model request, you should use before_model.
VI. before_model: execute before the model call
before_model Runs before each model call.
For example, if an Agent executes three model call cycles, before_model may run three times.
Example: count messages
Example
from
langchain.
agents
.
middleware
import
before_model
@
before_model
def
log_before_model
(
state
,
runtime
)
:
"""Print the current message count before each model call."""
count
=
len
(
state.
get
(
"messages"
,
[
]
)
)
(
f
"[Middleware] About to call the model, message count: {count}"
)
return
None
before_model can also end execution early based on conditions.
Example: intercept a test command early
Example
from
langchain.
agents
.
middleware
import
before_model
from
langchain.
messages
import
AIMessage
@
before_model
(
can_jump_to
=
[
"end"
]
)
def
block_test_command
(
state
,
runtime
)
:
"""End execution directly when a test command is encountered."""
users
=
[
msg
for
msg
in
state.
get
(
"messages"
,
[
]
)
if
msg.
type
==
"human"
]
if
users
and
users
[
1
]
.
content
==
"BLOCK_DEMO"
:
return
{
"messages"
:
[
AIMessage
(
content
=
"This is a demonstration interception result."
)
]
,
"jump_to"
:
"end"
}
return
None
Here:
can_jump_to=["end"]
declares that the Hook is allowed to end execution early.
**Important:** If you need to use jump_to in a Hook, you should explicitly configure the allowed jump targets. It is not a general jump interface where you can specify arbitrary node names.
VII. after_model: execute after the model reply
after_model Executes after each model call obtains a response.
Suitable for:
- Log model call results.
- Update the model call count.
- Check whether the model requested a tool.
- Decide whether to continue execution based on the model reply.
Example: log tool calls
Example
from
langchain.
agents
.
middleware
import
after_model
@
after_model
def
log_model_result
(
state
,
runtime
)
:
"""Check the model's most recent reply."""
messages
=
state.
get
(
"messages"
,
[
]
)
if
not
messages:
return
None
last
=
messages
[
1
]
if
last.
type
==
"ai"
:
(
"[Middleware] Model has returned"
)
for
call
in
getattr
(
last
,
"tool_calls"
,
[
]
)
:
(
"Requested tools:"
,
call
[
"name"
]
)
return
None
Note that after_model may trigger multiple times, so it is not suitable for unconditionally appending a one-time customer-service signature.
If you need to format the final answer after the entire Agent ends normally, you can usually consider after_agent.
VIII. after_agent: execute after the Agent completes
after_agent Usually used to handle the state after the Agent completes normally.
For example:
- Log task completion information.
- Format the final answer.
- Summarize execution results.
- Update the completion state.
Example: add a marker to the final answer
Example
from
langchain.
agents
.
middleware
import
after_agent
SIGNATURE
=
"\n\n---\nRUNOOB AI demo assistant"
@
after_agent
def
add_signature
(
state
,
runtime
)
:
"""Append a marker once to the final text reply."""
messages
=
state.
get
(
"messages"
,
[
]
)
if
not
messages:
return
None
last
=
messages
[
1
]
if
last.
type
!=
"ai"
:
return
None
if
getattr
(
last
,
"tool_calls"
,
[
]
)
:
return
None
if
not
isinstance
(
last.
content
,
str
)
:
return
None
if
SIGNATURE
in
last.
content
:
return
None
updated
=
last.
model_copy
(
update
=
{
"content"
: last.
content
- SIGNATURE
}
)
return
{
"messages"
:
[
updated
]
}
Here the original ID of the AIMessage is preserved, so in a state that supports the add_messages Reducer, you can update an existing message instead of simply appending a new reply.
**Note:** after_agent is not a general finally handler. If an unhandled exception occurs during execution, you should not assume it will definitely run. When you need to clean up resources regardless of success or failure, use try/finally or a context manager at the application layer.
IX. wrap_model_call: wrap the model call
wrap_model_call is the core Hook for controlling model execution.
The difference from before_model is that wrap_model_call can directly control whether the underlying model handler executes.
Basic form:
@wrap_model_call
def middleware(request, handler):
return handler(request)
Where:
request: the ModelRequest for this model request.handler: the handler function that actually performs the next layer of model calls.
Middleware can:
- Call handler once for normal execution.
- Call it multiple times on specific errors to implement retries.
- Skip calling handler and return a custom result directly.
- Modify the model or request content via request.override().
Example: Recording model call elapsed time
Example
import
time
from
langchain.
agents
.
middleware
import
(
wrap_model_call
,
ModelRequest
,
ModelResponse
)
@
wrap_model_call
def
measure_model_time
(
request: ModelRequest
,
handler
)
:
"""Measure the elapsed time of each model call."""
started
=
time
.
perf_counter
(
)
try
:
response
=
handler
(
request
)
return
response
finally
:
elapsed
=
time
.
perf_counter
(
)
- started
(
f
"[Middleware] Model call elapsed: {elapsed:.3f} seconds"
)
The timing here covers the synchronous execution of handler(request).
If the underlying handler raises an exception, finally will still print the elapsed time.
This kind of Middleware is suitable for recording latency and performance metrics, but do not output complete request content containing private data directly in production logs.
10. Modifying the model request with request.override()
ModelRequest.override() It creates a new request object with the modifications.
The original request is not modified directly.
For example, we can dynamically replace the system message:
Example
from
langchain.
messages
import
SystemMessage
from
langchain.
agents
.
middleware
import
wrap_model_call
@
wrap_model_call
def
set_custom_prompt
(
request
,
handler
)
:
new_request
=
request.
override
(
system_message
=
SystemMessage
(
content
=
"You are a Python programming teacher; please answer concisely."
)
)
return
handler
(
new_request
)
You can also modify the model:
new_request = request.override(
model=different_model
)
Or adjust the tools that are allowed to be used:
new_request = request.override(
tools=[selected_tool]
)
**Note:** tools can only use registered tools that can be executed by the Agent. You cannot simply add an arbitrary new tool object to request.tools and assume the underlying ToolNode automatically has the ability to execute it.
11. Key Attributes of ModelRequest
ModelRequest encapsulates the information needed for the current model call.
| property | Description |
|---|---|
model |
The currently used BaseChatModel |
messages |
The list of messages in the current model request, excluding the separate system_message |
system_message |
The current system message, which may be empty |
tools |
The list of tool definitions visible to the current model |
tool_choice |
The tool selection strategy |
response_format |
Structured output configuration |
model_settings |
Other configurations for the current model call |
state |
The Agent's current state |
runtime |
The runtime context and related capabilities |
It is important to distinguish:
request.messages
request.state["messages"]
The former is the messages to be provided to the model currently; the latter belongs to the Agent's execution state.
Some Middleware can adjust the messages in the current model request without permanently modifying the persisted history.
Common fields supported by ModelRequest.override()
| Field | Purpose |
|---|---|
model |
Switching models |
system_message |
Replace the system message |
messages |
Modify the current model input messages |
tools |
Adjust the tools visible to the model |
tool_choice |
Set the tool selection preference |
response_format |
Adjust the structured output configuration |
model_settings |
Pass model call settings |
state |
Replace the state view used by the current request |
In the old interface, system_prompt the override approach is deprecated; you should use system_message。
12. dynamic_prompt: Dynamic System Prompts
For scenarios that only need to dynamically generate a System Prompt, there is no need to write wrap_model_call yourself every time.
LangChain provides a simpler option:
@dynamic_prompt
It is essentially a convenience decorator implemented on top of the model call wrapping mechanism.
Example: Generating a system prompt based on the date
Example
from
datetime
import
datetime
from
zoneinfo
import
ZoneInfo
from
langchain.
agents
.
middleware
import
dynamic_prompt
,
ModelRequest
@
dynamic_prompt
def
date_prompt
(
request: ModelRequest
)
str
:
now
=
datetime
.
now
(
ZoneInfo
(
"Asia/Shanghai"
)
)
return
(
"You are a Python learning assistant.\n"
f
"Current date: {now.date().isoformat()}.\n"
"Answer as concisely as possible; provide code when necessary."
)
dynamic_prompt returns a system prompt string, not a state update dictionary.
It is ideal for:
- Date and time zone hints.
- Adjusting the response style based on user level.
- Generating role rules based on business scenarios.
Compared with directly modifying messages, dynamic_prompt does not need to repeatedly insert SystemMessage into the chat history.
13. wrap_tool_call: Wrapping Tool Execution
wrap_tool_call Similar to wrap_model_call, but it intercepts tool calls.
It can be used to:
- Record tool execution elapsed time.
- Catch tool exceptions.
- Control tool execution.
- Handle tool return results.
Basic form:
@wrap_tool_call
def middleware(request, handler):
return handler(request)
Example: Recording tool execution
Example
import
time
from
langchain.
agents
.
middleware
import
wrap_tool_call
@
wrap_tool_call
def
log_tool_execution
(
request
,
handler
)
:
"""Record the tool name and execution elapsed time."""
name
=
request.
tool_call
[
"name"
]
started
=
time
.
perf_counter
(
)
(
"[Starting tool execution]"
,
name
)
try
:
return
handler
(
request
)
finally
:
elapsed
=
time
.
perf_counter
(
)
- started
(
f
"[Tool execution finished] {name}, elapsed {elapsed:.3f} seconds"
)
A tool call request can be used to
request.tool_call
read the tool name, arguments, and call ID proposed by the model.
If you need to implement tool-level exception handling, you can selectively catch certain exceptions.
14. wrap_tool_call: Handling Tool Exceptions
For example, when a course query tool encounters a temporary error, the exception can be converted into a ToolMessage.
Example: Handling only specified exceptions
Example
from
langchain.
agents
.
middleware
import
wrap_tool_call
from
langchain.
messages
import
ToolMessage
@
wrap_tool_call
def
handle_course_error
(
request
,
handler
)
:
try
:
return
handler
(
request
)
except
ValueError
:
return
ToolMessage
(
content
=
"Tool arguments are incorrect; please check the input."
,
tool_call_id
=
request.
tool_call
[
"id"
]
,
name
=
request.
tool_call
[
"name"
]
,
status
=
"error"
)
This does not catch all exceptions; only ValueError is converted.
Exceptions without a match are still re-raised, allowing the program to identify genuine system failures.
**Note:** tool calls may have real side effects. For operations such as sending email, making payments, and deleting data, you cannot simply rely on generic Middleware retries, as this may lead to duplicate execution.
If you only need to standardize tool error handling, you can also use the built-in ToolErrorMiddleware.
15. The ModelResponse Data Structure
ModelResponse Represents the complete result returned by the model call handler.
Its core structure is:
ModelResponse(
result: list[BaseMessage],
structured_response: Any | None = None
)
| property | Type | Description |
|---|---|---|
result |
list[BaseMessage] | Messages produced by the model call |
structured_response |
ResponseT | None | Parsed structured output |
Typically, result contains an AIMessage.
If the model produces structured output through the tool mechanism, additional ToolMessages may also appear.
Example: Reading ModelResponse
Example
from
langchain.
agents
.
middleware
import
wrap_model_call
,
ModelResponse
@
wrap_model_call
def
inspect_model_response
(
request
,
handler
)
:
response
=
handler
(
request
)
if
isinstance
(
response
,
ModelResponse
)
:
(
"Number of returned messages:"
,
len
(
response.
result
)
)
(
"Whether there is a structured result:"
,
response.
structured_response
is
not
None
)
return
response
Note that the model return type of Middleware may also be AIMessage or ExtendedModelResponse.
Therefore, when writing generic code that needs to be compatible with multiple Middleware, you should not assume the response always has a single fixed type.
16. The ModelCallResult Return Type
LangChain summarizes the return types supported by model call Hooks as ModelCallResult。
Contains:
| Return Type | Purpose |
|---|---|
AIMessage |
A simplified model reply |
ModelResponse |
A complete model call result |
ExtendedModelResponse |
A model reply plus an additional state update command |
For example, in a simple interceptor, you can return an AIMessage directly:
Example
from
langchain.
agents
.
middleware
import
wrap_model_call
from
langchain.
messages
import
AIMessage
@
wrap_model_call
def
demo_short_circuit
(
request
,
handler
)
:
"""Intercept a fixed test message."""
if
(
request.
messages
and
request.
messages
[
1
]
.
type
==
"human"
and
request.
messages
[
1
]
.
content
==
"MOCK_REPLY"
)
:
return
AIMessage
(
content
=
"This is a Middleware simulated reply."
)
return
handler
(
request
)
If the user inputs the fixed MOCK_REPLY, Middleware can return a simulated AIMessage directly without calling the real model.
But this mechanism cannot replace formal user authorization, tool permissions, and security protections.
17. ExtendedModelResponse: Model Results and State Updates
ExtendedModelResponse You can return both the model result and an additional Command state update.
Main structure:
ExtendedModelResponse(
model_response=...,
command=Command(update={...})
)
| property | Description |
|---|---|
model_response |
The underlying ModelResponse |
command |
An optional state update Command |
For example, we want to record the Token usage of each model after every model return.
Example: Updating model call statistics
Example
from
typing
import
NotRequired
from
langchain.
agents
import
AgentState
from
langchain.
agents
.
middleware
import
(
wrap_model_call
,
ExtendedModelResponse
)
from
langgraph.
types
import
Command
class
UsageState
(
AgentState
)
:
last_model_tokens: NotRequired
[
int
]
@
wrap_model_call
(
state_schema
=
UsageState
)
def
track_token_usage
(
request
,
handler
)
:
response
=
handler
(
request
)
tokens
=
0
for
msg
in
response.
result
:
usage
=
getattr
(
msg
,
"usage_metadata"
,
None
)
if
usage:
tokens +
=
usage.
get
(
"total_tokens"
,
0
)
return
ExtendedModelResponse
(
model_response
=
response
,
command
=
Command
(
update
=
{
"last_model_tokens"
: tokens
}
)
)
In this way, after the model returns you can update:
last_model_tokens
This field stores the statistics of this model call; it is not equal to the cumulative Token count for the entire session.
**Important:** the Command in ExtendedModelResponse is currently mainly used for additional state updates.
Do not confuse it with arbitrary LangGraph routing jumps. Here, controlling graph execution freely through command configurations such as goto, resume, and graph is not supported.
18. Differences in State Updates Between Node-style and Wrap-style
The two Middleware approaches have different mechanisms for updating state.
| Hook type | State update method |
|---|---|
| before_agent | Return a dict directly or a supported Command |
| before_model | Return a dict directly or a supported Command |
| after_model | Return a dict directly or a supported Command |
| after_agent | Return a dict directly or a supported Command |
| wrap_model_call | Return an ExtendedModelResponse with an attached Command |
| wrap_tool_call | Can return a Command directly |
Updates returned by Node-style pass through the Reducer of the corresponding LangGraph field.
For example, messages typically use the add_messages Reducer.
Therefore:
return {"messages": [AIMessage(content="New message")]}
This usually means appending new messages rather than replacing the entire message list.
If you need to modify existing messages, consider reusing the original message ID, or using a specialized update method that conforms to the Reducer semantics.
19. Middleware Execution Order
When an Agent registers multiple Middleware, the execution order is very important.
For example:
middleware = [
middleware_a,
middleware_b,
middleware_c
]
Before Hook
Executed in list order:
A.before_model
B.before_model
C.before_model
Wrap Hook
Using a nested structure:
A.wrap_model_call
↓
B.wrap_model_call
↓
C.wrap_model_call
↓
模型执行
↑
C 返回
↑
B 返回
↑
A 返回
After Hook
Executed in reverse order:
C.after_model
B.after_model
A.after_model
Correspondingly, before_agent executes from front to back, while after_agent executes from back to front.
Therefore, the first Wrap Middleware in the list is the outermost layer.
**Recommendation:** wrappers that need to centrally handle exceptions from other Middleware can be placed on the outside; however, the specific order should still be designed and tested according to business logic.
20. Configuring Jumps with hook_config
If you inherit from AgentMiddleware through a class, you can use @hook_config to configure the allowed jump targets.
For example:
Example
from
langchain.
agents
.
middleware
import
AgentMiddleware
,
hook_config
from
langchain.
messages
import
AIMessage
class
MessageGuardMiddleware
(
AgentMiddleware
)
:
@
hook_config
(
can_jump_to
=
[
"end"
]
)
def
before_model
(
self
,
state
,
runtime
)
:
users
=
[
msg
for
msg
in
state.
get
(
"messages"
,
[
]
)
if
msg.
type
==
"human"
]
if
users
and
users
[
1
]
.
content
==
"STOP_DEMO"
:
return
{
"messages"
:
[
AIMessage
(
content
=
"Test request intercepted."
)
]
,
"jump_to"
:
"end"
}
return
None
Main jump targets:
| Goals | Purpose |
|---|---|
end |
Enter the Agent ending flow |
model |
Jump to the model execution flow |
tools |
Jump to the tool execution node |
Note that jumping to the tools node typically requires a valid tool call request to be present. Otherwise, an invalid execution state may result.
For ordinary business, the most commonly used is still:
can_jump_to=["end"]
Used to terminate early when explicit conditions are met.
21. Class-based Middleware: Implementing Multiple Hooks at Once
If a Middleware needs to record information both before and after model calls, using a class is more convenient.
Example: LoggingMiddleware
Example
import
time
from
langchain.
agents
.
middleware
import
AgentMiddleware
class
LoggingMiddleware
(
AgentMiddleware
)
:
"""Print simple logs of model execution and tool calls."""
def
before_agent
(
self
,
state
,
runtime
)
:
(
"[Agent] Starting execution"
)
return
None
def
before_model
(
self
,
state
,
runtime
)
:
(
"[Model] About to call"
)
return
None
def
wrap_model_call
(
self
,
request
,
handler
)
:
started
=
time
.
perf_counter
(
)
try
:
return
handler
(
request
)
finally
:
(
"[Model] Elapsed:"
,
round
(
time
.
perf_counter
(
)
- started
,
3
)
,
"seconds"
)
def
wrap_tool_call
(
self
,
request
,
handler
)
:
name
=
request.
tool_call
[
"name"
]
(
"[Tool] Start:"
,
name
)
return
handler
(
request
)
def
after_agent
(
self
,
state
,
runtime
)
:
(
"[Agent] Execution complete"
)
return
None
Register to the Agent:
agent = create_agent(
model="deepseek:deepseek-chat",
tools=[my_tool],
middleware=[LoggingMiddleware()]
)
Class-based Middleware is especially suitable for cross-project reuse, and you can also init provide custom parameters in
22. Custom Middleware State
Some Middleware needs to save counters or business state across multiple model calls.
In this case, you can extend AgentState.
Example: Counting model calls
Example
from
typing
import
NotRequired
from
langchain.
agents
import
AgentState
from
langchain.
agents
.
middleware
import
after_model
class
TrackingState
(
AgentState
)
:
model_call_count: NotRequired
[
int
]
@
after_model
(
state_schema
=
TrackingState
)
def
count_model_calls
(
state: TrackingState
,
runtime
)
:
"""Update the count after each model return."""
count
=
state.
get
(
"model_call_count"
,
0
)
return
{
"model_call_count"
: count +
1
}
If the Agent performs three model calls, normally you will see in the final State:
model_call_count = 3
In real production environments, it is more recommended to use the dedicated ModelCallLimitMiddleware to control the upper limit of model calls, rather than relying entirely on a counter you write yourself.
23. Dynamically Limiting Model-Visible Tools
Some tools should only be open to administrators.
You can use wrap_model_call to adjust the list of tools visible to the model based on trusted Runtime Context.
For example, ordinary users can only query, while administrators can perform specific administrative operations.
Example: Tool visibility filtering
Example
from
dataclasses
import
dataclass
from
langchain.
agents
.
middleware
import
wrap_model_call
@
dataclass
class
UserContext:
is_admin:
bool
=
False
@
wrap_model_call
def
filter_admin_tools
(
request
,
handler
)
:
is_admin
=
request.
runtime
.
context
.
is_admin
if
is_admin:
return
handler
(
request
)
allowed
=
[
tool
for
tool
in
request.
tools
if
tool.
name
!=
"delete_course"
]
return
handler
(
request.
override
(
tools
=
allowed
)
)
Here, delete_course is removed from the model tool list for ordinary users.
**Important:** a tool not being visible to the model does not mean permission control has truly been achieved.
If delete_course modifies the database, permission verification must also be performed at the tool execution layer based on trusted user identity.
The runtime context must also be provided by a trusted backend; you cannot let the browser freely submit is_admin=True.
24. Quick Reference of Built-in Middleware
LangChain also provides a series of built-in Middleware that can reduce repetitive development.
| Middleware | Main Use |
|---|---|
ModelRetryMiddleware |
Limited retries when the model fails |
ToolRetryMiddleware |
Limited retries when tool execution fails |
ToolErrorMiddleware |
Convert specified tool exceptions into error results |
ModelFallbackMiddleware |
Try a backup model when the primary model fails |
ModelCallLimitMiddleware |
Limit the number of model calls |
ToolCallLimitMiddleware |
Limit the number of tool calls |
SummarizationMiddleware |
Summarize long conversation history |
HumanInTheLoopMiddleware |
Human approval for tool operations |
PIIMiddleware |
Detect and handle specific personal information |
LLMToolSelectorMiddleware |
Select relevant tools via the model |
ContextEditingMiddleware |
Manage long tool contexts |
TodoListMiddleware |
Task planning and tracking |
For example, there is no need to write wrap_model_call from scratch for ordinary model retries.
You can simply:
from langchain.agents.middleware import ModelRetryMiddleware
middleware = [
ModelRetryMiddleware(max_retries=2)
]
Compared with custom infinite retries using except Exception, built-in Middleware makes it easier to manage retry counts, backoff delays, and failure handling.
25. Complete Example: Comprehensive Use of Middleware
Below we create a simple course query Agent and combine four Middleware:
- before_agent: record that the Agent has started.
- before_model: print the current number of messages.
- wrap_model_call: measure model elapsed time.
- wrap_tool_call: record tool calls.
- after_agent: record the completion status.
Filename:middleware_api_demo.py
Install dependencies:
pip install -U langchain langchain-deepseek python-dotenv
creation .env:
DEEPSEEK_API_KEY=your_deepseek_api_key
Complete example
import
time
from
dotenv
import
load_dotenv
from
langchain.
agents
import
create_agent
from
langchain.
agents
.
middleware
import
(
before_agent
,
before_model
,
wrap_model_call
,
wrap_tool_call
,
after_agent
)
from
langchain.
tools
import
tool
from
langchain_deepseek
import
ChatDeepSeek
load_dotenv
(
)
========== 1. Create tools ==========
@
tool
def
search_course
(
keyword
:
str
)
str
:
"""Query the simulated course catalog."""
courses
=
{
"Python"
:
"Python Fundamentals, Python Functions"
,
"Java"
:
"Java Fundamentals, Java Object-Oriented"
}
return
courses.
get
(
keyword
,
"No matching mock course"
)
========== 2. Before the Agent starts ==========
@
before_agent
def
log_start
(
state
,
runtime
)
:
(
"[Agent] Starting execution"
)
return
None
========== 3. Before each model call ==========
@
before_model
def
log_messages
(
state
,
runtime
)
:
(
"[Model] Current message count:"
,
len
(
state.
get
(
"messages"
,
[
]
)
)
)
return
None
========== 4. Model call wrapping ==========
@
wrap_model_call
def
track_model_time
(
request
,
handler
)
:
started
=
time
.
perf_counter
(
)
try
:
return
handler
(
request
)
finally
:
(
"[Model] Elapsed:"
,
round
(
time
.
perf_counter
(
)
- started
,
3
)
,
"seconds"
)
========== 5. Tool call wrapping ==========
@
wrap_tool_call
def
track_tool
(
request
,
handler
)
:
name
=
request.
tool_call
[
"name"
]
(
"[Tool] Executing:"
,
name
)
return
handler
(
request
)
========== 6. After the Agent completes ==========
@
after_agent
def
log_finish
(
state
,
runtime
)
:
(
"[Agent] Execution complete"
)
return
None
========== 7. Create the Agent ==========
agent
=
create_agent
(
model
=
ChatDeepSeek
(
model
=
"deepseek-chat"
,
temperature
=
0
)
,
tools
=
[
search_course
]
,
middleware
=
[
log_start
,
log_messages
,
track_model_time
,
track_tool
,
log_finish
]
,
system_prompt
=
(
"You are a programming course query assistant."
"When the user requests to find a course, use search_course."
"Answer only based on the mock tool data."
)
)
========== 8. Run ==========
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Please use the tool to query Python courses."
}
]
}
)
(
"\nFinal answer:"
)
(
result
[
"messages"
]
[
1
]
.
content
)
Possible logs:
[Agent] 开始执行
[Model] 当前消息数: 1
[Model] 耗时: 1.235 秒
[Tool] 正在执行: search_course
[Model] 当前消息数: 3
[Model] 耗时: 0.864 秒
[Agent] 执行完成
Final Answer:
模拟课程目录包含 Python 基础和 Python 函数。
The elapsed times and answers above are only for demonstrating the format, not actual measurement results.
If the model does not choose to call the search tool, the corresponding Tool log will not appear.
26. Testing Methods for Middleware
Not all Middleware tests require a real API Key.
For example, date formatting, message condition checks, and state updates can be verified with local code.
However, to test whether Middleware runs as expected in the Agent execution chain, you still need to register it with the Agent and trigger the corresponding Hook through a real model or a suitable test model.
It is recommended to test separately:
| Test item | Check content |
|---|---|
| Start and end Hooks | Whether the execution order is correct |
| before_model | Whether it triggers before each model call |
| wrap_model_call | Whether handler is called correctly |
| wrap_tool_call | Whether tool names and return values are correct |
| jump_to | Whether available targets are declared |
| State Update | Whether the Reducer merges fields as expected |
| Exception handling | Whether errors are propagated or converted |
| asynchronous | Whether the corresponding async Hook is implemented |
In particular, you need to verify behavior with multiple tool calls, repeated model calls, and exception interruptions; you cannot judge that Middleware is correctly implemented based on a single "hello" test.
27. Production Environment Considerations
1. Each Middleware is responsible for only one type of function
Try to separate logging, retries, permissions, prompts, and output formatting, avoiding a single Middleware that contains a large amount of interdependent logic.
2. Do not modify message history unconditionally
Agent messages typically use the add_messages Reducer. Adding messages and replacing messages have different semantics; you cannot simply assume that returning a shorter list will delete old content.
3. Do not retry model calls infinitely
wrap_model_call can call handler multiple times, but you should limit the count and only retry transient failures that are suitable for retrying.
4. Tool permissions must be enforced at the execution layer
Merely filtering request.tools does not mean the operation is truly prohibited. Database writes, email sending, and order queries still require backend authorization checks.
5. Avoid duplicate business side effects
If Middleware retries payment, email, or order creation tools, you need to design idempotent requests and real operation status queries first.
6. Handle synchronous and asynchronous logic correctly
When using ainvoke() or astream(), ensure that the dependent Middleware and tools support the corresponding asynchronous execution path.
7. Do not leak sensitive logs
Middleware may access complete conversations, user context, and tool arguments. Production logs and LangSmith tracing need to consider data masking.
8. Do not abuse jump_to
Jumping to tools or model arbitrarily may lead to unexpected execution states. Only use it when you clearly understand the Agent graph structure.
9. Pay attention to the order of multiple Middleware
before executes first when registered first, after executes first when registered last, and wrap is nested layer by layer. When you need to handle exceptions across the entire execution chain, pay special attention to the wrapping levels.
10. Prefer built-in Middleware
For common needs such as retries, call limits, conversation summarization, and human approval, evaluate LangChain's built-in solutions first before deciding whether to customize.
28. Frequently Asked Questions
1. What is the difference between AgentMiddleware and a regular Python decorator?
AgentMiddleware is a component integrated into the LangChain Agent execution lifecycle, able to access state, context, and the model and tool call processes.
2. Does before_agent execute on every model call?
No. It is positioned at the beginning of the Agent execution cycle, not a model call loop Hook.
3. What is the difference between before_model and wrap_model_call?
before_model is responsible for pre-execution state checks or updates; wrap_model_call can control whether and how handler is executed.
4. How to choose between after_model and after_agent?
Use after_model when processing is needed after each model reply; use after_agent when processing is needed after normal Agent completion.
5. Can Middleware completely skip a model call?
Yes. wrap_model_call can return an AIMessage directly under specific conditions without calling handler.
6. Does request.override() modify the original request?
No. It returns a new ModelRequest with overridden fields.
7. Does ModelRequest.messages include SystemMessage?
The system message is usually represented separately by system_message; you cannot simply treat request.messages as the complete final model payload.
8. Does ModelResponse always have only one AIMessage?
Not necessarily. Scenarios such as structured output may contain other messages.
9. What is the purpose of ExtendedModelResponse?
It allows providing additional state updates via Command while returning the model result.
10. Can ExtendedModelResponse.command jump to arbitrary nodes?
No. The current model response extension mechanism mainly supports additional state updates and does not support arbitrary goto or resume.
11. What types does ModelCallResult include?
It includes AIMessage, ModelResponse, and ExtendedModelResponse.
12. Why are old messages still present after I return {"messages": [...]}?
Because messages uses the add_messages Reducer by default, which typically merges or appends rather than directly replacing the entire history.
13. Can Middleware switch models dynamically?
Yes. Through wrap_model_call and request.override(model=...), you can select a different model before the model call.
14. Can Middleware control tools dynamically?
You can adjust the set of tools visible to the model, but real tool execution permissions still need to be controlled by backend code.
15. What is the execution order of multiple Middleware?
before executes in registration order, after executes in reverse order, and wrap treats the first Middleware as the outermost layer.
16. When should you use the AgentMiddleware class?
When you need multiple Hooks, synchronous and asynchronous implementations, initialization parameters, or cross-project reuse, using a class is usually more convenient.
17. Can you record the Token usage of each model?
You can check the usage_metadata returned by the model, or combine with LangSmith for tracing, but the actual data depends on whether the model provider supplies it.
18. Can Middleware replace the permission checks of a business system?
No. For user identity, order ownership, payments, and database modifications, permissions must be enforced by trusted business code.
Summary
Middleware is an important extension mechanism of LangChain Agent, able to add custom behavior to models and tools without modifying the Agent's core execution flow.
This chapter mainly introduced:
AgentMiddleware: a custom middleware base class.before_agent、after_agent: an execution cycle Hook.before_model、after_model: a model loop Hook.wrap_model_call: control model calls.wrap_tool_call: control tool execution.- The difference between synchronous and asynchronous Hooks.
dynamic_prompt: dynamically generate system prompts.ModelRequest: model request information.request.override(): create a modified request.ModelResponse: model execution results.ExtendedModelResponse: model results plus state updates.Command: update Agent State.hook_config: configure allowed graph jumps.- Nesting and execution order of multiple Middleware.
The simplest way to write Middleware:
from langchain.agents.middleware import before_model
@before_model
def log_request(state, runtime):
print("即将调用模型")
return None
Register in the Agent:
agent = create_agent(
model="deepseek:deepseek-chat",
tools=[my_tool],
middleware=[log_request]
)
**Core principle:** Node-style Hooks are responsible for state checks and updates before and after execution, while Wrap-style Hooks intercept and control the actual calls. Only by correctly understanding the difference between the two, the execution order, and the Reducer semantics can you safely extend the Agent's behavior.