Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

LangChain Middleware Hooks — @before_model and @after_model

LangChain Middleware Hooks — @before_model and @after_model

In a LangChain Agent, @before_model and @after_model are two very commonly used Middleware hooks.

They execute before and after the model call respectively, and can be used for message preprocessing, context management, input checks, response review, and flow control.

Unlike ordinary tools, Middleware does not need to be actively selected by the model; instead, it is run by the Agent execution framework at the corresponding stage.

This chapter is based on LangChain 1.x and introduces the working mechanism, state updates, message trimming, reply replacement, and can_jump_to flow control.


1. The Difference Between before_model and after_model

A typical Agent execution loop is as follows:

用户输入

    ↓

before_model

    ↓

模型调用

    ↓

after_model

    ↓

是否需要调用工具?

    ├── 是 → 执行工具 → 回到 before_model

    └── 否 → 返回最终结果

The main differences between the two:

Comparison Item before_model after_model
Execution Timing Before the model call After the model produces a response
Main objects Input messages and current state Model response and current state
Typical use Message management, input checks, early termination Response review, message correction, result statistics
Number of runs Possibly multiple times Possibly multiple times
Flow control Supports can_jump_to Supports can_jump_to

If the Agent needs multiple rounds of tool calls, the model may also be called multiple times, so these two hooks are not necessarily executed only once.


2. How to Define Hooks

Middleware can be created quickly with decorators.

Basic syntax:

Example

from

langchain.

agents

.

middleware

import

before_model

,

after_model

,

AgentState

from

langgraph.

runtime

import

Runtime

@

before_model

def

pre_model

(

state: AgentState

,

runtime: Runtime

)

None

:

   

"""Executed before the model call."""

   

print

(

"Preparing to call the model"

)

@

after_model

def

post_model

(

state: AgentState

,

runtime: Runtime

)

None

:

   

"""Executed after the model call."""

   

print

(

"The model has returned a result"

)

Then pass the two middleware to create_agent():

agent = create_agent(

    model="deepseek:deepseek-flash",

    tools=[],

    middleware=[pre_model, post_model]

)

These two hooks receive two important parameters:

If you only want to log, you can return Nonewithout needing to modify the State.


3. @before_model: Processing Before the Model Call

@before_model It runs before every model call, can read the current message history, and submit state updates as needed.

For example, check the message count:

Example

from

langchain.

agents

.

middleware

import

before_model

,

AgentState

from

langgraph.

runtime

import

Runtime

@

before_model

def

inspect_messages

(

state: AgentState

,

runtime: Runtime

)

None

:

   

"""Check the message count before this model call."""

    messages

=

state.

get

(

"messages"

,

[

]

)

    human_count

=

sum

(

msg.

type

==

"human"

for

msg

in

messages

)

   

print

(

f

"Total messages: {len(messages)}, user messages: {human_count}"

)

Note that the message count is not equal to the number of conversation turns.

A single Agent tool call may add multiple messages such as AIMessage and ToolMessage.


4. Scenario 1: Limiting Conversation History Length

As the conversation grows, the number of messages in the Agent State can keep increasing, consuming more context tokens.

You can use before_model to manage history messages, but you must understand how the add_messages Reducer works.

Incorrect Writing

return {"messages": messages[-6:]}

This approach does not guarantee that only the most recent six messages are kept.

Because messages Use add_messages merge updates. Other existing messages are not automatically deleted just because they do not appear in the new list.

Correct approach: delete messages with RemoveMessage

If you need to actually modify the saved message history, you can use RemoveMessage。

First, here is a simple example that deletes early plain-text user and AI messages.

Example

from

langchain.

agents

.

middleware

import

before_model

,

AgentState

from

langchain.

messages

import

RemoveMessage

from

langgraph.

runtime

import

Runtime

@

before_model

def

trim_simple_history

(

state: AgentState

,

runtime: Runtime

)

dict

|

None

:

   

"""Trim a demo conversation that has no tool calls."""

    messages

=

state.

