LangChain Middleware
LangChain Middleware is an important mechanism for extending Agent behavior.
Through Middleware, developers can insert custom logic at specific stages of model calls, tool execution, and the Agent lifecycle, enabling features such as logging, retries, model fallback, content checks, dynamic prompts, and execution limits.
This logic can be separated from the Agent's business tools, eliminating the need to modify the Agent's core execution code every time.
This chapter is based on LangChain 1.x and introduces the six core Hooks of Middleware, two definition approaches (decorators and class inheritance), execution order, state updates, and commonly used built-in middleware.
1. What is Middleware?
Middleware can be understood as an interceptor or Hook in the Agent execution flow.
A regular Agent typically runs according to the following flow:
用户输入
↓
调用模型
↓
模型判断是否调用工具
↓
执行工具
↓
将工具结果返回模型
↓
生成最终回答
Middleware can run additional logic before and after these stages.
For example:
用户输入
↓
[before_agent] 初始化和请求检查
↓
[before_model] 模型调用前检查
↓
[wrap_model_call] 模型请求拦截、重试
↓
Model
↓
[after_model] 模型响应检查
↓
[wrap_tool_call] 工具执行拦截
↓
Tools
↓
重新调用模型(按需循环)
↓
[after_agent] 执行结束处理
↓
返回结果
Note that the above is only a simplified flow. The actual execution order is also affected by the combination of multiple Middleware, model tool calls, interruptions, and other execution control mechanisms.

