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

LangChain Middleware Hooks - @before_agent and @after_agent

LangChain Middleware Hooks - @before_agent and @after_agent

In LangChain Agents, @before_agent and @after_agent are two Agent-level Middleware hooks.

They run before the Agent's main execution flow begins and after it completes normally, respectively, making them suitable for tasks such as input preprocessing, state initialization, access checks, result formatting, and execution statistics.

Unlike [hooks] executed before and after each model call, @before_model and @after_model these two hooks act on the entire Agent lifecycle.

This section is based on LangChain 1.x and introduces the basic usage, state updates, execution control, and practical applications of the two hooks.


1. The Difference Between before_agent and after_agent

The execution flow of a simple Agent can be understood as follows:

用户输入

    ↓

before_agent

    ↓

before_model

    ↓

模型调用

    ↓

after_model

    ↓

是否调用工具?

    ├── 是 → 执行工具 → 再次调用模型

    └── 否 → 继续

    ↓

after_agent

    ↓

返回最终结果

Among them, before_agent and after_agent mainly control the beginning and ending stages of the Agent's overall execution.

Comparison Item before_agent after_agent
Execution Timing Before the Agent's main flow begins After the Agent completes normally
Number of normal runs Usually once Usually once
Main Use Input checks, state initialization Result organization, statistics, ending logs
State Update Supported Supported
Flow control Supports configuring can_jump_to Supports configuring can_jump_to

**Note:** If an exception or interruption occurs during Agent execution, or if it resumes via a Checkpointer, the actual hook execution may differ from a normal complete call.


2. Basic Syntax of the Two Hooks

You can quickly define Agent lifecycle hooks using decorators.

Example

from

langchain.

agents

.

middleware

import

before_agent

,

after_agent

,

AgentState

from

langgraph.

runtime

import

Runtime

@

before_agent

def

start_hook

(

state: AgentState

,

runtime: Runtime

)

None

:

   

"""Runs before the Agent starts."""

   

print

(

"Agent starts executing"

)

@

after_agent

def

finish_hook

(

state: AgentState

,

runtime: Runtime

)

None

:

   

"""Runs after the Agent completes normally."""

   

print

(

"Agent execution complete"

)

When using, add middleware:

agent = create_agent(

    model="deepseek:deepseek-flash",

    tools=[],

    middleware=[start_hook, finish_hook]

)

The main parameters received by the two hooks:

If you do not need to modify the state, you can return None, or return nothing explicitly.


3. @before_agent: Input Preprocessing

@before_agent You can normalize user input before the Agent executes.

For example, remove extra spaces before and after the question and convert full-width spaces to ordinary spaces.

Note that the messages in AgentState use the messages Use add_messages Reducer, so you cannot simply return a brand-new message and assume the original message has been replaced.

The correct approach is to reuse the original message ID.

Example: Normalizing a User Message

Example

from

dotenv

import

load_dotenv

from

langchain.

agents

import

create_agent

from

langchain.

agents

.

middleware

import

before_agent

,

AgentState

from

langchain.

messages

import

HumanMessage

from

langgraph.

runtime

import

Runtime

load_dotenv

(

)

@

before_agent

def

preprocess_input

(

state: AgentState

,

runtime: Runtime

)

dict

|

None

:

   

"""Normalize the most recent user message."""

    users

=

[

msg

for

msg

in

state.

get

(

"messages"

,

[

]

)

if

msg.

type

==

"human"

]

   

if

not

users:

       

return

None

    last

=

users

[

1

]

   

if

not

isinstance

(

last.

content

,

str

)

:

       

return

None

    cleaned

=

last.

content

.

replace

(

" "

,

" "

)

.

strip

(

)

   

if

cleaned

==

last.

content

:

       

return

None

   

return

{

"messages"

:

[

HumanMessage

(

id

=

last.

id

,

content

=

cleaned

)

]

}

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

]

,

    middleware

=

[

preprocess_input

]

,

    system_prompt

=

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

)

result

=

agent.

invoke

