LangChain Advanced Tool Features
In the previous section, we learned how to define tools through the @tool decorator and register them with a LangChain Agent.
In real development, besides defining a tool's name, parameters, and execution logic, you need to solve several problems:
- After a tool finishes executing, can it return the result directly without calling the model again?
- How to get the unique ID of the current tool call?
- When a tool fails, how to avoid interrupting the whole Agent?
- How to have the model adjust its next action based on tool error information?
This chapter introduces four important advanced tool features:
return_direct: Control whether the Agent loop ends directly after tool execution.InjectedToolCallId: Inject the current call ID during tool execution.ToolException: Represent expected errors during tool execution.handle_tool_error: Control how a tool handles ToolException.
This tutorial uses the LangChain 1.x create_agent() API, with examples using the DeepSeek Flash model.
I. Installation and Environment Preparation
First install the dependencies:
pip install -U langchain langchain-deepseek python-dotenv
Create in the project directory .env File:
DEEPSEEK_API_KEY=your_deepseek_api_key
Read environment variables and initialize the model in Python:
Example
from
dotenv
import
load_dotenv
from
langchain.
chat_models
import
init_chat_model
load_dotenv
(
)
model
=
init_chat_model
(
"deepseek:deepseek-flash"
)
The tool examples in this chapter all use mock data and do not actually access the Runoob Tutorial database, real order systems, or weather services.
Note that the specific behavior of Tool Calling is determined jointly by the model's capabilities and the LangChain execution framework. Whether the model chooses a tool and how many tools it chooses at once are not completely fixed.
2. return_direct: Returning tool results directly
By default, after the Agent executes a tool, it sends the tool result back to the model so the model can continue answering based on the result.
The execution flow is usually as follows:
用户提问
↓
模型请求调用工具
↓
工具执行
↓
结果返回模型
↓
模型生成最终回答
For some query-type tools, the tool result itself is already a complete answer and does not necessarily need further processing by the model.
In this case, you can set:
@tool(return_direct=True)
In Agent execution frameworks that support this feature, the current Agent loop can end directly after the tool finishes executing.
1. Normal tools and return_direct tools
Example
from
langchain.
tools
import
tool
Normal tool
@
tool
def
search_normal
(
keyword
:
str
)
str
:
"""Search mock programming courses by specified keyword."""
courses
=
{
"python"
:
"Python Basics, Python Data Analysis"
,
"java"
:
"Java Fundamentals, Java Object-Oriented"
}
return
courses.
get
(
keyword
.
lower
(
)
,
"No matching simulated course found"
)
Direct-return tool
@
tool
(
return_direct
=
True
)
def
search_direct
(
keyword
:
str
)
str
:
"""Search mock courses and return the results directly."""
courses
=
{
"python"
:
"Python Basics, Python Data Analysis"
,
"java"
:
"Java Fundamentals, Java Object-Oriented"
}
return
courses.
get
(
keyword
.
lower
(
)
,
"No matching simulated course found"
)
(
"Normal tool:"
,
search_normal.
return_direct
)
(
"Direct-return tool:"
,
search_direct.
return_direct
)
Execution result:
普通工具: False
直接返回工具: True
You can check whether direct return is enabled through the tool object's return_direct attribute.
2. Comparing the two modes in an Agent
Below we create two Agents, one using a normal tool and the other using a direct-return tool.
Example
from
dotenv
import
load_dotenv
from
langchain.
agents
import
create_agent
from
langchain.
chat_models
import
init_chat_model
load_dotenv
(
)
model
=
init_chat_model
(
"deepseek:deepseek-flash"
)
Normal tool Agent
agent_normal
=
create_agent
(
model
=
model
,
tools
=
[
search_normal
]
,
system_prompt
=
(
"You are a course query assistant."
"Use the provided tool when querying courses."
"All course data is mock data."
)
)
Direct-return tool Agent
agent_direct
=
create_agent
(
model
=
model
,
tools
=
[
search_direct
]
,
system_prompt
=
(
"You are a course query assistant."
"Use the provided tool when querying courses."
"All course data is mock data."
)
)
question
=
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Please use the tool to search for python courses"
}
]
}
def
show_result
(
agent
)
:
result
=
agent.
invoke
(
question
)
for
message
in
result
[
"messages"
]
:
(
f
"[{message.type}]"
,
message.
content
)
(
"Last message type:"
,
result
[
"messages"
]
[
1
]
.
type
)
(
"Last message content:"
,
result
[
"messages"
]
[
1
]
.
content
)
(
"=== Normal tool ==="
)
show_result
(
agent_normal
)
(
"\n=== return_direct tool ==="
)
show_result
(
agent_direct
)
If the model chooses to call the corresponding tool, normal mode usually has the model process the tool result again; direct-return mode may end the current Agent loop after the tool executes.
The differences between the two are as follows:
| Mode | Processing after tool execution | Applicable scenarios |
|---|---|---|
return_direct=False |
Usually passes the tool result to the model for further processing | Requires analysis, summarization, or further tool calls |
return_direct=True |
Ends the Agent loop when direct-return conditions are met | The tool result can already be displayed directly |
3. The final message is not necessarily an AIMessage
When using a normal tool, the Agent's last message is usually generated by the model AIMessage。
But when using return_direct=True , the Agent may end directly after tool execution, so the last message may be ToolMessage。
For example:
result = agent_direct.invoke(question)
last_message = result["messages"][-1]
print(last_message.type)
print(last_message.content)
If the tool executes successfully and triggers direct return, the output may be:
tool
Python 基础、Python 数据分析
Therefore, you cannot assume that every Agent's final output must be an AIMessage.
4. Multiple tools and return_direct
For the current LangChain 1.x create_agent(), if the model generates multiple client-side tool calls in the same round, the execution framework combines the return_direct attribute of this batch of tools to decide whether to end the loop.
The current implementation requires that all executed client-side tools in this batch have return_direct=Trueset in order to end directly through this condition.
For example:
| This round's tool calls | Whether the return_direct end condition is met |
|---|---|
| Only one direct-return tool | Is |
| Both tools are return_direct=True | Is |
| One normal tool and one direct-return tool | No |
| Only normal tools | No |
**Note:** This is the execution behavior of the current create_agent() and should not be simply generalized to older versions of AgentExecutor or custom Agent frameworks.
In addition, even if a tool is set to direct return, it does not mean the tool execution necessarily succeeds. Production environments still need to check tool execution status.
If the business requires a step to be definitely executed, definitely terminated, or definitely followed by a summary, it should be explicitly orchestrated through program logic.
3. InjectedToolCallId: Injecting the tool call ID
When the model requests a tool call, each tool call usually has a unique identifier:
tool_call_id
For example:
{
"name": "log_user_action",
"args": {
"action": "查询 Python 课程"
},
"id": "call_log_001",
"type": "tool_call"
}
Sometimes a tool needs to get the ID of the current call internally, to correlate logs, tool results, or Agent state updates.
LangChain provides InjectedToolCallId, you can use a parameter annotation to have the runtime inject the corresponding tool call ID.
1. Basic Usage
Use Annotated Annotate a tool parameter:
from typing import Annotated
from langchain.tools import InjectedToolCallId
tool_call_id: Annotated[str, InjectedToolCallId]
This parameter is different from normal parameters and does not need to be generated by the model.
Example: Recording the tool call ID
Example
from
typing
import
Annotated
from
langchain.
tools
import
(
tool
,
InjectedToolCallId
)
@
tool
def
log_user_action
(
action:
str
,
tool_call_id: Annotated
[
str
,
InjectedToolCallId
]
)
str
:
"""Record a mock operation log."""
return
(
f
"Operation: {action};"
f
"Tool call ID: {tool_call_id}"
)
Manually construct a ToolCall
tool_call
=
{
"name"
:
"log_user_action"
,
"args"
:
{
"action"
:
"Query Python courses"
}
,
"id"
:
"call_log_001"
,
"type"
:
"tool_call"
}
Pass the complete ToolCall to the tool
result
=
log_user_action.
invoke
(
tool_call
)
(
"Return type:"
,
type
(
result
)
.name
)
(
"Returned content:"
,
result.
content
)
(
"Correlation ID:"
,
result.
tool_call_id
)
The execution result is similar to:
返回类型: ToolMessage
返回内容: 操作:查询 Python 课程;工具调用 ID:call_log_001
关联 ID: call_log_001
What is passed here is the complete ToolCall dictionary, which contains id。
LangChain injects based on it tool_call_id, so the tool function can get the identifier of the current call.
2. InjectedToolCallId is not a user parameter
Normal tool parameters are provided by the model, for example:
action="查询 Python 课程"
but tool_call_id belongs to runtime context.
Use InjectedToolCallId Once annotated, this field is not exposed to the model as a normal parameter.
You can view the parameters a tool exposes to the model with the following code:
print(log_user_action.tool_call_schema.model_json_schema())
Exposed parameters usually only include action, and do not require the model to fill in tool_call_id。
**Note:** The tool call ID is only the identifier of the current Tool Call and does not represent user identity, login status, or permission information.
If the business needs to identify real users, obtain identity from an authenticated application context; do not use the tool call ID in place of a user ID.
3. Applicable scenarios
InjectedToolCallId Commonly used for:
- Correlating model requests with tool execution logs.
- Tracking the execution result of a particular tool call.
- Constructing a ToolMessage corresponding to the current Tool Call.
- Updating Agent state in combination with LangGraph Command.
If a tool needs more runtime information, such as state, context, or storage objects, you can further study LangChain's ToolRuntime。
4. ToolException: Tool execution exceptions
In real development, tools do not always execute successfully.
For example:
- The queried course does not exist.
- The user provided invalid parameters.
- An external API request fails.
- No relevant record is found in the database.
For errors that may be expected during tool execution, you can use ToolException .
ToolException is a tool exception type defined by LangChain, used together with the tool error handling mechanism.
Example: Mock user information query
Example
from
langchain.
tools
import
(
tool
,
ToolException
)
@
tool
def
get_user_info
(
user_id:
int
)
str
:
"""Query a specified user's mock profile."""
if
user_id
<=
0
:
raise
ToolException
(
"User ID must be a positive integer"
)
users
=
{
1
:
"Zhang San, normal user"
,
2
:
"Li Si, normal user"
}
if
user_id
not
in
users:
raise
ToolException
(
f
"No user found with ID {user_id}"
)
return
users
[
user_id
]
Normal call
(
get_user_info.
invoke
(
{
"user_id"
:
1
}
)
)
Invalid parameters
try
:
get_user_info.
invoke
(
{
"user_id"
: -
1
}
)
except
ToolException
as
error:
(
"Tool exception:"
,
error
)
User does not exist
try
:
get_user_info.
invoke
(
{
"user_id"
:
999
}
)
except
ToolException
as
error:
(
"Tool exception:"
,
error
)
Execution result:
张三,普通用户
工具异常: 用户 ID 必须是正整数
工具异常: 未找到 ID 为 999 的用户
Here, ToolException is not handled inside the tool, so it is thrown to the caller.
We use try/except to catch the error.
ToolException and normal exceptions
| Type | Main Use |
|---|---|
ToolException |
Represents execution errors you want managed by the tool error handling mechanism |
ValueError |
Represents general Python errors such as parameter values not meeting requirements |
TimeoutError |
Represents timeout issues |
ValidationError |
Represents Pydantic input validation failures |
**Note:** Throwing ToolException does not mean the Agent will necessarily recover from the error automatically.
Whether an exception is converted into a tool result depends on the tool's own handle_tool_error settings, as well as the Agent's tool execution and middleware handling mechanisms.
5. handle_tool_error: Handling tool exceptions
handle_tool_error is a LangChain BaseTool attribute used to control how a tool handles ToolException when encountered.
The default value is:
handle_tool_error = False
That is, by default, ToolException continues to be thrown outward.
If you want the tool to convert errors into readable results, you can set:
my_tool.handle_tool_error = True
1. Setting handle_tool_error correctly
Note in particular that in the current official LangChain API,@tool the decorator does not have a handle_tool_error direct parameter for this.
Therefore, do not write:
# 错误写法:当前 @tool 不接受这个参数
@tool(handle_tool_error=True)
It is recommended to create the tool object first, then set the corresponding attribute.
Example: Converting to a tool error message
Example
from
langchain.
tools
import
(
tool
,
ToolException
)
@
tool
def
get_weather
(
city:
str
)
str
:
"""Query mock weather for a given city."""
weather_data
=
{
"Hangzhou"
:
"Sunny, 25°C"
,
"Beijing"
:
"Cloudy, 18°C"
,
"Shanghai"
:
"Light rain, 22°C"
}
if
city
not
in
weather_data:
raise
ToolException
(
f
"City not included: {city}."
"You can query Hangzhou, Beijing, and Shanghai."
)
return
(
f
"Mock weather for {city}:"
f
"{weather_data[city]}"
)
Set the tool error handling strategy
get_weather.
handle_tool_error
=
True
Input a city not included
result
=
get_weather.
invoke
(
{
"city"
:
"Northrealm"
}
)
(
result
)
Execution result:
未收录城市:北境。可查询杭州、北京和上海。
Since handle_tool_error=True, the tool will ToolException return the error text as the result, rather than continuing to throw the exception to the caller.
Here, a regular parameter dictionary is passed when calling the tool, so the result is returned as regular content.
If executed through a full ToolCall, including the tool call ID, LangChain can generate a ToolMessage。
2. Using ToolCall to view error status
Example
Reuse the already defined get_weather tool
tool_call
=
{
"name"
:
"get_weather"
,
"args"
:
{
"city"
:
"Northrealm"
}
,
"id"
:
"call_weather_001"
,
"type"
:
"tool_call"
}
result
=
get_weather.
invoke
(
tool_call
)
(
"Message type:"
,
type
(
result
)
.name
)
(
"Execution status:"
,
result.
status
)
(
"Tool results:"
,
result.
content
)
(
"Tool call ID:"
,
result.
tool_call_id
)
Execution result:
消息类型: ToolMessage
执行状态: error
工具结果: 未收录城市:北境。可查询杭州、北京和上海。
工具调用 ID: call_weather_001
status="error" indicates that an error occurred in this tool call.
It differs from a normal tool execution result; even if the error message has been converted to text, it should not be taken as proof that the business operation succeeded.
6. Four configuration methods for handle_tool_error
The tool object's handle_tool_error supports multiple configurations.
| Configure | Behavior |
|---|---|
False |
Does not handle ToolException, continues to throw it outward |
True |
Uses the error message of ToolException as the tool result |
str |
Returns a specified fixed error message |
Callable |
Calls a custom error-handling function to generate the result |
1. False: throws an exception by default
get_weather.handle_tool_error = False
When a tool raises a ToolException, it needs to be handled by the caller or the execution framework.
2. True: returns the original error message
get_weather.handle_tool_error = True
This approach is suitable for scenarios where business errors need to be understood by the model.
But if the original exception contains internal information or sensitive data, returning it directly is not recommended.
3. str: returns a fixed error message
get_weather.handle_tool_error = (
"天气查询失败,请检查城市名称。"
)
In this case, even if the internal ToolException has different error content, a specified uniform message is returned externally.
This approach is suitable for hiding internal error details.
4. Callable: custom error handling
Example
from
langchain.
tools
import
ToolException
def
handle_weather_error
(
error: ToolException
)
str
:
"""Convert the tool exception into a safe message."""
return
(
"Weather query was unsuccessful."
"Please check the city name,"
"or try querying Hangzhou, Beijing, or Shanghai."
)
get_weather.
handle_tool_error
=
(
handle_weather_error
)
result
=
get_weather.
invoke
(
{
"city"
:
"Northrealm"
}
)
(
result
)
Execution result:
天气查询未成功。请检查城市名称,或改为查询杭州、北京、上海。
Through a custom function, error content can be handled uniformly, avoiding exposing internal system information to the model.
handle_tool_error vs. handle_validation_error
It is also necessary to distinguish two error-handling attributes:
| property | Handled object |
|---|---|
handle_tool_error |
ToolException thrown during tool execution |
handle_validation_error |
Related validation errors produced when tool input Schema validation fails |
For example, if Pydantic requires user_id to be an integer, but the model passes invalid data, a validation error may be triggered before the function is executed.
At this point, one cannot assume that setting handle_tool_error=True will automatically catch all parameter validation errors.
7. The relationship between tool error handling and the Agent
When a tool is registered to create_agent() , the Agent executes the tool based on the tool call request generated by the model.
If the tool converts a ToolException into a tool result, the Agent can add this result to the message history and then hand it to the model for processing.
For example:
用户请求查询城市
↓
模型调用 get_weather
↓
工具发现城市不存在
↓
抛出 ToolException
↓
handle_tool_error 转换错误
↓
ToolMessage(status="error")
↓
模型读取错误信息
↓
向用户解释查询失败
Example: Letting the Agent handle weather query errors
Example
from
dotenv
import
load_dotenv
from
langchain.
tools
import
(
tool
,
ToolException
)
from
langchain.
agents
import
create_agent
from
langchain.
chat_models
import
init_chat_model
load_dotenv
(
)
@
tool
def
get_weather
(
city:
str
)
str
:
"""Query mock weather for a given city."""
data
=
{
"Hangzhou"
:
"Sunny, 25°C"
,
"Beijing"
:
"Cloudy, 18°C"
,
"Shanghai"
:
"Light rain, 22°C"
}
if
city
not
in
data:
raise
ToolException
(
f
"City not included: {city}."
"Currently only Hangzhou, Beijing, and Shanghai are supported."
)
return
(
f
"The simulated weather for {city} is {data[city]}"
)
Set before registering to the Agent
get_weather.
handle_tool_error
=
True
model
=
init_chat_model
(
"deepseek:deepseek-flash"
)
agent
=
create_agent
(
model
=
model
,
tools
=
[
get_weather
]
,
system_prompt
=
(
"You are a weather query assistant."
"The tool provides simulated data, not real weather."
"Use get_weather when querying the weather."
"If the tool returns an error, explain the reason,"
"do not fabricate data that is not there."
)
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Please query the simulated weather of the North."
}
]
}
)
View tool result
for
message
in
result
[
"messages"
]
:
if
message.
type
==
"tool"
:
(
"Tool name:"
,
message.
name
)
(
"Execution status:"
,
message.
status
)
(
"Tool results:"
,
message.
content
)
(
"\nAgent's final answer:"
)
(
result
[
"messages"
]
[
1
]
.
content
)
If the model calls get_weather, the tool returns an error message for cities not included.
When tool errors are handled correctly, the Agent can continue calling the model to generate an answer like:
目前没有收录“北境”的模拟天气数据。
支持查询的城市有杭州、北京和上海。
**Note:** Whether the model calls the tool, and how it organizes the final response, is not completely deterministic.
In addition, if you need to uniformly control error handling for all tools of the Agent, you can use LangChain's tool execution middleware instead of repeatedly writing exception-handling logic for each tool.
Cannot use with_config() to modify tool error policy
For example, the following is not the correct way to configure tool error handling:
# 不推荐:不能据此修改 BaseTool 的错误处理属性
my_tool.with_config(
handle_tool_errors=True
)
with_config() is a general runtime configuration mechanism for Runnable, and does not automatically convert handle_tool_errors into the tool's own handle_tool_error attribute.
Two names need to be distinguished here:
handle_tool_error: an attribute of a single BaseTool, singular.handle_tool_errors: the error-handling configuration name of LangGraph ToolNode, plural.
If you use create_agent(), it is recommended to prefer using tool object attributes or Agent middleware to handle errors, rather than relying on unsupported parameter-passing methods.
8. Complete example: Course registration Agent with exception handling
The following implements a course registration Agent, demonstrating how to ToolException and handle_tool_error in combination.
Here, Python dictionaries are used to simulate user and course information; all registration results are stored only in program memory, and no real orders are created or actual website data modified.
The complete execution flow is as follows:
用户提出登记请求
↓
Agent 选择 register_course
↓
检查用户是否存在
↓
检查课程是否存在
↓
验证是否重复登记
↓
成功则写入模拟记录
↓
失败则返回工具错误
↓
Agent 整理最终回答
Complete code
Filename:tool_advanced_demo.py
Complete example
File: tool_advanced_demo.py
from
dotenv
import
load_dotenv
from
langchain.
tools
import
(
tool
,
ToolException
)
from
langchain.
agents
import
create_agent
from
langchain.
chat_models
import
init_chat_model
load_dotenv
(
)
Simulated user data
USERS
=
{
"Zhang San"
,
"Li Si"
,
"Wang Wu"
}
Mock Course Data
COURSES
=
{
"Python3 Basic Tutorial"
,
"HTML Basics Tutorial"
,
"Java Object-Oriented"
}
Simulated registration records in memory
REGISTRATIONS
=
set
(
)
-------------------------
Define tools
-------------------------
@
tool
def
register_course
(
user_name:
str
,
course_name:
str
)
str
:
"""Register a simulated course for a specified user.
Args:
user_name: the user's name.
course_name: the course name.
"""
Check user
if
user_name
not
in
USERS:
raise
ToolException
(
f
"User does not exist: {user_name}"
)
Check course
if
course_name
not
in
COURSES:
raise
ToolException
(
f
"Course does not exist: {course_name}"
)
record
=
(
user_name
,
course_name
)
Prevent duplicate registration
if
record
in
REGISTRATIONS:
raise
ToolException
(
"This user has already registered for this course"
)
Write to in-memory simulated record
REGISTRATIONS.
add
(
record
)
return
(
f
"Simulated registration successful:"
f
"{user_name} - {course_name}"
)
Configure exception handling for a single tool
register_course.
handle_tool_error
=
(
"Course registration was not completed."
"Please check the user, course name, or duplicate registration."
)
-------------------------
Creating the Agent
-------------------------
model
=
init_chat_model
(
"deepseek:deepseek-flash"
)
agent
=
create_agent
(
model
=
model
,
tools
=
[
register_course
]
,
system_prompt
=
(
"You are a course registration assistant."
"This is a teaching simulation system, not a real order system."
"Only when the user explicitly requests registration,"
"may register_course be used."
"Do not claim that a real order or payment has been made."
"If the tool returns an error,"
"state that the registration was not successful."
)
)
-------------------------
Run and Debug
-------------------------
def
ask
(
question:
str
)
:
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
: question
}
]
}
,
config
=
{
"recursion_limit"
:
12
}
)
(
"\nQuestion:"
,
question
)
for
message
in
result
[
"messages"
]
:
View the tool call initiated by the model
if
(
message.
type
==
"ai"
and
message.
tool_calls
)
:
for
call
in
message.
tool_calls
:
(
"[Tool request]"
,
call
[
"name"
]
,
call
[
"args"
]
)
View tool execution result
elif
message.
type
==
"tool"
:
(
"[Tool result]"
,
message.
name
,
message.
status
,
message.
content
)
(
"Final answer: "
,
result
[
"messages"
]
[
1
]
.
content
)
if
name
==
"main"
:
Normal registration
ask
(
"Please register for Zhang San in the simulated system"
"Python3 Basic Tutorial."
)
User does not exist
ask
(
"Please register for Zhao Liu in the simulated system"
"Python3 Basic Tutorial."
)
Duplicate registration
ask
(
"Please register for Zhang San again"
"Python3 Basic Tutorial."
)
View simulated records
(
"\nSimulated registration records:"
)
(
REGISTRATIONS
)
Explanation of the results
If the model calls the tool correctly, the first registration will succeed:
模拟登记成功:张三 - Python3 基础教程
In the second request, the user 赵六 is not in the simulated user list, so the tool throws a ToolException.
Since the tool has handle_tool_errorset, the exception is converted into a tool error response:
课程登记未完成。请检查用户、课程名称或重复登记情况。
In the third request, since Zhang San has already registered for the same course, the tool also returns an error.
The final simulated registration set normally contains only one record:
{('张三', 'Python3 基础教程')}
However, the model's actual tool selection and number of calls are not strictly fixed. If the model does not call the tool, or generates different parameters, the execution result will change accordingly.
Why use a fixed error message here?
The tool above uses:
register_course.handle_tool_error = (
"课程登记未完成。"
"请检查用户、课程名称或重复登记情况。"
)
This avoids handing internal error details directly to the model or user.
If you need the Agent to know the specific reason for failure, you can change it to:
register_course.handle_tool_error = True
In this case, the tool returns the error content of the ToolException.
Actual business systems need to choose an appropriate error-message method based on security requirements.
**Important:** Tools with side effects such as registration, payment, and file deletion cannot rely solely on model judgment to ensure correct execution. Production environments also require authentication, authorization, parameter validation, idempotent handling, and necessary manual confirmation.
9. Notes on return_direct and error handling
A tool can be configured with both direct return and error handling.
For example:
@tool(return_direct=True)
def lookup_course(course_name: str) -> str:
"""查询指定模拟课程。"""
if course_name != "Python3 基础教程":
raise ToolException("课程不存在")
return "课程:Python3 基础教程"
lookup_course.handle_tool_error = True
But it is important to understand that the two options control different behaviors.
| Configure | Controlled issue |
|---|---|
return_direct |
Whether to end the Agent loop via the direct-return condition after tool execution |
handle_tool_error |
Whether ToolException is converted into a tool result |
One thing to note in particular:A tool producing an error response does not mean the Agent will necessarily continue trying to fix it.
In some LangChain versions or execution paths,return_direct=True a tool with this setting may still meet the direct-end condition even if it returns an error ToolMessage.
Therefore, if the business wants the model to reselect parameters or tools after a tool failure, it is recommended not to set this option on that tool return_direct=True, or to explicitly control the Agent's error-recovery flow.
10. Frequently asked questions
1. Does return_direct=True guarantee that the tool will be executed?
Not guaranteed.
It only controls the return behavior after the tool is executed; it does not force the model to select the tool.
If the business must execute a certain tool, it should be controlled through a program call or an explicit workflow.
2. Why is the last message a ToolMessage after return_direct=True?
Because the Agent may end directly after tool execution, without calling the model again to generate a new AIMessage.
Therefore, when reading the result, you can check the message type:
result = agent.invoke(inputs)
last = result["messages"][-1]
print(last.type)
print(last.content)
3. Is InjectedToolCallId a user ID?
No.
It is the identifier of the current tool call, mainly used to associate the request with the tool execution result.
The real user identity should be obtained from a trusted authentication context.
4. Why does using @tool(handle_tool_error=True) cause an error?
Because the current official @tool decorator does not accept handle_tool_error as a direct parameter.
Define the tool first:
@tool
def my_tool(value: str) -> str:
"""测试工具。"""
return value
Then set:
my_tool.handle_tool_error = True
5. Is ToolException automatically caught by the Agent?
Not necessarily.
The tool's own error policy, execution nodes, and Agent middleware can all affect the final behavior.
It is recommended to explicitly configure tool error handling rather than relying on default exception fallback.
6. Can handle_tool_error handle all Python exceptions?
No.
It mainly handles ToolException。
common program exceptions, input parameter validation errors, and model API errors; they need to be handled separately based on the actual type and execution layer.
7. What does ToolMessage's status="error" indicate?
It indicates that this tool call produced an error result.
Even if the tool error is converted to text and returned, it does not mean the business operation succeeded.
Actual programs can use status to distinguish success from failure.
8. Why can't with_config() be used to configure handle_tool_errors?
Because with_config() is used to set the runtime configuration of a Runnable, and does not automatically modify the error-handling attributes of the tool object or ToolNode.
ToolException handling for a single tool should be done through the handle_tool_error attribute.
9. What is the difference between ToolException and parameter validation errors?
ToolException are usually business errors actively thrown when the tool function is executed.
Parameter validation errors may occur before the tool function is actually executed, for example when the model provides parameters that do not conform to the Pydantic Schema.
These two types of errors are not necessarily handled by the same error-handling configuration.
10. Is it recommended to pass all exceptions directly to the model?
No, it is not recommended.
Database connection information, file system paths, internal service addresses, and exception stack traces may contain sensitive information.
Production environments should write internal errors to trusted logs and return only filtered, necessary information to the model.
Summary
LangChain's advanced tool features are mainly used to control the Agent's execution flow and exception handling.
| Function | Core Role |
|---|---|
return_direct |
Controls whether a tool result can directly end the Agent loop |
InjectedToolCallId |
Injects the current tool call ID |
ToolException |
Represents an error during tool execution |
handle_tool_error |
Determines how to handle ToolException thrown by the tool |
In actual development, it is important to distinguish three concepts:
- **The model's decision:** whether to call the tool and what parameters to pass.
- **The tool's execution:** actually running the Python code and returning a result or error.
- **The Agent's orchestration:** deciding whether to hand the tool result back to the model, continue the loop, or end the task.
For simple query tools, you can consider using return_direct=True, reducing unnecessary model calls.
For tools that need error recovery, you can use ToolException together with handle_tool_error, so that errors are returned as structured tool results.
For tools involving real users, databases, orders, or payments, permission control, data validation, and operation confirmation also need to be implemented in the application; one cannot rely solely on the Agent's natural-language judgment.