2. The Six Core Hooks of Middleware
LangChain Middleware provides six main Hooks, divided into two categories: Node-style and Wrap-style.
| Hook | Type | Trigger Timing | Common Use Cases |
|---|---|---|---|
before_agent |
Node | Before the Agent's main flow begins | Initialization, input checks, logging |
before_model |
Node | Before each model call | Message checks, state updates, flow control |
wrap_model_call |
Wrap | Wrap model call | Retries, model fallback, request rewriting |
after_model |
Node | After model response | Result checks, logging, state updates |
wrap_tool_call |
Wrap | Wrap tool call | Tool error handling, retries, auditing |
after_agent |
Node | When the Agent completes normally | Result statistics, ending logs |
Node-style Hooks
Node Hooks run at specified execution stages, suitable for logging, state updates, and flow checks.
Contains:
before_agent
before_model
after_model
after_agent
Typically, you can return:
None: do not modify state.dict: update Agent State.Command: perform state or flow control in supported execution scenarios.
Wrap-style Hooks
Wrapping Hooks are responsible for intercepting model or tool calls.
Contains:
wrap_model_call
wrap_tool_call
Such Hooks receive a handler, which executes the wrapped operation.
Developers can choose to call handler once, multiple times, or not call handler under appropriate conditions.
**Note:** the return value of a Wrap-style Hook must conform to the corresponding protocol; you cannot treat a regular state dictionary directly as the return value of a model or tool call.
3. Two Ways to Define Middleware
LangChain supports using decorators or inheriting from the AgentMiddleware class to create middleware.
Approach 1: Decorators
Suitable for middleware with simple functions and independent logic.
Example
from
langchain.
agents
.
middleware
import
before_model
,
after_model
,
AgentState
from
langgraph.
runtime
import
Runtime
@
before_model
def
log_before
(
state: AgentState
,
runtime: Runtime
)
None
:
"""Print the number of messages before the model call."""
(
"[before_model] Message count:"
,
len
(
state.
get
(
"messages"
,
[
]
)
)
)
@
after_model
def
log_after
(
state: AgentState
,
runtime: Runtime
)
None
:
"""Print tool requests after the model call."""
last
=
state
[
"messages"
]
[
1
]
tools
=
[
call
[
"name"
]
for
call
in
getattr
(
last
,
"tool_calls"
,
[
]
)
]
(
"[after_model] Tool requests:"
,
tools
or
"None"
)
When using, add the middleware to middleware:
agent = create_agent(
model="deepseek:deepseek-flash",
middleware=[log_before, log_after]
)
Middleware defined with decorators can be reused across multiple Agents.
Approach 2: Inheriting from AgentMiddleware
If a middleware needs multiple Hooks, internal configuration, or state management, you can use class inheritance.
Example
from
langchain.
agents
.
middleware
import
AgentMiddleware
,
AgentState
from
langgraph.
runtime
import
Runtime
class
LoggingMiddleware
(
AgentMiddleware
)
:
"""Uniformly record Agent execution logs."""
def
before_agent
(
self
,
state: AgentState
,
runtime: Runtime
)
None
:
(
"[Logging] Agent started"
)
def
before_model
(
self
,
state: AgentState
,
runtime: Runtime
)
None
:
(
"[Logging] Preparing to call the model"
)
def
after_model
(
self
,
state: AgentState
,
runtime: Runtime
)
None
:
(
"[Logging] Model call completed"
)
def
after_agent
(
self
,
state: AgentState
,
runtime: Runtime
)
None
:
(
"[Logging] Agent completed normally"
)
middleware
=
LoggingMiddleware
(
)
The class only needs to implement the Hooks actually used; there is no need to write out all six methods.
By default, the middleware name usually uses the class name, but it can also be configured as needed.
**Note:** for simple logging, decorators are sufficient. Only when the logic is complex, configuration needs to be maintained, or multiple Hooks need to be combined is class inheritance recommended.
4. before_agent: Before the Agent Starts
before_agent Runs before the Agent's main flow begins, suitable for initialization, input checks, and basic logging.
For example, recording the number of user messages:
Example
from
langchain.
agents
.
middleware
import
before_agent
,
AgentState
from
langgraph.
runtime
import
Runtime
@
before_agent
def
start_log
(
state: AgentState
,
runtime: Runtime
)
None
:
"""Record Agent startup information."""
(
"Agent starts executing"
)
(
"Message count: "
,
len
(
state.
get
(
"messages"
,
[
]
)
)
)
In a normal complete execution,before_agent it usually executes at the start of an Agent call.
However, when persistent checkpoints, execution recovery, or interruptions are involved, you should not simply assume that every recovery necessarily re-runs all lifecycle Hooks.
5. before_model: Before the Model Call
before_model Runs before the model call.
Unlike before_agent, if the Agent needs to call the model multiple times, before_model may also execute multiple times.
It is suitable for checking messages, modifying state, or ending the current execution early when conditions are met.
Example: Limiting the number of messages
Example
from
langchain.
agents
.
middleware
import
before_model
,
AgentState
from
langchain.
messages
import
AIMessage
from
langgraph.
runtime
import
Runtime
@
before_model
(
can_jump_to
=
[
"end"
]
)
def
check_message_limit
(
state: AgentState
,
runtime: Runtime
)
dict
|
None
:
"""End early when there are too many messages."""
if
len
(
state
[
"messages"
]
)
=
50
:
return
{
"messages"
:
[
AIMessage
(
content
=
"The current session has many messages; please start a new session."
)
]
,
"jump_to"
:
"end"
}
return
None
Here, can_jump_to=["end"] Declare that this Hook is allowed to jump to the ending flow.
If the number of messages reaches the limit, the Hook returns a new AIMessage and controls the Agent to end.
**Note:** this only demonstrates a message count limit, not a Token count limit, and cannot replace actual context window management.
6. after_model: After the Model Call
after_model Runs after the model obtains a response.
Can be used to record whether the model initiated a tool call, or to update execution statistics.
Example: Checking tool requests
Example
from
langchain.
agents
.
middleware
import
after_model
,
AgentState
from
langgraph.
runtime
import
Runtime
@
after_model
def
inspect_response
(
state: AgentState
,
runtime: Runtime
)
None
:
"""Check whether the model requests a tool call."""
last
=
state
[
"messages"
]
[
1
]
calls
=
getattr
(
last
,
"tool_calls"
,
[
]
)
if
calls:
(
"Model requested tool:"
,
[
call
[
"name"
]
for
call
in
calls
]
)
else
:
(
"The model did not request a tool"
)
If the model requested a tool, the Agent may then enter the tool execution node.
If there is no tool call and no other execution control requirements, the Agent usually ends the current loop.
In addition, after_model can update custom state fields by returning a state dictionary, but the corresponding fields need to be defined in the Agent State Schema.
7. wrap_model_call: Intercepting Model Calls
wrap_model_call is a powerful Middleware Hook.
It can wrap a model call through handler and control how the request is executed.
Typical scenarios include:
- Retrying after a model API request fails.
- Switching models based on conditions.
- Measuring model call elapsed time.
- Modifying model request parameters.
- Caching specific model requests.
Example: Recording model call elapsed time
Example
import
time
from
typing
import
Callable
from
langchain.
agents
.
middleware
import
wrap_model_call
,
ModelRequest
,
ModelResponse
@
wrap_model_call
def
time_model_call
(
request: ModelRequest
,
handler: Callable
[
[
ModelRequest
]
,
ModelResponse
]
)
ModelResponse:
"""Measure the elapsed time of a single model call."""
start
=
time
.
perf_counter
(
)
try
:
return
handler
(
request
)
finally
:
(
f
"[Model] Elapsed: {time.perf_counter() - start:.2f} seconds"
)
Here, handler(request) Execute the actual model call.
If handler is not called, the wrapped model request will not be executed through the normal flow.
Example: Retrying after failure
Below is a simplified retry example:
Example
from
typing
import
Callable
from
langchain.
agents
.
middleware
import
wrap_model_call
,
ModelRequest
,
ModelResponse
@
wrap_model_call
def
retry_model
(
request: ModelRequest
,
handler: Callable
[
[
ModelRequest
]
,
ModelResponse
]
)
ModelResponse:
"""Demonstrate retrying after a model call fails."""
for
attempt
in
range
(
3
)
:
try
:
return
handler
(
request
)
except
TimeoutError:
if
attempt
==
2
:
raise
(
f
"Model call timed out, preparing attempt {attempt + 2}"
)
raise
RuntimeError
(
"Model retry failed"
)
The example only catches TimeoutError, and not all provider timeout exceptions are of this type.
For real projects, it is recommended to handle the exceptions actually raised by the current model integration, adding exponential backoff and a retry limit.
LangChain also provides ready-made ModelRetryMiddleware, so there is generally no need to write a complete retry mechanism from scratch.
8. wrap_tool_call: Intercepting Tool Execution
wrap_tool_call Used to wrap tool execution in the Agent.
Can log before and after calling a tool, or catch specific tool execution exceptions.
Example: log tool calls
Example
from
typing
import
Callable
from
langchain.
agents
.
middleware
import
wrap_tool_call
from
langchain.
agents
.
middleware
.
types
import
ToolCallRequest
from
langchain.
messages
import
ToolMessage
from
langgraph.
types
import
Command
@
wrap_tool_call
def
log_tool_call
(
request: ToolCallRequest
,
handler: Callable
[
[
ToolCallRequest
]
,
ToolMessage | Command
]
)
ToolMessage | Command:
"""Record the tool name and execution result."""
name
=
request.
tool_call
[
"name"
]
(
"[Tool] Start:"
,
name
)
try
:
return
handler
(
request
)
finally
:
(
"[Tool] Finished:"
,
name
)
Here, the following is used request.tool_call Obtain the tool call information generated by the model.
The tool execution result is usually a ToolMessage, but may also be a Command used to update state.
**Note:** not all exceptions occur inside the tool function. For example, tool argument binding or argument validation failures may be handled by ToolNode before the tool executes.
For tools with database writes, payments, or other side effects, you cannot retry blindly, as this may lead to duplicate execution.
9. after_agent: After the Agent Execution Ends
after_agent Used to handle logic after the Agent completes normally.
For example, counting messages or recording ending logs.
Example
from
langchain.
agents
.
middleware
import
after_agent
,
AgentState
from
langgraph.
runtime
import
Runtime
@
after_agent
def
finish_log
(
state: AgentState
,
runtime: Runtime
)
None
:
"""Output statistics after the Agent completes."""
messages
=
state.
get
(
"messages"
,
[
]
)
tool_count
=
sum
(
msg.
type
==
"tool"
for
msg
in
messages
)
(
f
"Agent complete: {len(messages)} messages, {tool_count} tool results"
)
Note that after_agent should not be treated as a reliable exception cleanup mechanism.
If a model call raises an exception, a task is canceled, or the execution flow is interrupted, after_agent does not necessarily run along the normal ending path.
For database connections, file handles, or other resources that must be released, use Python's context manager,try/finally and similar mechanisms to handle them.
10. Complete Example: Observing the Middleware Lifecycle
Below we combine four node Hooks and one tool to observe the Agent's execution process.
To avoid confusion, the weather tool returns fixed mock data and does not connect to a real-time weather API.
Filename:middleware_demo.py
Install dependencies:
pip install -U langchain langchain-deepseek langgraph python-dotenv
in .env Configuration:
DEEPSEEK_API_KEY=your_deepseek_api_key
Complete example
from
dotenv
import
load_dotenv
from
langchain.
agents
import
create_agent
from
langchain.
agents
.
middleware
import
before_agent
,
before_model
,
after_model
,
after_agent
,
AgentState
from
langchain.
tools
import
tool
from
langgraph.
runtime
import
Runtime
load_dotenv
(
)
@
before_agent
def
start_log
(
state: AgentState
,
runtime: Runtime
)
None
:
(
"[before_agent] Agent started"
)
@
before_model
def
pre_model
(
state: AgentState
,
runtime: Runtime
)
None
:
(
"[before_model] Message count:"
,
len
(
state.
get
(
"messages"
,
[
]
)
)
)
@
after_model
def
post_model
(
state: AgentState
,
runtime: Runtime
)
None
:
last
=
state
[
"messages"
]
[
1
]
calls
=
[
c
[
"name"
]
for
c
in
getattr
(
last
,
"tool_calls"
,
[
]
)
]
(
"[after_model] Tool requests:"
,
calls
or
"None"
)
@
after_agent
def
end_log
(
state: AgentState
,
runtime: Runtime
)
None
:
(
"[after_agent] Total messages:"
,
len
(
state.
get
(
"messages"
,
[
]
)
)
)
@
tool
def
get_weather
(
city:
str
)
str
:
"""Query mock weather for a given city."""
data
=
{
"Hangzhou"
:
"Sunny, 25°C"
,
"Beijing"
:
"Cloudy, 18°C"
}
return
data.
get
(
city
,
"No simulated weather data for this city"
)
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
get_weather
]
,
middleware
=
[
start_log
,
pre_model
,
post_model
,
end_log
]
,
system_prompt
=
"You are a Chinese-language assistant. When querying the weather, use the tool; the tool returns mock data and does not represent real-time weather."
)
def
ask
(
question:
str
)
:
(
"\nUser:"
,
question
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
: question
}
]
}
)
(
"AI:"
,
result
[
"messages"
]
[
1
]
.
content
)
if
name
==
"main"
:
ask
(
"Please query Hangzhou's mock weather."
)
ask
(
"Hello, please introduce yourself."
)
Possible run results
用户:请查询杭州的模拟天气。
[before_agent] Agent 开始
[before_model] 消息数: 1
[after_model] 工具请求: ['get_weather']
[before_model] 消息数: 3
[after_model] 工具请求: 无
[after_agent] 消息总数: 4
AI:杭州的模拟天气为晴天,25°C。
用户:你好,请介绍一下自己。
[before_agent] Agent 开始
[before_model] 消息数: 1
[after_model] 工具请求: 无
[after_agent] 消息总数: 2
AI:你好,我是一名中文助手。
From this example, we can see:
before_agent: runs when normal execution begins.before_model: Runs before each model call.after_model: runs after each model response.after_agent: runs after normal execution completes.
If the model needs to call a tool, before_model and after_model may execute multiple times.
But the actual number of calls is determined by the model; you should not assume that a request with tools necessarily produces four messages.
11. Middleware Return Values and State Updates
For different types of Middleware, the meaning of the return value differs.
| Hook type | Common return values | Purpose |
|---|---|---|
| Node-style | None |
Do not submit state updates |
| Node-style | dict |
Submit state updates, merged by the Reducer |
| Node-style | Command |
Update state or control flow in supported scenarios |
wrap_model_call |
ModelResponse or a supported model response type |
Return the model execution result |
wrap_tool_call |
ToolMessage or Command |
Return the tool result or state update |
For example, a Node-style Middleware can modify custom state by returning a dictionary.
Example: Counting model calls
Example
from
typing_extensions
import
NotRequired
from
langchain.
agents
import
create_agent
from
langchain.
agents
.
middleware
import
after_model
,
AgentState
from
langgraph.
runtime
import
Runtime
class
TrackingState
(
AgentState
)
:
model_call_count: NotRequired
[
int
]
@
after_model
(
state_schema
=
TrackingState
)
def
count_calls
(
state: TrackingState
,
runtime: Runtime
)
dict
:
"""Count the number of model calls."""
return
{
"model_call_count"
: state.
get
(
"model_call_count"
,
0
)
1
}
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
]
,
middleware
=
[
count_calls
]
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Hello" (Chinese)
}
]
}
)
(
"Model call count:"
,
result.
get
(
"model_call_count"
)
)
If the model is called only once, the result is typically:
模型调用次数: 1
Here, model_call_count through the Middleware's state_schema declaration, then updated by returning a dictionary.
For messages field, LangGraph uses the add_messages Reducer to merge messages.
But not all fields use append logic. Ordinary fields without a special Reducer typically use overwrite-style updates.
12. Execution Order of Multiple Middleware
An Agent can use multiple Middleware at the same time:
middleware=[middleware_a, middleware_b]
The combination order of different Hook types is not entirely the same.
Generally speaking:
- Node-style pre-hooks execute in configuration order.
- Post-hooks usually execute in reverse order, forming a corresponding lifecycle wrapping relationship.
- Wrap-style Hooks use a nested wrapping structure, with the first Middleware usually at the outermost layer.
For example, the execution process of two Wrap Middleware can be understood as:
middleware_a:开始
middleware_b:开始
执行模型调用
middleware_b:结束
middleware_a:结束
Therefore, the order of Middleware may affect the results of retries, logging, caching, and error handling.
**Note:** in complex applications, if multiple Middleware modify the same state or model request, you should explicitly design the execution order and test it.
13. Built-in Middleware: No Need to Reinvent the Wheel
LangChain provides several commonly used built-in middleware that can be added directly to the Agent.
| Middleware | Main Function |
|---|---|
ModelRetryMiddleware |
Retries after model call failures |
ToolRetryMiddleware |
Retries after tool execution failures |
ModelFallbackMiddleware |
Switch to a backup model when the primary model is unavailable |
ModelCallLimitMiddleware |
Limit the number of model calls |
ToolCallLimitMiddleware |
Limit the number of tool calls |
SummarizationMiddleware |
Summarize and compress long conversations |
HumanInTheLoopMiddleware |
Human review before sensitive tool operations |
PIIMiddleware |
Identify and handle personally identifiable information |
LLMToolSelectorMiddleware |
Filter currently relevant tools from a large set of tools |
Example: Limiting the Number of Model Calls
Example
from
langchain.
agents
import
create_agent
from
langchain.
agents
.
middleware
import
ModelCallLimitMiddleware
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
]
,
middleware
=
[
ModelCallLimitMiddleware
(
run_limit
=
5
,
exit_behavior
=
"end"
)
]
,
system_prompt
=
"You are a Chinese programming assistant."
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"What is a Python decorator?"
}
]
}
)
(
result
[
"messages"
]
[
1
]
.
content
)
This limits the number of model calls in one Agent run.
Note that this does not equate to limiting Token consumption, nor is it a precise cap on API costs.
In practical applications, you can also combine API quotas, Token budgets, and timeout controls.
14. Middleware and Streaming Events
Middleware can also be combined with Streaming to send custom execution status to the frontend.
For example, sending a hint to the event stream before a model call:
正在调用模型……
In a runtime environment that supports streaming events, you can send events through the Runtime's stream writer.
Example: Custom status events
Example
from
langchain.
agents
import
create_agent
from
langchain.
agents
.
middleware
import
before_model
,
AgentState
from
langgraph.
runtime
import
Runtime
@
before_model
def
notify_model
(
state: AgentState
,
runtime: Runtime
)
None
:
"""Send the model call status."""
if
runtime.
stream_writer
:
runtime.
stream_writer
(
{
"stage"
:
"model"
,
"message"
:
"Calling the model"
}
)
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
]
,
middleware
=
[
notify_model
]
)
for
event
in
agent.
stream
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Introduce Python."
}
]
}
,
stream_mode
=
"custom"
,
version
=
"v2"
)
:
if
event
[
"type"
]
==
"custom"
:
(
event
[
"data"
]
)
In LangGraph versions that support the corresponding v2 streaming protocol, the output may be:
{'stage': 'model', 'message': '正在调用模型'}
Note thatruntime.stream_writer Availability depends on the actual execution context.
It is recommended to consume custom events through stream() or astream() rather than assuming that a regular invoke() will display the events directly.
15. Considerations for Using Middleware in Production
Although Middleware is convenient, not all business logic is suitable for placing in Middleware.
1. Do not repeatedly execute operations with side effects
Model request retries and tool retries carry different risks.
For read-only tools, retries are usually easier to control.
However, for operations such as payments, deleting files, and creating orders, retries may lead to duplicate execution; safety must be ensured through idempotency keys, transactions, or other mechanisms.
2. Do not log sensitive information
Middleware can access Agent State, tool arguments, and model output.
When logging, avoid directly saving passwords, API Keys, access tokens, and sensitive personal information.
3. Do not treat prompts as security controls
Prompts can guide model behavior, but cannot replace authentication, tool permission checks, and server-side business constraints.
4. Avoid synchronous blocking
For asynchronous applications, use the corresponding async Middleware hooks and avoid long-running blocking operations in the async event loop.
5. Control the number and complexity of Middleware
Multiple middleware may modify requests, state, and responses simultaneously, increasing the difficulty of troubleshooting.
It is recommended that each Middleware be responsible for one clear category of functionality, and that tests be written for critical logic.
16. Common Questions
1. What is the difference between Middleware and Tool?
Tool is responsible for executing specific business functions, such as querying courses or reading data.
Middleware is responsible for adding cross-cutting logic such as logging, retries, and checks at specific stages of the Agent execution flow.
2. Does before_agent execute only once each time?
It usually executes once in a normal complete Agent invocation. Interruptions, resumptions, or exceptional flows may affect the actual lifecycle.
3. Will before_model execute multiple times?
Yes. If the Agent requires multiple rounds of model calls, before_model will run again before the corresponding calls.
4. What is the difference between wrap_model_call and before_model?
before_model is mainly used for state updates and flow control before the model call.
wrap_model_call, on the other hand, wraps the actual model request through a handler, allowing control over whether to call, how to retry, and how to handle the model response.
5. Can wrap_tool_call return a dict?
A plain state dictionary cannot be returned directly as a tool result.
It should return a ToolMessage or Command that conforms to the tool execution protocol.
6. How to modify Agent State?
A Node-style Hook can return a state update dictionary, and LangGraph merges it into the Agent State according to the Reducer.
7. Can Middleware control the early termination of an Agent?
Yes. Declare it in a node hook that supports flow jumps can_jump_to, and return the corresponding routing instruction.
8. What should be used when a model API call fails?
You can use wrap_model_call to customize retries, or prefer LangChain's built-in ModelRetryMiddleware.
9. Is the execution order of multiple Middleware important?
Yes. Especially since Wrap-style middleware uses a nested execution structure, the order affects request wrapping, retries, and error handling.
10. Does Middleware support asynchronous execution?
Yes. LangChain provides corresponding async hooks, such as abefore_model、awrap_model_call , etc. For specific usage, please refer to the API Reference.
11. Can after_agent guarantee resource cleanup?
Not fully. When a task encounters an exception, interruption, or cancellation, you should not rely on after_agent being executed. Resource cleanup should be done through a separate reliable mechanism.
12. When should Middleware be used?
When certain logic needs to be reused across multiple Agents or across multiple model and tool calls, and does not belong to the core business of a particular tool, you can consider Middleware.
Summary
LangChain Middleware provides a flexible execution extension mechanism for Agents.
This chapter introduces six core hooks:
before_agent: executed before the Agent starts.before_model: executed before the model call.wrap_model_call: wraps the model request.after_model: executed after the model response.wrap_tool_call: wraps tool execution.after_agent: executed after the Agent completes normally.
You can simply remember:
Node-style:执行检查、更新 State
Wrap-style:拦截调用、重试、处理异常
简单逻辑:使用装饰器
复杂逻辑:继承 AgentMiddleware
常见功能:优先考虑内置 Middleware
In real projects, it is recommended to start using Middleware with logging, execution limits, and model error handling, then gradually expand to dynamic model selection, human review, and state management.
Core principles:Let Middleware handle reusable execution control and cross-cutting logic, and let Tool handle specific business operations, keeping the Agent structure clear and easy to test and maintain.