(

{

   

"messages"

:

[

{

"role"

:

"user"

,

"content"

:

"  What is Python? "

}

]

}

)

print

(

result

[

"messages"

]

[

1

]

.

content

)

In this example, the original user input is:

  Python 是什么?  

After preprocessing, the message content becomes:

Python 是什么?

What the model receives is the normalized question.

Key points:HumanMessage(id=last.id, ...) The original message ID is preserved, so add_messages can replace the corresponding message instead of appending a duplicate user message.

This example only handles plain text and does not directly modify multimodal content such as images or audio.


4. @before_agent: Initializing Custom State

For Agents that need to maintain business state, you can initialize missing fields in before_agent.

For example, a learning assistant needs to save the current learning level and learning goal.

Example: Initializing Learning State

Example

from

typing_extensions

import

NotRequired

from

langchain.

agents

import

AgentState

from

langchain.

agents

.

middleware

import

before_agent

from

langgraph.

runtime

import

Runtime

class

LearningState

(

AgentState

)

:

    user_level: NotRequired

[

str

]

    current_goal: NotRequired

[

str

]

@

before_agent

(

state_schema

=

LearningState

)

def

init_learning_state

(

state: LearningState

,

runtime: Runtime

)

dict

|

None

:

   

"""Set default values for missing learning fields."""

    updates

=

{

}

   

if

"user_level"

not

in

state:

        updates

[

"user_level"

]

=

"Beginner"

   

if

"current_goal"

not

in

state:

        updates

[

"current_goal"

]

=

"Learn Python"

   

return

updates

or

None

Suppose the input state only has:

{

    "messages": [...]

}

The middleware can add:

{

    "user_level": "入门",

    "current_goal": "学习 Python"

}

A custom LearningState is used here to declare extended fields.

**Note:** Custom fields are not in the default structure of AgentState and need to be declared through state_schema and other supported means.

If the user has already provided the relevant fields, the example does not overwrite the original values.


5. @before_agent: Access Control

In some applications, the Agent needs to check whether the user can use a specific feature before executing.

For example, ordinary visitors can query courses but cannot call administrative functions.

You can use before_agent to perform an initial check at the start of the flow.

However, the actual user identity and permissions must be confirmed by a trusted backend; you cannot rely on the model to judge by itself, nor only on keywords in the user's message.

Example: Intercepting Requests Based on the Runtime Role

Here, Context is used to simulate a role already confirmed by the backend.

Example

from

dataclasses

import

dataclass

from

langchain.

agents

import

create_agent

from

langchain.

agents

.

middleware

import

before_agent

,

AgentState

from

langchain.

messages

import

AIMessage

from

langgraph.

runtime

import

Runtime

@

dataclass

class

UserContext:

    role:

str

=

"guest"

    allow_admin:

bool

=

False

@

before_agent

(

can_jump_to

=

[

"end"

]

)

def

access_control

(

state: AgentState

,

runtime: Runtime

[

UserContext

]

)

dict

|

None

:

   

"""Demonstrate an access check based on trusted context."""

    ctx

=

runtime.

context

    users

=

[

m

for

m

in

state.

get

(

"messages"

,

[

]

)

if

m.

type

==

"human"

]

   

if

not

users:

       

return

None

    text

=

users

[

1

]

.

content

   

if

isinstance

(

text

,

str

)

and

text.

startswith

(

"/admin"

)

:

       

if

not

ctx.

allow_admin

:

           

return

{

               

"jump_to"

:

"end"

,

               

"messages"

:

[

AIMessage

(

content

=

"The current account does not have permission for administrative functions."

)

]

           

}

   

return

None

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

]

,

    context_schema

=

UserContext

,

    middleware

=

[

access_control

]

)

result

=

agent.

invoke

(

   

{

"messages"

:

[

{

"role"

:

"user"

,

"content"

:

"/admin delete course"

}

]

}

,

    context

=

UserContext

(

role

=

"guest"

,

allow_admin

=

False

)

)

print

(

result

[

"messages"

]

[

1

]

.

content

)