get

(

"messages"

,

[

]

)

   

if

len

(

messages

)

<=

6

:

       

return

None

   

Only for simple conversations without tool calls

   

if

any

(

getattr

(

msg

,

"tool_calls"

,

[

]

)

or

msg.

type

==

"tool"

for

msg

in

messages

)

:

       

return

None

    old

=

[

msg

for

msg

in

messages

[

:-

6

]

if

msg.

id

]

   

if

not

old:

       

return

None

   

return

{

"messages"

:

[

RemoveMessage

(

id

=

msg.

id

)

for

msg

in

old

]

}

This code differs from the original; it explicitly submits a delete instruction to the Reducer.

But to avoid accidentally deleting tool messages, the example deliberately skips conversation history that contains Tool Calling.

**Note:** In a real project you cannot simply delete messages arbitrarily by count, and especially must not separate tool calls in AIMessage from their corresponding ToolMessage.

Recommended approach: use SummarizationMiddleware

For long conversations, it is more recommended to use LangChain's built-in SummarizationMiddlewarewhich generates a summary when the context reaches a threshold, instead of blindly keeping the last few messages.

If you need to directly clear old tool outputs, you can also consider ContextEditingMiddleware。

Therefore, the recommendations are:

Requirements Recommended approach
Simple demo of deleting history messages RemoveMessage
Long conversation compression SummarizationMiddleware
Clearing old tool results ContextEditingMiddleware
Only change the context of this model request Use an appropriate model request wrapper or context-handling mechanism

5. Scenario 2: Input Content Checks

You can use before_model to check user input before the model call and end the Agent early when a rule is met.

For example, for certain demo-only keywords, return a prompt directly without calling the model.

Note that it is not advisable to treat words like "password" and "ID card" as completely forbidden keywords, because users may simply be asking about technical knowledge such as password security or identity authentication.

Example: Demo Keyword Interception

Example

from

dotenv

import

load_dotenv

from

langchain.

agents

import

create_agent

from

langchain.

agents

.

middleware

import

before_model

,

AgentState

from

langchain.

messages

import

AIMessage

from

langgraph.

runtime

import

Runtime

load_dotenv

(

)

@

before_model

(

can_jump_to

=

[

"end"

]

)

def

content_filter

(

state: AgentState

,

runtime: Runtime

)

dict

|

None

:

   

"""Intercept the agreed demo keywords."""

    users

=

[

msg

for

msg

in

state

[

"messages"

]

if

msg.

type

==

"human"

]

   

if

not

users:

       

return

None

    content

=

users

[

1

]

.

content

   

if

isinstance

(

content

,

str

)

and

"BLOCK_DEMO"

in

content:

       

return

{

           

"jump_to"

:

"end"

,

           

"messages"

:

[

AIMessage

(

content

=

"This request has been intercepted by the demo rule."

)

]

       

}

   

return

None

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

]

,

    middleware

=

[

content_filter

]

,

    system_prompt

=

"You are the programming assistant of Runoob Tutorial RUNOOB."

)

result

=

agent.

invoke

(

{

"messages"

:

[

{

"role"

:

"user"

,

"content"

:

"BLOCK_DEMO"

}

]

}

)

print

(

result

[

"messages"

]

[

1

]

.

content

)

Output:

该请求已被演示规则拦截。

There are two key points here:

**Note:** This example only demonstrates input interception and should not be treated as a complete sensitive-information detection or security protection system.

If you need to protect users' personal information, use more reliable rules, data-detection mechanisms, and server-side permission controls.


6. @after_model: Post-Processing After Model Response

@after_model It executes after the model returns a response, making it suitable for checking or logging output content.

It may run after the final reply, or after the model requests a tool call.

Therefore, before processing the final text, you should first check whether the model produced a tool call tool_calls。

Example: Check Whether the Model Requested a Tool

Example

from

langchain.

agents

.

middleware

import

after_model

,

AgentState

from

langgraph.

runtime

import

Runtime

@

after_model

def

