LangChain Model Call Interception — @wrap_model_call
@wrap_model_call is an important model call interception mechanism in LangChain Middleware.
The difference between @before_model and @after_model in Vue 2,@wrap_model_call It can directly wrap model calls, controlling how model requests are executed through custom logic.
For example, you can check the request before calling the model, retry on execution failure, switch to a backup model, read the cache, or directly return a preset result under certain conditions.
This chapter is based on LangChain 1.x and introduces handler callbacks, ModelRequest, ModelResponse, request modification, model retry, failover, caching, and the combination of multiple middleware.
1. What is @wrap_model_call?
@wrap_model_call It belongs to LangChain's Wrap-style Middleware.
It intercepts model requests and responses by wrapping the model execution process.
Basic flow:
Agent 准备调用模型
↓
wrap_model_call
↓
检查或修改 ModelRequest
↓
handler(request)
↓
模型执行
↓
ModelResponse
↓
修改或记录执行结果
↓
返回 Agent
Wherehandler is the key.
called handler(request) will continue to execute the wrapped model request; if the handler is not called, you can directly return a result as long as the protocol is satisfied.
Basic Syntax
Example
from
langchain.
agents
.
middleware
import
wrap_model_call
,
ModelRequest
,
ModelResponse
@
wrap_model_call
def
my_middleware
(
request: ModelRequest
,
handler
)
ModelResponse:
"""Execute custom logic before and after the model call."""
(
"The model is about to be called"
)
response
=
handler
(
request
)
(
"Model call completed"
)
return
response
Unlike Node-style Middleware, here you cannot directly return an ordinary State dictionary in place of the model response.
If you need to modify the Agent State, you should use the corresponding state update mechanism.
2. Understanding ModelRequest and ModelResponse
wrap_model_call the two most important objects are:
ModelRequest: the request currently about to be sent to the model.ModelResponse: the messages and structured result returned after the model executes.
Common ModelRequest Attributes
| property | Description |
|---|---|
request.model |
The current model object |
request.messages |
The list of messages for this model request |
request.system_message |
The current system message object |
request.tools |
The tool definitions available for this request |
request.state |
The Agent's current state |
request.runtime |
Runtime context |
request.response_format |
The current structured output configuration |
Whererequest.messages is the message currently about to be submitted to the model, not necessarily equivalent to the complete Agent history state.
Common ModelResponse Attributes
| property | Description |
|---|---|
response.result |
The message list of the model response |
response.structured_response |
Optional structured output result |
For example, you can through:
response = handler(request)
for message in response.result:
print(message.content)
to read the messages returned by the model.
Note:handler(request) usually returns a ModelResponse rather than directly returning an AIMessage, so it cannot be used in all scenarios with response.content。
3. Scenario One: Recording Model Call Duration
The simplest application is recording model execution time.
You can use Python's time.perf_counter() to measure the duration of each call.
Example
Example
import
time
from
dotenv
import
load_dotenv
from
langchain.
agents
import
create_agent
from
langchain.
agents
.
middleware
import
wrap_model_call
,
ModelRequest
,
ModelResponse
load_dotenv
(
)
@
wrap_model_call
def
log_model_time
(
request: ModelRequest
,
handler
)
ModelResponse:
"""Record the model call duration."""
start
=
time
.
perf_counter
(
)
try
:
return
handler
(
request
)
finally
:
(
f
"[Model] Elapsed: {time.perf_counter() - start:.2f} seconds"
)
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
]
,
middleware
=
[
log_model_time
]
,
system_prompt
=
"You are the programming assistant of Runoob Tutorial RUNOOB."
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"What is Python?"
}
]
}
)
(
result
[
"messages"
]
[
1
]
.
content
)
Execution may output:
[Model] 耗时:1.82 秒
Python 是一种通用编程语言,语法简洁易读。
Here, the following is used finally, the time already consumed can be recorded even if the model call throws an exception.
However, if the model execution fails, the program will still throw the original exception and will not automatically generate a successful result.
4. Scenario Two: Retrying After a Model Call Fails
The model API may fail due to network interruption, request timeout, or temporary server failure.
For temporary errors suitable for retrying, you can use wrap_model_call to call the handler multiple times.
Example: Limiting the Number of Retries
Example
import
time
from
langchain.
agents
.
middleware
import
wrap_model_call
,
ModelRequest
,
ModelResponse
@
wrap_model_call
def
retry_on_timeout
(
request: ModelRequest
,
handler
)
ModelResponse:
"""When a standard timeout exception occurs, try up to three times."""
for
attempt
in
range
(
3
)
:
try
:
return
handler
(
request
)
except
TimeoutError:
if
attempt
==
2
:
raise
wait
=
2
** attempt
(
f
"Model timed out, retrying in {wait} seconds"
)
time
.
sleep
(
wait
)
Here, the handler is called at most three times, with wait times of 1 second and 2 seconds respectively.
Note that the actual model SDK's timeout exception is not necessarily Python's built-in TimeoutError.
Production environments should handle according to the specific model provider's exception types, and distinguish:
- Network timeouts, temporary server errors: usually can be retried a limited number of times.
- Rate limiting errors: should be combined with Retry-After or a backoff strategy.
- Invalid API Key, incorrect request parameters: usually should not be retried.
- Content or permission restrictions: cannot be simply bypassed through retries.
In addition, repeated model calls will increase the number of requests and costs.
Recommendation: Use the Built-in ModelRetryMiddleware
LangChain already provides ModelRetryMiddleware, so there is usually no need to implement retry and backoff mechanisms yourself.
Example
from
langchain.
agents
import
create_agent
from
langchain.
agents
.
middleware
import
ModelRetryMiddleware
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
]
,
middleware
=
[
ModelRetryMiddleware
(
max_retries
=
2
)
]
,
system_prompt
=
"You are a Chinese programming assistant."
)
Here max_retries=2 indicates that additional retries are allowed, and the specific number of executions is also affected by the exception handling configuration.
**Note:** the model integration itself may also configure a retry count. You should check the combined effect of the two layers of retries to avoid far more API requests than expected.
5. Scenario Three: Model Downgrade and Failover
If the primary model is unavailable, you can switch to a backup model.
This mechanism is called Fallback.
For example, after the primary model fails due to a temporary error, you can try using another model service.
Note that the backup model should be a genuinely different model or deployment, not simply re-initializing the same model.
Example: Switching Models via request.override()
Example
from
langchain.
agents
import
create_agent
from
langchain.
chat_models
import
init_chat_model
from
langchain.
agents
.
middleware
import
wrap_model_call
,
ModelRequest
,
ModelResponse
primary_model
=
init_chat_model
(
"deepseek:deepseek-flash"
)
fallback_model
=
init_chat_model
(
"openai:gpt-4o-mini"
)
@
wrap_model_call
def
fallback_on_error
(
request: ModelRequest
,
handler
)
ModelResponse:
"""Try a backup model when the primary model throws an exception."""
try
:
return
handler
(
request
)
except
Exception
as
error:
(
"[Fallback] Primary model failed:"
,
type
(
error
)
.name
)
return
handler
(
request.
override
(
model
=
fallback_model
)
)
agent
=
create_agent
(
model
=
primary_model
,
tools
=
[
]
,
middleware
=
[
fallback_on_error
]
)
This example requires installing both:
pip install -U langchain-deepseek langchain-openai
and configuring:
DEEPSEEK_API_KEY=your_deepseek_api_key
OPENAI_API_KEY=your_openai_api_key
After the primary model fails, the code re-executes the request using the fallback model.
If the fallback model also fails, the exception continues to propagate upward.
**Note:** The example above catches all exceptions to highlight the principle. In real projects, you should limit the exception types that can trigger failover, to avoid masking authentication errors or incorrect business configuration as ordinary service failures.
The role of request.override()
request.override() It returns a new ModelRequest and does not modify the old request in place.
For example:
new_request = request.override(model=fallback_model)
response = handler(new_request)
Besides the model, you can also modify the system message, the current message list, tool definitions, and other supported request configurations.
Recommended: Use ModelFallbackMiddleware
For common failover needs, you can use LangChain's built-in middleware.
Example
from
langchain.
agents
import
create_agent
from
langchain.
agents
.
middleware
import
ModelFallbackMiddleware
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
middleware
=
[
ModelFallbackMiddleware
(
"openai:gpt-4o-mini"
)
]
,
system_prompt
=
"You are a programming learning assistant."
)
The built-in middleware can try a fallback model after the primary model call fails.
If the primary and fallback models come from different providers, make sure both support the tool calling, structured output, and other capabilities required by the current Agent.
In addition, cross-model failover should also consider the scope of data transfer, privacy policies, and cost differences.
VI. Scenario 4: Caching Model Responses
If multiple model requests are completely identical, you can consider caching the response to reduce duplicate requests.
But caching Agent model results is more complex than caching ordinary strings.
Because model output may be affected by the following information:
- The system prompt.
- The complete message history.
- Tool definitions.
- The model name and parameters.
- Structured output configuration.
- Runtime context.
Therefore, you cannot create a cache key based only on the last user message.
Why is the original caching approach problematic?
For example:
cache_key = last_content[:200]
This approach may cause two different requests to use the same cache key.
At the same time, the fact that users send the same question does not mean the model should return the same result.
For example, under different conversation histories:
用户 A:介绍一下 Python。
用户 B:介绍一下 Python。
Two users may have different system permissions, response languages, or tool data.
If incorrect cached results are shared, it may cause data leakage or return irrelevant information.
Example: Caching Only Simple, Tool-Free Requests
Below we create an in-memory caching example suitable for teaching, handling only simple requests with a fixed model, no tools, and no structured output.
Example
import
hashlib
import
json
from
langchain.
agents
.
middleware
import
wrap_model_call
,
ModelRequest
,
ModelResponse
cache
=
{
}
@
wrap_model_call
def
cache_simple_response
(
request: ModelRequest
,
handler
)
ModelResponse:
"""Only demonstrates caching simple, tool-free model requests."""
if
request.
tools
or
request.
response_format
is
not
None
:
return
handler
(
request
)
payload
=
{
"model"
:
str
(
request.
model
)
,
"system"
:
str
(
request.
system_message
.
content
)
if
request.
system_message
else
""
,
"messages"
:
[
m.
model_dump
(
mode
=
"json"
)
for
m
in
request.
messages
]
}
key
=
hashlib.
sha256
(
json.
dumps
(
payload
,
sort_keys
=
True
,
ensure_ascii
=
False
)
.
encode
(
)
)
.
hexdigest
(
)
if
key
in
cache:
(
"[Cache hit]"
)
return
cache
[
key
]
.
model_copy
(
deep
=
True
)
response
=
handler
(
request
)
if
len
(
response.
result
)
==
1
and
response.
result
[
0
]
.
type
==
"ai"
and
not
response.
result
[
0
]
.
tool_calls
:
cache
[
key
]
=
response.
model_copy
(
deep
=
True
)
(
"[Cache write]"
)
return
response
This example constructs the cache key from the complete message content, system prompt, and model information, avoiding using only the last 200 characters.
But this is still only a teaching implementation and is not suitable for direct use as a production-grade multi-user cache.
Real projects also need to consider:
- Model parameters, API versions, and structured output configuration.
- Isolation of users, tenants, and data access.
- Cache expiration and capacity limits.
- Cache invalidation after tool data changes.
- Deduplication of concurrent requests.
- Sensitive information that may be contained in responses.
**Note:** The example above uses an in-process dictionary; the cache disappears after the program restarts, and it is not suitable for sharing across multiple processes.
If you only want to cache ordinary model call results, you can also consider LangChain's model caching mechanism instead of specifically implementing it with Middleware.
VII. Scenario 5: Modifying Model Requests
ModelRequest.override() You can not only switch models, but also modify the current request's messages, system prompt, and some model parameters.
Common needs include:
- Adjusting the prompt according to the user's level.
- Adding a description of the current task for the model.
- Adjusting model settings in special cases.
- Modifying only this model request, without directly modifying the AgentState.
Example: Dynamically Injecting Time Information
Example
from
datetime
import
datetime
from
zoneinfo
import
ZoneInfo
from
langchain.
messages
import
SystemMessage
from
langchain.
agents
.
middleware
import
wrap_model_call
,
ModelRequest
,
ModelResponse
@
wrap_model_call
def
inject_time_context
(
request: ModelRequest
,
handler
)
ModelResponse:
"""Inject Beijing time into the model."""
now
=
datetime
.
now
(
ZoneInfo
(
"Asia/Shanghai"
)
)
base
=
str
(
request.
system_message
.
content
)
if
request.
system_message
else
"You are a programming assistant."
extra
=
f
"Current Beijing time: {now:%Y-%m-%d %H:%M}."
new_request
=
request.
override
(
system_message
=
SystemMessage
(
content
=
base +
"\n"
- extra
)
)
return
handler
(
new_request
)
Here, the following is used ZoneInfo("Asia/Shanghai") Explicitly specify Beijing time.
But if you need to display time according to the user's location, you should read the time zone from trusted user settings rather than treating server time directly as the user's time.
**Note:** If you only need to dynamically adjust the System Prompt, you can prefer using the one introduced in the previous chapter @dynamic_prompt, and you do not necessarily need to write wrap_model_call directly.
VIII. Short-Circuit Return: Not Calling the Model
wrap_model_call You can choose not to execute the handler and directly return a protocol-compliant model response.
For example, when a user makes a fixed demo request, directly return a preset text.
Example: Returning a Fixed Reply
Example
from
langchain.
messages
import
AIMessage
from
langchain.
agents
.
middleware
import
wrap_model_call
,
ModelRequest
@
wrap_model_call
def
fixed_reply
(
request: ModelRequest
,
handler
)
:
"""Directly return a fixed answer for demo keywords."""
messages
=
request.
messages
if
messages
and
messages
[
1
]
.
type
==
"human"
:
if
messages
[
1
]
.
content
==
"PING_DEMO"
:
return
AIMessage
(
content
=
"PONG_DEMO"
)
return
handler
(
request
)
Since an AIMessage is returned, the Agent can process it as a model response.
This approach is suitable for simple fixed answers, testing, or short-circuiting specific requests.
But if the current request has structured output enabled or has special tool calling requirements, you cannot treat an arbitrary text AIMessage as a fully compatible result.
In addition, production environments should not use this approach to disguise real API calls or hide service failures.
IX. Combination Order of Multiple wrap_model_call
An Agent can register multiple model-wrapping middleware.
For example:
middleware=[outer_middleware, inner_middleware]
LangChain combines them in a nested wrapping manner.
The first Middleware is at the outermost layer.
Example: Observing Execution Order
Example
from
langchain.
agents
import
create_agent
from
langchain.
agents
.
middleware
import
wrap_model_call
,
ModelRequest
,
ModelResponse
@
wrap_model_call
def
outer_middleware
(
request: ModelRequest
,
handler
)
ModelResponse:
(
"[Outer] Start"
)
response
=
handler
(
request
)
(
"[Outer] End"
)
return
response
@
wrap_model_call
def
inner_middleware
(
request: ModelRequest
,
handler
)
ModelResponse:
(
" [Inner] Start"
)
response
=
handler
(
request
)
(
" [Inner] End"
)
return
response
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
]
,
middleware
=
[
outer_middleware
,
inner_middleware
]
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Hello" (Chinese)
}
]
}
)
(
result
[
"messages"
]
[
1
]
.
content
)
During normal execution, the log order is:
[外层] 开始
[内层] 开始
[内层] 结束
[外层] 结束
The execution process is similar to:
outer_middleware
↓
inner_middleware
↓
模型调用
↓
inner_middleware 返回
↓
outer_middleware 返回
If an exception occurs in a middleware and is not handled, the corresponding subsequent logs may not execute.
Therefore, when you need to always log the end event, you can use try/finally。
X. Execution Order of Caching and Retry
The order of multiple middleware affects actual behavior.
For example:
middleware=[cache_middleware, retry_middleware]
Its execution process can be understood as:
缓存检查
↓
未命中
↓
重试逻辑
↓
模型调用
↓
返回结果
↓
写入缓存
If there is a cache hit, the outer middleware can directly return the result without executing the inner retry and model call.
Conversely, if retry is placed on the outer layer, the retry may re-execute the entire inner cache processing logic.
Therefore, when designing the Middleware order, you should clarify the responsibility of each middleware.
Generally speaking:
| Function | Suitable Position | Description |
|---|---|---|
| Request validation | Toward the outer layer | Block invalid requests as early as possible |
| Cache lookup | Outside the retry logic | Can return directly on a cache hit |
| Model retry | Close to the model call | Handle actual request failures |
| Logging and monitoring | Choose according to statistical goals | The outer layer measures total elapsed time, the inner layer measures actual calls |
This is just a common organization; specifically, you also need to consider whether the cache covers fallback models, whether request parameters change, and behavioral differences between providers.
XI. Synchronous and Asynchronous wrap_model_call
The previous examples all use synchronous handler(request)。
If the application uses an asynchronous Agent, you can use @awrap_model_call to implement asynchronous model interception.
Example: Asynchronously Logging Model Call Time
Example
import
time
from
langchain.
agents
.
middleware
import
awrap_model_call
,
ModelRequest
,
ModelResponse
@
awrap_model_call
async
def
async_timer
(
request: ModelRequest
,
handler
)
ModelResponse:
"""Log the elapsed time of asynchronous model calls."""
start
=
time
.
perf_counter
(
)
try
:
return
await handler
(
request
)
finally
:
(
f
"[Async Model] Elapsed: {time.perf_counter() - start:.2f} seconds"
)
Asynchronous model calls require the use of await handler(request)。
If you implement retry waiting in asynchronous middleware, you should use:
await asyncio.sleep(seconds)
instead of time.sleep(), to avoid blocking the event loop.
**Note:** The synchronous and asynchronous hooks of middleware must match the Agent's execution mode. When using ainvoke() or astream() , make sure the relevant Middleware supports the asynchronous path.
XII. Complete Example: Model Call Monitoring and Retry
Below we combine model call elapsed time statistics and a retry mechanism to build a simple programming assistant.
Filename:wrap_model_demo.py
Install dependencies:
pip install -U langchain langgraph langchain-deepseek python-dotenv
Configure .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
wrap_model_call
,
ModelRequest
,
ModelResponse
,
ModelRetryMiddleware
load_dotenv
(
)
@
wrap_model_call
def
monitor_model
(
request: ModelRequest
,
handler
)
ModelResponse:
"""Track model execution time and results."""
start
=
time
.
perf_counter
(
)
try
:
response
=
handler
(
request
)
(
"[Model] Number of returned messages:"
,
len
(
response.
result
)
)
return
response
finally
:
(
f
"[Model] Call elapsed time: {time.perf_counter() - start:.2f} seconds"
)
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
]
,
middleware
=
[
monitor_model
,
ModelRetryMiddleware
(
max_retries
=
2
)
]
,
system_prompt
=
"You are the Chinese programming assistant of Runoob Tutorial RUNOOB, answering accurately and concisely."
)
def
ask
(
question:
str
)
:
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
: question
}
]
}
)
(
"User:"
,
question
)
(
"AI:"
,
result
[
"messages"
]
[
1
]
.
content
)
if
name
==
"main"
:
ask
(
"What is a Python decorator?"
)
ask
(
"What are the main differences between Python and Java?"
)
During execution, the following may appear:
[Model] 返回消息数: 1
[Model] 调用耗时: 1.75 秒
用户: 什么是 Python 装饰器?
AI: 装饰器是一种用于扩展函数行为的机制……
If a retryable error occurs in the model request, the inner ModelRetryMiddleware can handle it according to configuration.
Here we use:
middleware=[monitor_model, ModelRetryMiddleware(max_retries=2)]
This means the outer monitoring measures the entire execution time including inner retries, rather than the time of each individual underlying API request.
If you need to precisely measure a single API attempt, you should adjust the placement of the monitoring middleware.
13. Production environment considerations
1. Do Not Retry All Errors Unconditionally
Invalid API keys, incorrect request parameters, and permission errors should generally not be retried repeatedly.
It is recommended to handle these based on exception type, server status code, and retry limits.
2. Do Not Use Insecure Cache Keys
Caching results based only on the user's last message may cause cross-user data confusion.
Production environments should be designed with complete request semantics, user isolation, model parameters, and cache expiration in mind.
3. Fallback Models Must Be Compatible with the Current Agent
If the Agent relies on Tool Calling or structured output, the fallback model must support the corresponding capabilities.
Otherwise, even if the model API can be called, the task may not be completed.
4. Do Not Disguise Model Errors as Success
When the model service fails, if the business must obtain reliable results, you should explicitly return an error status to the application or perform a controlled degradation.
Directly returning fixed text such as 'processed successfully' may cause the upper-level program to misjudge the task status.
5. Handle Sensitive Information Carefully
Middleware can read message history and request context, and should not casually log user passwords, API keys, access tokens, or other sensitive data.
6. Monitor Actual Request Costs
Retries and model degradation may lead to additional API calls; you should monitor the number of model calls, token consumption, execution time, and error rate.
14. Frequently Asked Questions
1. What is the difference between @wrap_model_call and @before_model?
@before_model It is a node hook before the model call, mainly responsible for state checking, updating, and routing control.
@wrap_model_call It wraps the model request through a handler, suitable for retry, degradation, short-circuit return, and request modification.
2. Does handler(request) return an AIMessage?
It usually returns a ModelResponse, whose result stores the model response message.
But Middleware allows simplified return of supported model call result types such as AIMessage.
3. Can I skip calling the handler?
Yes. This way you can directly return a preset AIMessage or other protocol-compliant results.
4. Can the handler be executed multiple times?
Yes. Both retry and degradation may call the handler multiple times, but this increases the number of actual API requests.
5. Does request.override() modify the original request?
No. It returns a new ModelRequest, and the original request object remains unchanged.
6. How do I read the text of a ModelResponse?
Usually you can iterate over response.result, and read the text content of the AIMessage within it.
7. Why can't I use only the last message as the cache key?
Because model output is also affected by the system prompt, message history, tool configuration, model parameters, and user context.
8. Can the fallback model be the same as the primary model?
Technically you can repeatedly request the same model, but this is usually a retry, not true cross-model failover.
9. What is the difference between ModelRetryMiddleware and a custom retry?
ModelRetryMiddleware provides ready-made retry control. Custom retries are suitable for scenarios with special exception identification, additional monitoring, or business requirements.
10. What is the execution order of multiple wrap_model_call?
The first is at the outermost layer, and subsequent ones wrap inward in order. On return, they exit in the opposite direction.
11. Can I modify AgentState in wrap_model_call?
You can use the LangChain-supported ExtendedModelResponse and related Command update mechanisms, but you cannot simply return an ordinary state dictionary as a ModelResponse.
12. What hook should an asynchronous Agent use?
You can use the @awrap_model_calland use the await handler(request) Execute asynchronous model calls.
Summary
@wrap_model_call It is an important extension mechanism for LangChain Agents to intercept model calls.
It can be used to:
- Log model call elapsed time.
- Retry after failure.
- Switch to a fallback model when the primary model fails.
- Cache eligible model responses.
- Modify the current model request.
- Skip model calls under specific conditions.
- Combine multiple independent model execution middleware.
Basic usage:
@wrap_model_call
def my_middleware(request: ModelRequest, handler):
# Before model call
response = handler(request)
# After model call
return response
When you need to modify the model:
new_request = request.override(model=fallback_model)
response = handler(new_request)
When you need to directly return a fixed reply:
return AIMessage(content="Preset reply")
Core principles:Control model execution through the handler, modify the current request through request.override(), and pass the result to the Agent through a protocol-compliant return value. For common model retries and failover, prioritize the built-in Middleware provided by LangChain.