Output:

当前账户没有管理功能权限。

Here, /admin is only a command prefix for demonstration, not a complete security control.

**Important:** Real management tools must still perform permission checks at the tool execution layer or in the backend API.

Even if before_agent intercepts some requests, you cannot assume that the user cannot trigger restricted tools through other prompts.

For strict access control, a more reliable design is:


6. can_jump_to: Ending the Agent Early

before_agent You can configure can_jump_toto declare the allowed flow jump targets.

For example:

@before_agent(can_jump_to=["end"])

def check_request(state, runtime):

    ...

If the input does not meet business rules, you can return:

{

    "jump_to": "end",

    "messages": [AIMessage(content="The request does not meet the requirements.")]

}

This allows the current execution flow to end early without calling the model normally.

Supported jump targets include:

Goals Description
"end" End the main execution flow
"model" Enter the model execution path
"tools" Enter the tool node; valid tool call information is required

Usually, the most common jump scenario for before_agent is "end"。

**Note:** You should not assume that setting jump_to="tools" allows you to directly execute any tool. The tool node still requires a valid tool call context.


7. @after_agent: Statistics After Execution Completes

@after_agent It runs when the Agent completes execution normally and can gather statistics on the message history.

For example:

Note that the number of messages is not equal to the number of model API calls.

Example: Counting Execution Results

Example

from

langchain.

agents

.

middleware

import

after_agent

,

AgentState

from

langgraph.

runtime

import

Runtime

@

after_agent

def

conversation_stats

(

state: AgentState

,

runtime: Runtime

)

None

:

   

"""Output the message statistics for this Agent run."""

    messages

=

state.

get

(

"messages"

,

[

]

)

    humans

=

sum

(

m.

type

==

"human"

for

m

in

messages

)

    tool_requests

=

sum

(

len

(

getattr

(

m

,

"tool_calls"

,

[

]

)

)

for

m

in

messages

)

    tool_results

=

sum

(

m.

type

==

"tool"

for

m

in

messages

)

   

print

(

"Total messages:"

,

len

(

messages

)

)

   

print

(

"User messages:"

,

humans

)

   

print

(

"Tool requests:"

,

tool_requests

)

   

print

(

"Tool results:"

,

tool_results

)

If the Agent made one tool call, you might get:

消息总数: 4

用户消息: 1

工具请求: 1

工具结果: 1

The actual data depends on the Agent's execution path.

If the Agent uses a Checkpointer to save multi-turn history, the statistics here may be cumulative messages in the current State, not just those newly added in this run.

If you need an accurate count of model API calls for a single run, it is recommended to use a dedicated Middleware counter or model call tracing data.


8. Saving Statistics Through Custom State

Besides printing logs directly, you can also write the statistics into the Agent State.

This way, the caller can read the statistics from the final result.

Example: Returning Custom Statistics Fields

Example

from

typing_extensions

import

NotRequired

from

langchain.

agents

import

AgentState

from

langchain.

agents

.

middleware

import

after_agent

from

langgraph.

runtime

import

Runtime

class

StatsState

(

AgentState

)

:

    tool_result_count: NotRequired

[

int

]

    message_count: NotRequired

[

int

]

@

after_agent

(

state_schema

=

StatsState

)

def

save_stats

(

state: StatsState

,

runtime: Runtime

)

dict

:

   

"""Write the current message statistics into the State."""

    messages

=

state.

get

(

"messages"

,

[

]

)

   

return

{

       

"message_count"

:

len

(

messages

)

,

       

"tool_result_count"

:

sum

(

m.

type

==

"tool"

for

m

in

messages

)

   

}

After the Agent completes execution normally, you can read:

result["message_count"]

result["tool_result_count"]

This approach is suitable for returning statistics to the application.

However, note that they are statistics of the current message state and are not necessarily independent counts for this call.


9. @after_agent: Formatting the Final Output

Besides recording statistics, you can also use after_agent to uniformly adjust the final answer.

For example, automatically append an AI content disclaimer.