inspect_output

(

state: AgentState

,

runtime: Runtime

)

None

:

   

"""Check the model response type."""

    last

=

state

[

"messages"

]

[

1

]

   

if

getattr

(

last

,

"tool_calls"

,

[

]

)

:

       

print

(

"Model requested tool:"

,

[

c

[

"name"

]

for

c

in

last.

tool_calls

]

)

   

else

:

       

print

(

"Model text:"

,

str

(

last.

content

)

[

:

100

]

)

If the model requests a tool, the Agent may then continue to the tool node.

If the model produced no tool call and there is no other flow control, the current loop usually ends.


7. Scenario 3: Reviewing and Replacing Model Replies

For some applications, you need to check the content after the model returns a reply.

For example, a system may forbid showing an agreed internal test marker to users.

Here, the following is used INTERNAL_DEMO_ONLY as an interception string for teaching purposes.

Why can't you simply add a new AIMessage?

The original uses the following approach:

return {

    "messages": [AIMessage(content="Replaced reply")]

}

This does not guarantee overwriting the old reply, because a new AIMessage usually has a different message ID.

To replace an existing message, use the same message ID so that the add_messages Reducer performs the replacement.

Correct example: preserve the original message ID

Example

from

langchain.

agents

.

middleware

import

after_model

,

AgentState

from

langchain.

messages

import

AIMessage

from

langgraph.

runtime

import

Runtime

@

after_model

def

response_audit

(

state: AgentState

,

runtime: Runtime

)

dict

|

None

:

   

"""Replace the final reply containing the demo internal marker."""

    last

=

state

[

"messages"

]

[

1

]

   

if

last.

type

!=

"ai"

or

last.

tool_calls

:

       

return

None

   

if

not

isinstance

(

last.

content

,

str

)

or

"INTERNAL_DEMO_ONLY"

not

in

last.

content

:

       

return

None

   

return

{

"messages"

:

[

AIMessage

(

       

id

=

last.

id

,

        content

=

"This reply contains a demo internal marker and has been replaced."

   

)

]

}

The key code here is:

id=last.id

Since the new and old messages use the same ID, the Reducer can replace the existing model reply instead of appending an extra answer to the message history.

**Note:** If unreviewed message fragments have already been sent to the frontend via Streaming, the replacement in after_model cannot retract the already transmitted content.

For content that must be strictly reviewed before display, buffer the response and complete the review before sending it to the user, or use other reliable output protection mechanisms.


8. Scenario 4: Adding a Notice to the Final Answer

If you need to automatically add an explanation after the model's final answer, you can also update the last message via after_model.

For example, add a fixed notice to AI-generated content.

Example: Appending a Content Disclaimer

Example

from

langchain.

agents

.

middleware

import

after_model

,

AgentState

from

langchain.

messages

import

AIMessage

from

langgraph.

runtime

import

Runtime

DISCLAIMER

=

"\n\n---\nThe above content is generated by AI and is for reference only."

@

after_model

def

append_disclaimer

(

state: AgentState

,

runtime: Runtime

)

dict

|

None

:

   

"""Add a notice after the final text reply."""

    last

=

state

[

"messages"

]

[

1

]

   

if

last.

type

!=

"ai"

or

last.

tool_calls

:

       

return

None

   

if

not

isinstance

(

last.

content

,

str

)

or

not

last.

content

or

DISCLAIMER

in

last.

content

:

       

return

None

   

return

{

"messages"

:

[

AIMessage

(

id

=

last.

id

,

content

=

last.

content

)

]

}

If the model returns:

Python 是一门适合初学者的编程语言。

the updated message content is:

Python 是一门适合初学者的编程语言。



---

以上内容由 AI 生成,仅供参考。

Here we again use id=last.id to replace the original reply.

It also checks whether the disclaimer already exists to avoid duplicate appends.

**Note:** For teaching purposes, a new AIMessage is constructed here. In production, if you need to preserve the original message's response metadata, usage information, and so on, you may prefer to copy the original message and update only the necessary fields.


