LangChain Tool Call Interception——@wrap_tool_call
In LangChain Agents, @wrap_tool_call is used to intercept and control the execution process of tools.
The difference between @wrap_model_call Similarly, it also uses a handler callback function, but the object it handles is not the large language model, but the tools called by the Agent.
Through this middleware, you can implement tool retries, parameter normalization, result caching, log monitoring, error handling, and custom tool responses.
This chapter is based on LangChain 1.x and introduces ToolCallRequest、request.override()、ToolMessage、Command and built-in Middleware related to tool execution.
I. What is @wrap_tool_call?
When an Agent calls a tool, it usually follows this process:
用户发送问题
↓
模型生成工具调用请求
↓
wrap_tool_call:执行前检查
↓
handler(request)
↓
执行 Python 工具
↓
ToolMessage 或 Command
↓
wrap_tool_call:结果处理
↓
返回 Agent,继续执行
Wherehandler(request) is responsible for executing the current tool call.
You can add custom logic before and after the handler, or under specific conditions skip calling the handler and directly return a protocol-compliant result.
Basic structure
Example
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
my_tool_wrapper
(
request: ToolCallRequest
,
handler
)
ToolMessage | Command:
"""Intercept a tool call."""
(
"Preparing to execute:"
,
request.
tool_call
[
"name"
]
)
result
=
handler
(
request
)
(
"Tool execution complete"
)
return
result
There are usually two types of return values here:
ToolMessage: tool execution result.Command: state updates produced by tool execution or supported graph execution control.
**Note:** You cannot directly replace these two return types with an ordinary string or arbitrary dictionary.
II. What Information Does ToolCallRequest Contain?
ToolCallRequest Describes the tool call currently about to be executed.
| property | Description |
|---|---|
request.tool_call |
Tool call information, including name, arguments, and call ID |
request.tool |
The current tool object, which may be None in some cases |
request.state |
Current Agent State |
request.runtime |
The current ToolRuntime, providing access to runtime context |
request.override() |
Generate a modified tool call request |
The most commonly used of these are:
request.tool_call["name"]
request.tool_call["args"]
request.tool_call["id"]
For example, the model is about to execute:
search_course(keyword="python")
The corresponding tool call information may be:
{
"name": "search_course",
"args": {"keyword": "python"},
"id": "call_123",
"type": "tool_call"
}
id Used to associate the tool request initiated by the model with the subsequent tool response.
Example: Viewing Tool Call Information
Example
from
langchain.
agents
.
middleware
import
wrap_tool_call
@
wrap_tool_call
def
inspect_tool
(
request
,
handler
)
:
"""Print the current tool name and argument names."""
call
=
request.
tool_call
(
"Tool:"
,
call
[
"name"
]
)
(
"Argument names:"
,
list
(
call.
get
(
"args"
,
{
}
)
)
)
(
"Call ID:"
,
call
[
"id"
]
)
return
handler
(
request
)
By default, only argument names are printed here, not the full argument values, to avoid writing sensitive data such as passwords and tokens to the log.
III. Scenario 1: Retrying After a Tool Call Fails
Tools may depend on external HTTP APIs, databases, or other services.
If an external service experiences a temporary failure, you can consider limited retries through tool middleware.
But not all errors are suitable for retry.
For example, a failed course query can be retried, but operations such as creating an order or deducting payment, without idempotency protection, repeated execution may cause serious problems.
Example: Retrying Only Specified Exceptions
Example
import
time
from
langchain.
agents
.
middleware
import
wrap_tool_call
class
TemporaryServiceError
(
Exception
)
:
"""Simulate a temporary external service failure."""
@
wrap_tool_call
def
retry_tool
(
request
,
handler
)
:
"""Execute up to three times on temporary failures."""
for
attempt
in
range
(
3
)
:
try
:
result
=
handler
(
request
)
if
isinstance
(
result
,
ToolMessage
)
and
result.
status
==
"error"
:
return
result
return
result
except
TemporaryServiceError:
if
attempt
==
2
:
raise
delay
=
2
** attempt
(
f
"Tool temporarily unavailable, retry in {delay} seconds"
)
time
.
sleep
(
delay
)
Here the tool call is executed at most three times:
第一次调用
↓ 发生 TemporaryServiceError
等待 1 秒
↓
第二次调用
↓ 发生 TemporaryServiceError
等待 2 秒
↓
第三次调用
Only when explicitly raising TemporaryServiceError will this custom retry logic be triggered.
**Note:** If the tool returns ToolMessage(status="error"), the error message is returned directly here and will not be automatically converted into an exception.
Python exceptions raised by a tool and error ToolMessages returned belong to different error-handling approaches.
IV. Complete Example: Simulating Tool Failure and Retry
Below we create a simulated course query service that fails on the first and second calls and returns a result on the third.
For ease of understanding, this uses an in-memory Python counter to simulate failures and does not connect to a real website.
Example
import
time
from
dotenv
import
load_dotenv
from
langchain.
agents
import
create_agent
from
langchain.
agents
.
middleware
import
wrap_tool_call
from
langchain.
tools
import
tool
from
langchain.
messages
import
ToolMessage
load_dotenv
(
)
class
TemporaryServiceError
(
Exception
)
:
pass
attempts
=
{
}
@
tool
def
fetch_course_data
(
course_id:
str
)
str
:
"""Query mock data for a specified course ID."""
attempts
[
course_id
]
=
attempts.
get
(
course_id
,
0
)
1
if
attempts
[
course_id
]
<
3
:
raise
TemporaryServiceError
(
"Mock course service temporarily unavailable"
)
return
f
"{course_id}: Python3 Basics Tutorial, free"
@
wrap_tool_call
def
retry_course_tool
(
request
,
handler
)
:
"""Retry only the specified course query tool."""
if
request.
tool_call
[
"name"
]
!=
"fetch_course_data"
:
return
handler
(
request
)
for
attempt
in
range
(
3
)
:
try
:
return
handler
(
request
)
except
TemporaryServiceError:
if
attempt
==
2
:
raise
(
f
"Attempt {attempt + 1} failed, preparing to retry"
)
time
.
sleep
(
0.2
)
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
fetch_course_data
]
,
middleware
=
[
retry_course_tool
]
,
system_prompt
=
"You are a course assistant. Call the tool when the user requests a course query; the data is for demonstration only."
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Please use the tool to query course python-001."
}
]
}
)
(
result
[
"messages"
]
[
1
]
.
content
)
If the model calls the tool as expected, the following may appear:
第 1 次失败,准备重试
第 2 次失败,准备重试
Python3 基础教程是一门免费的模拟课程。
Here the third tool call returned a successful result.
However, whether the model calls the tool, the final reply content, and whether other steps occur are all determined by actual execution.
**Note:** This counter is only for a single-process teaching example and is not suitable for concurrent production environments.
V. Recommended: ToolRetryMiddleware
For common tool retries, LangChain already provides ToolRetryMiddleware.
It supports:
- Specifying the maximum number of retries.
- Limiting which tools need retry.
- Specifying which exceptions need retry.
- Exponential backoff and random jitter.
- Controlling the behavior after all retries fail.
Example: Using Built-in Tool Retry
Example
from
langchain.
agents
import
create_agent
from
langchain.
agents
.
middleware
import
ToolRetryMiddleware
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
fetch_course_data
]
,
middleware
=
[
ToolRetryMiddleware
(
tools
=
[
"fetch_course_data"
]
,
max_retries
=
2
,
retry_on
=
(
TemporaryServiceError
,
)
,
on_failure
=
"error"
,
initial_delay
=
1.0
,
backoff_factor
=
2.0
)
]
)
Here, max_retries=2 means at most two additional retries; together with the first execution, that is at most three times in total.
Common parameters are as follows:
| Parameters | Description |
|---|---|
max_retries |
The number of additional retries allowed after the first execution fails |
tools |
Specify the tools to which retry should be applied |
retry_on |
Exception types or predicate functions allowed for retry |
on_failure |
After retries fail, continue returning an error message or raise an exception |
initial_delay |
Initial wait time |
backoff_factor |
Exponential backoff factor |
max_delay |
Maximum wait time |
jitter |
Whether to add random wait jitter |
on_failure Common values:
"continue": return an error ToolMessage and let the Agent continue processing."error": re-raise the exception, stopping the current execution path.
Generally, it is recommended to prioritize built-in middleware rather than reimplementing complex retry logic.
VI. Scenario 2: Modifying Tool Arguments
Sometimes the tool arguments generated by the model need to be normalized before execution.
For example, the user inputs:
杭州
杭州
杭州
This content may contain ordinary spaces, full-width spaces, or other formatting differences.
can be used via request.override(tool_call=...) Modify the arguments before the tool executes.
Example: Normalizing City Names
Example
from
langchain.
agents
.
middleware
import
wrap_tool_call
@
wrap_tool_call
def
normalize_city
(
request
,
handler
)
:
"""Normalize the city argument of the get_weather tool."""
call
=
request.
tool_call
if
call
[
"name"
]
!=
"get_weather"
:
return
handler
(
request
)
args
=
dict
(
call
[
"args"
]
)
city
=
args.
get
(
"city"
)
if
isinstance
(
city
,
str
)
:
args
[
"city"
]
=
city.
replace
(
" "
,
" "
)
.
strip
(
)
call
=
{
**call
,
"args"
: args
}
request
=
request.
override
(
tool_call
=
call
)
return
handler
(
request
)
If the model passes in:
{"city": " 杭州 "}
The arguments actually received by the tool will be normalized to:
{"city": "杭州"}
Here, request.override() It returns a new ToolCallRequest and does not directly modify the original request object.
**Note:** Argument normalization cannot replace argument validation. For sensitive parameters such as database IDs, file paths, and permission identifiers, validation must still be performed by trusted business logic.
VII. Scenario 3: Caching Tool Call Results
Some tools are relatively expensive to execute, such as reading stable technical documentation, querying static configuration, or accessing public materials that are updated infrequently.
If the tool name and arguments are the same, you can consider caching the result.
But not all tools are suitable for caching.
| Tool Type | Suitable for Caching | Description |
|---|---|---|
| Static tutorial catalog | Suitable for | Content changes infrequently |
| Public configuration query | Depends | Needs a cache expiration set |
| Real-time weather, stock prices | Caution | Data is time-sensitive |
| User private information | Caution | Must consider user isolation |
| Creating orders, sending emails | Not suitable for simple caching | These are operations with side effects |
Example: Caching a Mock Course Query
Below we cache only search_course the successful text result of the tool.
Example
import
json
from
langchain.
agents
.
middleware
import
wrap_tool_call
from
langchain.
messages
import
ToolMessage
from
langgraph.
types
import
Command
tool_cache
=
{
}
@
wrap_tool_call
def
cache_course
(
request
,
handler
)
:
"""Cache read-only course search results."""
call
=
request.
tool_call
if
call
[
"name"
]
!=
"search_course"
:
return
handler
(
request
)
key
=
json.
dumps
(
call
[
"args"
]
,
sort_keys
=
True
,
ensure_ascii
=
False
)
if
key
in
tool_cache:
(
"[Cache hit] search_course"
)
return
ToolMessage
(
content
=
tool_cache
[
key
]
,
tool_call_id
=
call
[
"id"
]
,
name
=
call
[
"name"
]
)
result
=
handler
(
request
)
if
isinstance
(
result
,
ToolMessage
)
and
result.
status
!=
"error"
and
isinstance
(
result.
content
,
str
)
:
tool_cache
[
key
]
=
result.
content
(
"[Cache write] search_course"
)
return
result
This example has several key design points:
- Cache only the specified read-only tool.
- Use normalized JSON arguments to generate the cache key.
- Cache only successful text ToolMessages.
- Do not cache Command state updates.
- On a cache hit, use the current
tool_call_idto create a new tool reply.
Why can't we directly reuse the old ToolMessage?
Because the old message is associated with a previous Tool Call ID, and a new tool request must have a corresponding new ToolMessage.
**Note:** This example uses a Python dictionary as the cache, with no expiration, capacity limit, or concurrency protection; it is only suitable for teaching.
Production environments should also consider user isolation, permissions, cache invalidation, and tool version changes.
VIII. Scenario 4: Tool Call Logging and Monitoring
@wrap_tool_call is also very suitable for recording tool execution time, execution status, and call counts.
For example, you can record:
- Which tool was called.
- Whether execution succeeded.
- Execution elapsed time.
- Whether an exception occurred.
But by default it is not recommended to log full tool arguments, because arguments may contain user privacy or authentication information.
Example: Logging Tool Elapsed Time
Example
import
time
from
langchain.
agents
.
middleware
import
wrap_tool_call
from
langchain.
messages
import
ToolMessage
@
wrap_tool_call
def
monitor_tool
(
request
,
handler
)
:
"""Log the tool name, elapsed time, and status."""
name
=
request.
tool_call
[
"name"
]
start
=
time
.
perf_counter
(
)
try
:
result
=
handler
(
request
)
status
=
"Failed"
if
isinstance
(
result
,
ToolMessage
)
and
result.
status
==
"error"
else
"Done"
(
f
"[Tool] {name}:{status},{time.perf_counter() - start:.2f}s"
)
return
result
except
Exception
:
(
f
"[Tool] {name}: exception, {time.perf_counter() - start:.2f}s"
)
raise
If the model calls the course query tool, the following may be output:
[Tool] search_course:完成,0.02s
If the tool returns ToolMessage(status="error"), the log records it as a failure.
If the tool raises an exception, it enters the except branch, and continues to propagate the exception outward.
Here, the following is used time.perf_counter(), which is more suitable for measuring code elapsed time.
IX. Scenario 5: Handling Tool Error Results
When tool execution fails, there are two common situations:
- The tool raises a Python exception.
- The tool normally returns an error result, such as 'course not found'.
The two need to be handled differently.
Case 1: Converting a Tool Exception into an Error Message
You can catch specific exceptions in the tool middleware and return ToolMessage(status="error")。
Example
from
langchain.
agents
.
middleware
import
wrap_tool_call
from
langchain.
messages
import
ToolMessage
@
wrap_tool_call
def
handle_course_error
(
request
,
handler
)
:
"""Convert a temporary course service failure into an error message."""
try
:
return
handler
(
request
)
except
TemporaryServiceError:
call
=
request.
tool_call
return
ToolMessage
(
content
=
"The course service is temporarily unavailable, please try again later."
,
tool_call_id
=
call
[
"id"
]
,
name
=
call
[
"name"
]
,
status
=
"error"
)
This way, the Agent can obtain a clear tool failure message instead of propagating the exception directly to the outermost layer.
**Note:** You should only catch exception types you explicitly intend to handle. Do not unconditionally swallow all exceptions, otherwise you may hide program bugs and important failures.
Case 2: The Tool Returns 'Not Found'
If the search tool returns:
未找到相关课程
This does not necessarily mean the tool execution failed; it may be a normal empty query result.
You can uniformly organize the message content after tool execution:
Example
from
langchain.
agents
.
middleware
import
wrap_tool_call
from
langchain.
messages
import
ToolMessage
@
wrap_tool_call
def
format_empty_result
(
request
,
handler
)
:
"""Normalize empty course search results."""
result
=
handler
(
request
)
if
request.
tool_call
[
"name"
]
!=
"search_course"
:
return
result
if
isinstance
(
result
,
ToolMessage
)
and
result.
content
==
"No relevant course found"
:
return
ToolMessage
(
content
=
"No matching results in the course catalog; you can ask the user to change keywords."
,
tool_call_id
=
request.
tool_call
[
"id"
]
,
name
=
request.
tool_call
[
"name"
]
)
return
result
Here a new ToolMessage is returned, and the Agent can then continue to generate a reply based on the tool result.
Unlike the original, we do not return:
Command(update={
"messages": [AIMessage(content="No results found")]
})
Because this does not guarantee the Agent ends directly, and may also break the tool call/response relationship that should have been provided.
X. Command: Updating AgentState Through Tools
For tools that need to modify Agent State, you can return Command。
For example, a study assistant can mark a topic as completed.
But note thatCommand It is not a general shortcut for arbitrarily skipping the Agent loop.
Example: Saving Learning Progress
Example
from
langchain.
tools
import
tool
,
ToolRuntime
from
langchain.
messages
import
ToolMessage
from
langgraph.
types
import
Command
@
tool
def
complete_topic
(
topic:
str
,
runtime: ToolRuntime
)
Command:
"""Record completed study topics."""
topics
=
list
(
runtime.
state
.
get
(
"completed_topics"
,
[
]
)
)
if
topic
not
in
topics:
topics.
append
(
topic
)
return
Command
(
update
=
{
"completed_topics"
: topics
,
"messages"
:
[
ToolMessage
(
content
=
f
"Recorded completed: {topic}"
,
tool_call_id
=
runtime.
tool_call_id
)
]
}
)
This tool submits two updates through Command:
completed_topics: the new list of study topics.messages: the ToolMessage corresponding to the current tool call.
If the tool has already returned a Command,@wrap_tool_call you should preserve its state update semantics and not casually convert it into ordinary text.
For the continue, jump, and end behaviors after tool execution, you should use control flows supported by LangGraph, rather than simply assuming that adding an AIMessage will immediately end the Agent.
XI. Built-in ToolErrorMiddleware
If you only need to convert specific tool exceptions into error messages, you do not necessarily need to write your own @wrap_tool_call。
LangChain provides ToolErrorMiddleware, used to centrally handle tool execution exceptions.
Example: Custom Exception Prompts
Example
from
langchain.
agents
.
middleware
import
ToolErrorMiddleware
def
on_tool_error
(
error:
Exception
,
request
)
str
|
None
:
"""Only handle mock course service exceptions."""
if
isinstance
(
error
,
TemporaryServiceError
)
:
return
"The course service is temporarily unavailable, please try again later."
return
None
middleware
=
ToolErrorMiddleware
(
on_error
=
on_tool_error
,
tools
=
[
"fetch_course_data"
]
)
When a string is returned here, the middleware converts the exception into a corresponding error ToolMessage.
Return None , the exception is not handled and is allowed to continue propagating.
Note that the responsibility of ToolErrorMiddleware iserror conversion, not retry。
If you need both retry and a friendly message on final failure, you can combine ToolRetryMiddleware and ToolErrorMiddleware.
XII. Combining Multiple Tool Middleware
An Agent can be configured with multiple @wrap_tool_call middleware.
They use nested wrapping, with the first middleware usually at the outermost layer.
For example:
middleware=[
monitor_tool,
cache_course,
retry_course_tool
]
The execution process is roughly:
monitor_tool
↓
cache_course
↓
缓存未命中
↓
retry_course_tool
↓
执行工具
↓
返回结果
↓
写入缓存
↓
记录耗时
↓
返回 Agent
If there is a cache hit, the inner retry and actual tool execution may be skipped directly.
Therefore, the middleware order affects the behavior of caching, retry, and monitoring.
Common Combination Recommendations
| Combination | Recommended Order | Reason |
|---|---|---|
| Monitoring + Caching | Monitoring on the outside | Measure the overall time of cache hits and misses |
| Caching + Retry | Caching on the outside | Avoid executing retry logic on a cache hit |
| Exception Conversion + Retry | Exception conversion on the outside | First allow inner retries to complete, then convert the exception finally |
| Argument Normalization + Caching | Normalization on the outside | Improve cache key consistency |
The specific order should still be tested according to business requirements.
XIII. Asynchronous Tool Call Interception
If the Agent uses ainvoke() or astream(), you can use @awrap_tool_call to write asynchronous tool middleware.
Example: Asynchronous Tool Monitoring
Example
import
time
from
langchain.
agents
.
middleware
import
awrap_tool_call
@
awrap_tool_call
async
def
async_tool_monitor
(
request
,
handler
)
:
"""Measure asynchronous tool call elapsed time."""
start
=
time
.
perf_counter
(
)
try
:
return
await handler
(
request
)
finally
:
name
=
request.
tool_call
[
"name"
]
(
f
"[Async Tool] {name}:{time.perf_counter() - start:.2f}s"
)
Asynchronous middleware needs to use:
await handler(request)
If retry waiting is needed, you should use:
await asyncio.sleep(seconds)
avoid directly using in an asynchronous event loop time.sleep()。
XIV. Complete Example: Argument Handling and Monitoring of Course Tools
Below we combine argument normalization, tool retry, and execution monitoring to create a simple course query Agent.
Filename:wrap_tool_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
import
time
from
dotenv
import
load_dotenv
from
langchain.
agents
import
create_agent
from
langchain.
agents
.
middleware
import
wrap_tool_call
,
ToolRetryMiddleware
from
langchain.
tools
import
tool
from
langchain.
messages
import
ToolMessage
load_dotenv
(
)
COURSES
=
{
"python"
:
"Python3 Basic Tutorial"
,
"java"
:
"Java Basics Tutorial"
,
"html"
:
"HTML Basics Tutorial"
}
@
tool
def
search_course
(
keyword
:
str
)
str
:
"""Query simulated courses by programming language."""
return
COURSES.
get
(
keyword
,
"No relevant course found"
)
@
wrap_tool_call
def
normalize_keyword
(
request
,
handler
)
:
"""Convert search keywords into a uniform format."""
call
=
request.
tool_call
if
call
[
"name"
]
==
"search_course"
:
args
=
dict
(
call
[
"args"
]
)
if
isinstance
(
args.
get
(
"keyword"
)
,
str
)
:
args
[
"keyword"
]
=
args
[
"keyword"
]
.
strip
(
)
.
lower
(
)
request
=
request.
override
(
tool_call
=
{
**call
,
"args"
: args
}
)
return
handler
(
request
)
@
wrap_tool_call
def
monitor_tool
(
request
,
handler
)
:
"""Monitor tool execution elapsed time."""
start
=
time
.
perf_counter
(
)
try
:
result
=
handler
(
request
)
status
=
"Failed"
if
isinstance
(
result
,
ToolMessage
)
and
result.
status
==
"error"
else
"Success"
(
f
"[Tool] {request.tool_call['name']}:{status}"
)
return
result
finally
:
(
f
"[Tool] Elapsed: {time.perf_counter() - start:.2f}s"
)
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
search_course
]
,
middleware
=
[
normalize_keyword
,
monitor_tool
,
ToolRetryMiddleware
(
tools
=
[
"search_course"
]
,
max_retries
=
2
)
]
,
system_prompt
=
"You are a course assistant. Call search_course when querying courses; the course catalog is mock data for teaching only."
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Please use the tool to query the PYTHON course."
}
]
}
)
(
"Final answer: "
,
result
[
"messages"
]
[
1
]
.
content
)
Possible run results
[Tool] search_course:成功
[Tool] 耗时:0.01s
最终回答:可以学习 Python3 基础教程。
This example demonstrates the collaboration of three middleware:
normalize_keyword: unify tool input arguments.monitor_tool: record tool execution results and elapsed time.ToolRetryMiddleware: retry when eligible tool exceptions occur.
Here the course catalog is static mock data, and no network failure actually occurs, so retries are not triggered under normal circumstances.
Whether the tool is called depends on model behavior, and the run result is for reference only.
XV. The Difference Between @wrap_tool_call and @wrap_model_call
| Comparison Item | @wrap_model_call | @wrap_tool_call |
|---|---|---|
| Interception Target | Model request | Tool execution |
| Request object | ModelRequest | ToolCallRequest |
| Main Parameters | model、messages、tools、system_message | tool_call、tool、state、runtime |
| Common return values | ModelResponse, AIMessage, etc. | ToolMessage、Command |
| Typical use | Model retry, degradation, dynamic request modification | Tool retry, argument normalization, result caching |
| Built-in retry | ModelRetryMiddleware | ToolRetryMiddleware |
You can simply remember:
@wrap_model_call:管理模型怎么调用
@wrap_tool_call:管理工具怎么执行
Both support wrapping the execution process through a handler, but the request objects and return protocols are not the same.
XVI. Production Environment Considerations
1. Do Not Blindly Retry Tools with Side Effects
Tools such as sending emails, deducting payments, creating orders, and deleting files may risk repeated execution.
If retry is necessary, use idempotency keys, transactions, or other deduplication mechanisms on a trusted backend.
2. Caching Must Consider User Isolation
User private data, order information, and permission-related queries cannot directly share a global cache.
Cache keys need to include an appropriate user or tenant scope and have a cache expiration set.
3. Tool Arguments Need Backend Validation
Tool arguments generated by the model are not necessarily reliable.
Middleware can normalize arguments, but real permission checks and business validation must be performed by trusted programs.
4. Do Not Output Sensitive Arguments in Logs
Tool arguments may contain database query conditions, access tokens, and users' personal information.
It is recommended to log the tool name, call status, and elapsed time by default, rather than full arguments.
5. Do Not Swallow All Exceptions
Tool execution exceptions may come from temporary network failures or from code bugs.
It is recommended to only catch exception types you explicitly need to handle, to avoid hindering problem diagnosis.
6. Command Must Preserve the Tool Message Protocol
If a tool updates State through Command, you should preserve the ToolMessage with the corresponding tool call ID, to avoid producing an incomplete tool call history.
17. Frequently Asked Questions
1. What is the difference between @wrap_tool_call and a regular @tool?
@tool defines tool functionality;@wrap_tool_call intercepts the tool's execution process.
2. What does handler(request) return?
It usually returns a ToolMessage; tools using state updates may also return a Command.
3. Can I skip calling the handler?
Yes. For example, on a cache hit, you can directly construct a ToolMessage corresponding to the current call ID.
4. Does request.override() modify the original request?
No. It returns a new ToolCallRequest and can modify tool call arguments or supported state fields.
5. Is ToolRetryMiddleware's max_retries the total number of executions?
No. It represents the number of additional retries allowed after the first execution.
6. Why doesn't a tool returning an error message trigger an exception retry?
Because an error state in a ToolMessage is different from a Python exception. Error-handling logic should be designed according to the specific tool behavior.
7. Can I cache a Command?
It is not recommended to simply cache and reuse a Command. It may contain state modifications, message associations, and execution control information.
8. Why create a new ToolMessage on a cache hit?
Because each tool call has its own tool_call_id, and you need to return a message corresponding to the current tool call.
9. How do I handle a tool's empty query result?
You can treat it as a normal business result and return a clear ToolMessage, letting the Agent continue answering based on the result.
10. What is the difference between ToolErrorMiddleware and ToolRetryMiddleware?
The former converts specified exceptions into error ToolMessages; the latter retries specified exceptions.
11. Is the order of multiple tool middleware important?
Yes. The first middleware is usually at the outermost layer, and the order of caching, retry, and error handling affects actual behavior.
12. What should asynchronous tool calls use?
You can use the @awrap_tool_calland use the await handler(request) Execute asynchronous tools.
Summary
@wrap_tool_call It is an important mechanism for LangChain Agents to intercept tool execution.
Through it you can achieve:
- Retry after tool execution fails.
- Tool argument normalization and request modification.
- Caching of read-only tool results.
- Tool call logging and elapsed time statistics.
- Tool exception handling and error message conversion.
- Post-processing of tool execution results.
- Combination of multiple tool Middleware.
The most basic usage:
@wrap_tool_call
def my_wrapper(request, handler):
# Perform preprocessing
result = handler(request)
# Perform post-processing
return result
When you need to modify arguments:
new_request = request.override(tool_call=new_tool_call)
result = handler(new_request)
When you need to return a cached result:
return ToolMessage(
content=cached_content,
tool_call_id=request.tool_call["id"]
)
Core principles:Let tools handle business functionality and let Middleware handle execution control. Tool retries, caching, and error handling must maintain the correct association between ToolMessages and current tool calls, and must not break the Agent's execution protocol for the sake of simpler code.