However, the approach in the original text of adding a new AIMessage may result in a duplicate answer.

Because messages uses the add_messages Reducer, to replace an existing message you should preserve the original message ID.

Example: Adding a Footer to the Final Reply

Example

from

langchain.

agents

.

middleware

import

after_agent

,

AgentState

from

langchain.

messages

import

AIMessage

from

langgraph.

runtime

import

Runtime

FOOTER

=

"\n\n---\nProvided by the Runoob Tutorial RUNOOB AI assistant; content is for reference only."

@

after_agent

def

format_output

(

state: AgentState

,

runtime: Runtime

)

dict

|

None

:

   

"""Add a note to the final text reply."""

    messages

=

state.

get

(

"messages"

,

[

]

)

   

if

not

messages:

       

return

None

    last

=

messages

[

1

]

   

if

last.

type

!=

"ai"

or

getattr

(

last

,

"tool_calls"

,

[

]

)

:

       

return

None

   

if

not

isinstance

(

last.

content

,

str

)

or

not

last.

content

or

FOOTER

in

last.

content

:

       

return

None

    updated

=

last.

model_copy

(

update

=

{

"content"

: last.

content

}

)

   

return

{

"messages"

:

[

updated

]

}

If the model's original answer is:

Python 语法简洁,适合初学者学习。

the content finally returned will become:

Python 语法简洁,适合初学者学习。



---

由Runoob Tutorial RUNOOB AI 助手提供,内容仅供参考。

Here, the following is used model_copy(update=...) to preserve the original AIMessage's ID and other message fields, and update only the content.

Therefore, add_messages will replace the corresponding old reply instead of appending a brand-new one.

**Note:** If Streaming is used to push model text in real time, the text already sent to the browser will not update automatically because after_agent modified the final State.

If you need to display the formatted final content, you can send a final result event after execution ends, or render a fixed footer separately on the frontend.


10. after_agent and Custom Streaming Events

If you want to push statistics to the frontend in real time, you can send Custom Streaming events in a supported runtime context.

You need to receive them through stream_mode="custom" and use the corresponding event structure according to the LangGraph version.

Example: Sending a Completion Statistics Event

Example

from

langchain.

agents

import

create_agent

from

langchain.

agents

.

middleware

import

after_agent

,

AgentState

from

langgraph.

runtime

import

Runtime

@

after_agent

def

stream_stats

(

state: AgentState

,

runtime: Runtime

)

None

:

   

"""Send a statistics event after the Agent completes."""

   

if

runtime.

stream_writer

:

        messages

=

state.

get

(

"messages"

,

[

]

)

        runtime.

stream_writer

(

{

           

"type"

:

"stats"

,

           

"messages"

:

len

(

messages

)

,

           

"tool_results"

:

sum

(

m.

type

==

"tool"

for

m

in

messages

)

       

}

)

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

]

,

    middleware

=

[

stream_stats

]

)

for

event

in

agent.

stream

(

   

{

"messages"

:

[

{

"role"

:

"user"

,

"content"

:

"Hello" (Chinese)

}

]

}

,

    stream_mode

=

"custom"

,

    version

=

"v2"

)

:

   

if

event

[

"type"

]

==

"custom"

and

event

[

"data"

]

.

get

(

"type"

)

==

"stats"

:

       

print

(

"Statistics event:"

,

event

[

"data"

]

)

After normal execution completes, you may receive:

统计事件: {'type': 'stats', 'messages': 2, 'tool_results': 0}

Here, the version="v2" streaming format is used, and events are read through the following fields:

event["type"]

event["ns"]

event["data"]

This differs from the old version that directly unpacked (mode, chunk) the values; the formats are different.

**Note:** The availability of StreamWriter depends on the execution context. If you only need to obtain statistics after a normal invoke() completes, you can write the statistics directly into the State; there is no need to use Streaming.


11. Complete Example: Four Hooks Working Together

The following combines before_agent, before_model, after_model, and after_agent to create a simple Agent lifecycle demonstration.

The weather tool in the example returns simulated data, not real weather.