9. can_jump_to: Controlling Agent Execution Flow

can_jump_to Used to declare which targets the hook is allowed to route the Agent to.

Optional targets include:

Goals Meaning Common Use Cases
"end" End the Agent's main loop Early exit, input interception
"model" Route to the model execution path When model processing needs to be redone
"tools" Route to the tool node Flow control when a valid tool call request already exists

For example:

@before_model(can_jump_to=["end"])

def check_exit(state, runtime):

    ...

Only when a routing target has been explicitly designed should you return the corresponding jump_to values.

Example: Ending Early When the User Says Goodbye

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

conditional_exit

(

state: AgentState

,

runtime: Runtime

)

dict

|

None

:

   

"""Return a fixed reply directly when the user sends a closing message."""

    users

=

[

m

for

m

in

state

[

"messages"

]

if

m.

type

==

"human"

]

   

if

not

users

or

not

isinstance

(

users

[

1

]

.

content

,

str

)

:

       

return

None

   

if

users

[

1

]

.

content

.

strip

(

)

.

lower

(

)

in

{

"goodbye"

,

"Bye"

,

"bye"

}

:

       

return

{

           

"jump_to"

:

"end"

,

           

"messages"

:

[

AIMessage

(

content

=

"Goodbye! Welcome to continue learning programming next time."

)

]

       

}

   

return

None

This example lets the Agent return a fixed reply directly for a simple closing message, without calling the model.

One thing to note in particular:


10. Complete Example: Input Checks and Reply Processing

Below, before_model and after_model are combined into a complete example.

This Agent supports:

Filename:middleware_hooks_demo.py

Install dependencies:

pip install -U langchain langgraph langchain-deepseek python-dotenv

Configure .env:

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_model

,

after_model

,

AgentState

from

langchain.

messages

import

AIMessage

from

langgraph.

runtime

import

Runtime

load_dotenv

(

)

DISCLAIMER

=

"\n\n---\nThe above content is generated by AI and is for reference only."

@

before_model

(

can_jump_to

=

[

"end"

]

)

def

check_input

(

state: AgentState

,

runtime: Runtime

)

dict

|

None

:

   

"""Check input and log the message count."""

    messages

=

state.

get

(

"messages"

,

[

]

)

   

print

(

"[before_model] Message count:"

,

len

(

messages

)

)

    users

=

[

m

for

m

in

messages

if

m.

type

==

"human"

]

   

if

users

and

isinstance

(

users

[

1

]

.

content

,

str

)

:

       

if

"BLOCK_DEMO"

in

users

[

1

]

.

content

:

           

return

{

               

"jump_to"

:

"end"

,

               

"messages"

:

[

AIMessage

(

content

=

"The request was intercepted by the demo rule."

)

]

           

}

   

return

None

@

after_model

def

process_output

(

state: AgentState

,

runtime: Runtime

)

dict

|

None

:

   

"""Check the final text reply and append a notice."""

    last

=

state

[

"messages"

]

[

1

]

   

if

last.

type

!=

"ai"

:

       

return

None

   

if

last.

tool_calls

:

       

print

(

"[after_model] The model requested a tool"

)

       

return

None

   

print

(

"[after_model] The model has generated a text reply"

)

   

if

not

isinstance

(

last.

content

,

str

)

or

not

last.

content

or

DISCLAIMER

in

last.

content

:

       

return

None

   

return

{

"messages"

:

[

AIMessage

(

id

=

last.

id

,

content

=

last.

content

)

]

}

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

]

,

    middleware

=

[

check_input

,

process_output

]

,

    system_prompt

=

"You are a programming learning assistant for Runoob Tutorial RUNOOB; answer in concise Chinese."

)

def

ask

(

question:

str

)

:

   

print

(

"\nUser:"

,

question

)

    result

=

agent.

invoke

(

{

"messages"

:

[

{

"role"

:

"user"

,

"content"

: question

}

]

}

)

   

print

(

"AI:"

,

result

[

"messages"

]

[

1

]

.

content

)

if

name

==

"main"

:

    ask

(

"Is Python suitable for beginners?"

)

    ask

(

"BLOCK_DEMO"

)

Possible run results

用户:Python 适合初学者吗?

[before_model] 消息数量: 1

[after_model] 模型已生成文本回复

AI:Python 语法相对简洁,适合初学者入门。



---

以上内容由 AI 生成,仅供参考。



用户:BLOCK_DEMO

[before_model] 消息数量: 1

AI:请求已被演示规则拦截。

Here the responsibilities of the two hooks are very clear:

When before_model ends the Agent directly, the model does not run along the normal path, so after_model usually does not process the fixed reply produced by this interception.


11. The Difference Between before_model and wrap_model_call

Sometimes you need to modify messages, and sometimes you need to truly intercept the model request; these two needs should be handled differently.

Requirements Recommended approach
Check the current Agent State before_model
Update custom State fields before_model
End the Agent early before_model + can_jump_to
Modify the messages of this model request wrap_model_call
Switch models or retry an API request wrap_model_call
Check model output after_model
Replace the generated final message after_model + same message ID

An important difference is:

before_model The returned messages is handed to the Reducer as a state update, whereas wrap_model_call can modify the current model request without having to change this input by deleting history messages.

Therefore, for scenarios where you only want to temporarily adjust the model context without deleting the saved message history, wrap_model_call is usually more suitable.


12. Frequently asked questions

1. Does before_model execute every round?

If the Agent calls the model multiple times, before_model usually executes before each corresponding model call.

2. Can after_model intercept tool calls?

It can check the tool_calls in the model response tool_callsand decide subsequent execution based on the currently supported flow-control mechanism.

But it is not equivalent to tool permission control. When you need to control real tool operations, validation should also be done at the tool execution layer.

3. Why does returning the last six messages not delete the old messages?

Because messages uses the add_messages Reducer. Returning a shorter message list alone does not delete old messages.

When deletion is needed, use a supported mechanism such as RemoveMessage.

4. Why do two AI replies appear after after_model returns an AIMessage?

Because the new message uses a different ID and is appended as a new message.

To replace the old message, reuse the original message ID.

5. Why does content filtering use AIMessage?

Because the interception prompt is content the assistant returns to the user, not a newly sent user message.

Therefore HumanMessage should not be used.

6. Can can_jump_to=["tools"] directly execute any tool?

No. The tool node still requires a valid tool call request and arguments.

7. Can multiple before_model hooks be registered at the same time?

Yes, but be mindful of the interactions among the execution order, state updates, and jump behavior of multiple Middleware.

8. Is after_model suitable for complete content safety review?

It can be part of the review process, but it cannot replace dedicated security detection and permission control.

Especially in streaming scenarios, content already sent cannot rely on after_model to retract it automatically.

9. How do you send custom progress in middleware?

You can use the Runtime's StreamWriter in an environment that supports streaming execution and stream_mode="custom" consume events via it.

10. How do you limit the context of long conversations?

It is recommended to prefer LangChain's built-in SummarizationMiddleware rather than simply truncating a fixed number of messages.

11. Is after_model always the last step of the Agent?

No. If the model requested a tool, execution may continue to call the tool after after_model runs, and then re-enter the model execution loop.

12. How do you test whether the middleware actually takes effect?

You can inspect the returned messages and State, or use stream_mode="updates" to observe the node execution process.

For message replacement logic, it is best to test whether the message ID remains unchanged and whether the history message count is as expected.


Summary

@before_model and @after_model are two important Middleware hooks in a LangChain Agent.

Main differences:

before_model:

    模型执行前

    检查输入、管理 State、控制执行流程



after_model:

    模型执行后

    审核结果、修改消息、记录输出信息

This chapter focused on:

Core principles:Use node hooks when you need to read or update Agent State; consider wrapper hooks when you need to modify the current model request. When handling message history, you must obey the merge rules of the add_messages Reducer.