Filename:agent_lifecycle_demo.py

Install dependencies:

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

in .env Configure in :

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

,

after_agent

,

before_model

,

after_model

,

AgentState

from

langchain.

tools

import

tool

from

langgraph.

runtime

import

Runtime

load_dotenv

(

)

@

before_agent

def

start_session

(

state: AgentState

,

runtime: Runtime

)

None

:

   

print

(

">>> Agent starts"

)

@

before_model

def

before_call

(

state: AgentState

,

runtime: Runtime

)

None

:

   

print

(

"[Before model call] Message count:"

,

len

(

state.

get

(

"messages"

,

[

]

)

)

)

@

after_model

def

after_call

(

state: AgentState

,

runtime: Runtime

)

None

:

    last

=

state

[

"messages"

]

[

1

]

    names

=

[

c

[

"name"

]

for

c

in

getattr

(

last

,

"tool_calls"

,

[

]

)

]

   

print

(

"[After model call] Tool requests:"

,

names

or

"None"

)

@

after_agent

def

finish_session

(

state: AgentState

,

runtime: Runtime

)

None

:

    messages

=

state.

get

(

"messages"

,

[

]

)

   

print

(

"<<< Agent complete, total messages:"

,

len

(

messages

)

)

@

tool

def

get_weather

(

city:

str

)

str

:

   

"""Query mock weather for a given city."""

    weather

=

{

"Hangzhou"

:

"Sunny, 25°C"

,

"Beijing"

:

"Cloudy, 18°C"

}

   

return

weather.

get

(

city

,

"No simulated weather data for this city"

)

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

get_weather

]

,

    middleware

=

[

start_session

,

before_call

,

after_call

,

finish_session

]

,

    system_prompt

=

"You are a Chinese assistant. Weather information must be queried using tools, and you must clearly state that the tool data is simulated."

)

result

=

agent.

invoke

(

{

   

"messages"

:

[

{

"role"

:

"user"

,

"content"

:

"Please use the tool to query the simulated weather in Hangzhou."

}

]

}

)

print

(

"AI:"

,

result

[

"messages"

]

[

1

]

.

content

)

Possible run results

>>> Agent 开始

[模型调用前] 消息数: 1

[模型调用后] 工具请求: ['get_weather']

[模型调用前] 消息数: 3

[模型调用后] 工具请求: 无

<<< Agent 完成,消息总数: 4



AI:杭州的模拟天气为晴天,25°C。

This example shows the responsibilities of the four hooks:

If the model does not call a tool, then before_model and after_model may execute only once.

If the model calls multiple tools consecutively, the actual number of hook executions may also increase.


12. How to Choose Between before_agent and before_model?

Both hooks can run before a model call, but they have different scopes.

Requirements Recommended hook Reason
Check the Agent's initial input for this run before_agent Located before the main execution flow begins
Initialize conversation state before_agent Avoid repeated initialization before every model call
Check every model request before_model The Agent may call the model multiple times
Control the next model call based on the current messages before_model Suitable for dynamic checks during loops
Temporarily modify input for this model request wrap_model_call Can modify ModelRequest

It can be simply understood as follows:

before_agent:整个 Agent 运行前的检查



before_model:每次模型调用前的检查


13. How to Choose Between after_agent and after_model?

Both hooks can run after the model produces a response, but they execute at different stages.

Requirements Recommended hook Reason
Check every model response after_model Executes immediately after the model responds
Determine whether the model requests a tool after_model Can directly check tool_calls
Count the complete Agent message history after_agent Obtain the final state upon normal completion
Uniformly format the final reply after_agent Suitable for final result processing
Release external resources when execution fails Mechanisms such as try/finally Cannot guarantee that after_agent runs on exceptions

For scenarios that need to review every model output, after_model should be preferred.

For scenarios such as final statistics and adding notes, after_agent is more suitable.


14. Quick Reference Table of the Six Middleware Hooks

Hook Execution scope Main Use Key mechanism
before_agent Agent start stage Input checks, initialization State updates, routing control
before_model Before each model call Message management, flow checks State updates, jump_to
wrap_model_call During model requests Retries, fallback, request modification handler、ModelRequest
after_model After each model response Review, state updates State Reducer
wrap_tool_call During tool execution Tool retries, caching, parameter modification handler、ToolCallRequest
after_agent Agent end stage Final statistics, result organization State updates

The six hooks can be divided into two categories:

Node-style:before_agent、before_model、after_model、after_agent。

Wrap-style:wrap_model_call、wrap_tool_call。

Node-style mainly handles state and flow, while Wrap-style mainly handles wrapping model or tool execution.


15. Production Environment Considerations

1. Do Not Only Check Tool Permissions in before_agent

before_agent can perform an initial access check, but real tools should still verify identity and permissions through a trusted backend at execution time.

2. Do Not Reinitialize Existing State

If you use a Checkpointer to save multi-turn conversations, before_agent should check whether a field already exists to avoid overwriting previously saved data on every call.

3. Do not treat after_agent as an exception cleanup hook

When an Agent encounters an exception or is interrupted, after_agent is not guaranteed to execute.

For resources such as database connections and file handles, use reliable context management or a finally mechanism.

4. Do not treat the message count as the number of API calls

Message history may contain user messages, AIMessage, ToolMessage, as well as historical content from multi-turn sessions.

When you need to accurately count model requests, use model call monitoring or a dedicated state counter.

5. Avoid leaking sensitive information in logs

Middleware can access messages, state, and the runtime Context; logs should avoid recording API keys, passwords, access tokens, or other sensitive data.

6. Note the difference between streaming output and final state

If the frontend has already received streaming text, State modifications in after_agent will not automatically retract that content.

For the final formatted result, you can send a complete result event after the stream ends, or handle unified display on the frontend.


16. Common Questions

1. Are before_agent and after_agent each executed exactly once?

In a normal complete run they are usually each executed once, but exceptions, interruptions, recovery, and similar situations can affect the execution path.

2. Can before_agent modify user input?

Yes. You can update messages by returning a state dictionary, and reuse the original message ID for replacement.

3. Why does directly returning a new HumanMessage increase the message count?

Because messages uses the add_messages Reducer. A new message has a different ID and is usually appended.

4. How do you initialize fields in before_agent?

You can extend AgentState and have before_agent return a state update dictionary containing default values.

5. Can before_agent end the Agent early?

Yes. When supported, by can_jump_to=["end"] declaring an end target and returning the corresponding routing instruction.

6. Can runtime.context be used for permission checks?

Yes, but identity and permission information in the Context must be provided by a trusted application backend.

7. Can after_agent modify the final reply?

Yes. For a plain-text AIMessage, you can reuse the original message ID and submit new message content so the Reducer replaces the old reply.

8. Can after_agent send custom Streaming events?

Yes, you can use StreamWriter in a supported streaming run context and receive them via custom mode.

9. Why does the message count reported by after_agent exceed the current turn?

If a Checkpointer is used to save history, the current State may contain messages from previous turns.

10. Can after_agent handle model call failures?

No, it should not be treated as a general exception-catching mechanism. Model request exceptions should be handled through the corresponding wrapper middleware or higher-level error handling.

11. When should you use before_model instead of before_agent?

Use before_model when the logic needs to run before every model call, rather than only at the start of the entire Agent.

12. When should you use after_model instead of after_agent?

Use after_model when you need to review every model response, check tool calls, or process state within the execution loop.


Summary

@before_agent and @after_agent are two important hooks in the LangChain Agent lifecycle.

This chapter introduces:

You can simply remember:

before_agent:

    Agent 开始之前

    输入预处理、初始化、访问检查



after_agent:

    Agent 正常完成之后

    结果格式化、统计、结束日志

Core principles:Put Agent-level preparation in before_agent and final processing in after_agent; for logic that must run on every model call, use before_model and after_model. Critical tasks such as permission validation and resource management cannot rely solely on the Middleware lifecycle.