LangChain Error Handling and Debugging
When developing a LangChain Agent, the program cannot always run normally.
For example, model API request timeouts, incorrect tool parameters, knowledge base retrieval failures, Token overruns, or the Agent repeatedly calling the same tool can all cause program exceptions.
If a reasonable error handling mechanism is lacking, a common network failure can interrupt the entire task; and a misconfigured retry mechanism can cause the Agent to repeatedly send emails, create orders, or execute payments.
Therefore, building a reliable Agent requires not only enabling the model to complete tasks, but also considering error classification, exception catching, automatic retry, execution limits, log debugging, and fault recovery.
This section is based on LangChain 1.x and introduces common error troubleshooting, ModelRetryMiddleware, ToolRetryMiddleware, ToolErrorMiddleware, Debug mode, Streaming debugging, and production best practices.
I. Common LangChain Error Types
Agent runtime errors can be divided into the following categories:
| Error types | Typical causes | Handling suggestions |
|---|---|---|
| ImportError | Missing dependencies, version incompatibility, incorrect import paths | Check the installation environment and current API |
| AuthenticationError | API Key missing, incorrect, or expired | Check credentials and model service permissions |
| RateLimitError | Request rate or service quota limited | Rate limiting, backoff retry, check quota |
| TimeoutError | Network or model response timeout | Set a timeout and retry selectively |
| Context Length Error | Context exceeds the model limit | Reduce history messages or summarize the context |
| ValidationError | Tool parameters or structured output do not conform to the Schema | Check parameters and the data model |
| Tool Execution Error | Tool internal code or external service exceptions | Classify exceptions and handle failed results |
| GraphRecursionError | Agent execution steps exceed the graph recursion limit | Check the loop logic and limit the number of calls |
| Checkpoint Error | Thread ID, database connection, or state recovery exceptions | Check the Checkpointer and thread_id |
Different types of errors should use different handling strategies.
For example:
- Network timeout: you can retry when conditions are met.
- API Key error: credentials should be fixed immediately.
- Tool parameter error: parameters should be re-validated.
- Order creation failure: you must first confirm whether the order was actually created, and cannot simply call again.
**Core principle:** Not all exceptions should be retried. First determine whether the error can be resolved by calling again, and whether repeated execution is safe.
II. Environment Preparation
This tutorial uses LangChain 1.x and the DeepSeek chat model.
Install dependencies
pip install -U langchain langgraph langchain-deepseek python-dotenv pydantic
creation .env File:
DEEPSEEK_API_KEY=your_deepseek_api_key
Load in Python:
Example
import
os
from
dotenv
import
load_dotenv
load_dotenv
(
)
if
not
os
.
getenv
(
"DEEPSEEK_API_KEY"
)
:
raise
RuntimeError
(
"DEEPSEEK_API_KEY is missing, please check the .env file"
)
It is recommended to always install dependencies in the current project's virtual environment, to avoid version inconsistencies between system Python and the virtual environment.
III. ImportError: Import Failure
LangChain 1.x splits different features into multiple Python packages.
For example, the DeepSeek model uses:
from langchain_deepseek import ChatDeepSeek
If only installed langchain, but not installed langchain-deepseek, you may see:
ModuleNotFoundError: No module named 'langchain_deepseek'
Solution:
python -m pip install -U langchain-deepseek
Check the installed version
Example
from
importlib.
metadata
import
version
packages
=
[
"langchain"
,
"langgraph"
,
"langchain-deepseek"
]
for
package
in
packages:
try
:
(
package
,
version
(
package
)
)
except
Exception
as
e:
(
package
,
"Check failed:"
,
e
)
Note that after upgrading the LangChain version, the import paths of some older tutorials may have changed.
It is recommended to first check the official API for the corresponding version, rather than continuing to use the old AgentExecutor, the old Chain, or migrated import methods.
IV. API Key and Authentication Errors
If the model service returns an authentication error, common causes include:
- The .env file does not exist or was not loaded successfully.
- API Key spelling error.
- Credentials have expired or been revoked.
- The current Key has no permission to access the specified model.
- An incorrect service provider API address was configured.
You can first check whether the environment variable exists:
Example
import
os
from
dotenv
import
load_dotenv
load_dotenv
(
)
key
=
os
.
getenv
(
"DEEPSEEK_API_KEY"
)
(
"Does the API Key exist:"
,
bool
(
key
)
)
Do not output the full API Key directly, and do not write the Key into program logs.
**Note:** Authentication failures are usually not temporary network faults and should not be subject to a large number of automatic retries. You should first check credentials, the account, and model access permissions.
V. Model Timeout and Automatic Retry
When calling a large language model, you may encounter network jitter, request timeouts, temporary service unavailability, and other issues.
LangChain provides ModelRetryMiddleware, which can perform a limited number of retries when a model call fails.
Basic handling flow:
调用模型
↓
是否成功?
├── 是 → 返回结果
│
└── 否
↓
是否属于可重试错误?
├── 否 → 立即处理失败
│
└── 是
↓
等待退避时间
↓
重新调用
↓
达到重试上限后停止
Example: ModelRetryMiddleware
Example
from
dotenv
import
load_dotenv
from
langchain.
agents
import
create_agent
from
langchain.
agents
.
middleware
import
ModelRetryMiddleware
from
langchain_deepseek
import
ChatDeepSeek
load_dotenv
(
)
model
=
ChatDeepSeek
(
model
=
"deepseek-chat"
,
temperature
=
0
,
timeout
=
30
,
max_retries
=
0
)
agent
=
create_agent
(
model
=
model
,
tools
=
[
]
,
middleware
=
[
ModelRetryMiddleware
(
max_retries
=
2
,
initial_delay
=
1.0
,
backoff_factor
=
2.0
,
max_delay
=
10.0
,
jitter
=
True
,
on_failure
=
"error"
)
]
,
system_prompt
=
"You are the programming assistant of Runoob Tutorial RUNOOB."
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Introduce Python."
}
]
}
)
(
result
[
"messages"
]
[
1
]
.
content
)
Here we use:
max_retries=2
means at most two more retries after the first call fails.
Therefore, at most the following may be executed:
首次调用
↓ 失败
第一次重试
↓ 失败
第二次重试
↓
成功或停止
A total of at most three attempts.
This example sets the model client's max_retries to 0, to avoid SDK internal retries stacking with Middleware retries, for easier teaching and troubleshooting.
**Note:** In production, adjust retry_on according to the actual model provider's error types, avoiding repeated requests for authentication, permission, and permanent parameter errors.
VI. Understanding Exponential Backoff
When a large number of clients encounter service failures at the same time, if all requests retry immediately, it can further increase pressure on the service.
Therefore, the retry middleware supports exponential backoff.
For example:
initial_delay=1.0
backoff_factor=2.0
jitter=False
When retries are allowed, the wait time is approximately:
第一次重试前:1 秒
第二次重试前:2 秒
第三次重试前:4 秒
If enabled:
jitter=True
the wait time will include random jitter, to avoid multiple clients retrying at exactly the same time.
Common retry parameters
| Parameters | Purpose |
|---|---|
max_retries |
Maximum number of additional retries after the first failure |
initial_delay |
Base delay before the first retry |
backoff_factor |
Exponential backoff multiplier |
max_delay |
Maximum single wait time |
jitter |
Whether to add random jitter |
retry_on |
Specify the exception types or predicate functions allowed for retry |
on_failure |
Handling strategy after all retries fail |
where on_failure="error" means continuing to raise the exception after retries are exhausted.
If you use on_failure="continue", model errors may be converted into an AIMessage and returned, and the application needs to distinguish error replies from normal business results.
VII. ToolRetryMiddleware: Tool Call Retry
In addition to calling the model, the Agent also calls databases, search services, and other external APIs.
For example, a course search tool may temporarily fail due to network issues.
If a tool operation can be safely repeated, you can use ToolRetryMiddleware.
Example: Retry only temporary tool failures
Example
from
langchain.
agents
import
create_agent
from
langchain.
agents
.
middleware
import
ToolRetryMiddleware
from
langchain.
tools
import
tool
from
langchain_deepseek
import
ChatDeepSeek
attempts
=
0
@
tool
def
search_course
(
keyword
:
str
)
str
:
"""Query the simulated course catalog."""
global
attempts
attempts +
=
1
Simulate a temporary failure on the first call
if
attempts
==
1
:
raise
ConnectionError
(
"Simulation: course service temporarily unavailable"
)
return
f
"Query successful: found simulated courses related to {keyword}"
agent
=
create_agent
(
model
=
ChatDeepSeek
(
model
=
"deepseek-chat"
,
max_retries
=
0
)
,
tools
=
[
search_course
]
,
middleware
=
[
ToolRetryMiddleware
(
tools
=
[
"search_course"
]
,
max_retries
=
2
,
retry_on
=
(
ConnectionError
,
TimeoutError
)
,
initial_delay
=
1.0
,
backoff_factor
=
2.0
,
jitter
=
False
,
on_failure
=
"continue"
)
]
,
system_prompt
=
"You are a course assistant. Use search_course when the user requests a course query."
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Please use the tool to search for Python courses."
}
]
}
)
(
result
[
"messages"
]
[
1
]
.
content
)
If the model calls search_course, the first tool execution will trigger a simulated ConnectionError.
The middleware can retry, and after the second call succeeds, pass the result to the model.
Here it uses retry_on Explicitly retry only the specified temporary failures.
**Note:** The global attempts counter in the example is only for single-process teaching tests and is not suitable for real concurrent services.
VIII. Which Tools Should Not Be Retried Automatically?
Not all tools are suitable for ToolRetryMiddleware.
Especially tools with external side effects, such as:
- Sending emails.
- Creating orders.
- Executing payments.
- Deletes a file.
- Modifying database records.
Suppose the order creation tool times out:
Agent → 创建订单
↓
服务端已经创建成功
↓
响应在网络中丢失
↓
Agent 认为调用失败
↓
重试
↓
创建第二个订单
Therefore, you cannot simply assume that "a tool throwing an exception means the business operation did not succeed".
For real business, priority should be given to designing:
- Idempotent request IDs.
- Unique business serial numbers.
- Execution result queries.
- Duplicate request detection.
- Necessary manual approval.
**Recommendation:** ToolRetryMiddleware should be used first for tools suitable for repeated execution, such as search and read-only queries. When operations involving payment and deletion are involved, additional idempotent protection must be designed.
IX. ToolErrorMiddleware: Handling Tool Errors
Some errors do not need to be retried, but need to be converted into tool failure information that the model can understand.
For example, the course ID entered by the user is invalid.
In this case, you can use ToolErrorMiddleware。
Example: Handling business parameter errors
Example
from
langchain.
agents
import
create_agent
from
langchain.
agents
.
middleware
import
ToolErrorMiddleware
from
langchain.
tools
import
tool
@
tool
def
get_course
(
course_id:
int
)
str
:
"""Query simulated courses by positive integer course ID."""
if
course_id
<=
0
:
raise
ValueError
(
"Course ID must be greater than 0"
)
return
f
"Mock course {course_id}: Python Basics"
def
handle_tool_error
(
exc
,
request
)
:
"""Convert the specified business exception into a tool failure message."""
if
isinstance
(
exc
,
ValueError
)
:
return
"Course ID is invalid, please use an integer greater than 0."
return
None
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
get_course
]
,
middleware
=
[
ToolErrorMiddleware
(
on_error
=
handle_tool_error
)
]
)
Only ValueError is handled here.
Other exceptions that are not explicitly handled will continue to be raised, to avoid masking real system failures.
Note that a ValueError actively raised inside a tool and the parameter binding or Pydantic validation errors that occur when the model calls the tool do not necessarily go through exactly the same processing path.
**Recommendation:** In production, handle tool input validation, business exceptions, and infrastructure failures separately, and do not simply swallow all errors with a single except Exception.
X. Combining Retry and Error Middleware
When a tool may experience both network failures and business parameter errors, Retry and Error Middleware can be used in combination.
Design idea:
工具调用
↓
ToolRetryMiddleware
↓
临时错误?
├── 是 → 有限次数重试
└── 否 → 不重试
↓
ToolErrorMiddleware
↓
转换允许公开的业务错误
↓
Agent 获得工具结果
For example:
Example
from
langchain.
agents
.
middleware
import
ToolErrorMiddleware
,
ToolRetryMiddleware
middleware
=
[
ToolErrorMiddleware
(
on_error
=
handle_tool_error
)
,
ToolRetryMiddleware
(
tools
=
[
"get_course"
]
,
max_retries
=
2
,
retry_on
=
(
ConnectionError
,
TimeoutError
)
,
on_failure
=
"error"
)
]
Here ToolErrorMiddleware is placed on the outside and ToolRetryMiddleware on the inside.
When a retryable error ultimately still fails, the exception can continue to propagate to the outer handler.
But in this example, the handle_tool_error only handles ValueError, so errors such as ConnectionError will still propagate outward.
If you need to show the user "service temporarily unavailable", you can explicitly add corresponding exception handling logic.
XI. debug=True: Enabling Agent Debug Mode
LangChain's create_agent() Supported debug=True。
Once enabled, the underlying graph execution process will output more detailed debug information, including node execution and state updates.
Example: Enabling debug mode
Example
from
langchain.
agents
import
create_agent
from
langchain_deepseek
import
ChatDeepSeek
agent
=
create_agent
(
model
=
ChatDeepSeek
(
model
=
"deepseek-chat"
,
temperature
=
0
)
,
tools
=
[
]
,
debug
=
True
,
system_prompt
=
"You are a Python programming assistant."
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Hello" (Chinese)
}
]
}
)
(
"Final answer: "
,
result
[
"messages"
]
[
1
]
.
content
)
This mode is suitable for checking the Agent's execution logic during local development.
Note that the specific format of debug output may change with LangChain and LangGraph versions.
Therefore, you should not write programs that depend on a fixed piece of debug text.
**Security reminder:** debug=True may output message content, tool parameters, and other state information; it is not recommended to enable full debugging directly in environments containing real user privacy or production credentials.
XII. stream_mode="updates": Viewing Execution Steps
If you want to view the Agent's execution steps in a structured way, you can use Streaming.
For general tool call debugging, it is recommended to start with:
stream_mode="updates"
.
It returns the corresponding state updates after the graph nodes finish executing.
Example: Viewing model and tool calls
Example
from
langchain.
agents
import
create_agent
from
langchain.
tools
import
tool
@
tool
def
search_course
(
keyword
:
str
)
str
:
"""Search for simulated programming courses."""
return
f
"Found introductory courses for {keyword}"
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
search_course
]
,
system_prompt
=
"You are a course assistant. Use search_course for course queries."
)
for
event
in
agent.
stream
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Please search for Python courses."
}
]
}
,
stream_mode
=
"updates"
)
:
for
node
,
update
in
event.
items
(
)
:
(
"Executing node:"
,
node
)
for
msg
in
update.
get
(
"messages"
,
[
]
)
:
if
msg.
type
==
"ai"
and
getattr
(
msg
,
"tool_calls"
,
[
]
)
:
(
"Tool calls:"
,
msg.
tool_calls
)
elif
msg.
type
==
"tool"
:
(
"Tool results:"
,
msg.
content
)
elif
msg.
type
==
"ai"
and
msg.
content
:
(
"Model answer:"
,
msg.
content
)
Possible node execution flow:
执行节点: model
工具调用: search_course
执行节点: tools
工具结果: 找到 Python 入门课程
执行节点: model
模型回答: 为你找到了 Python 入门课程。
This allows you to check whether the Agent actually called the tool and whether the tool returned results correctly.
XIII. stream_mode="debug": More Detailed Graph Debugging
LangGraph also supports:
stream_mode="debug"
for outputting more fine-grained execution events.
Unlike updates, debug mode is mainly used for in-depth observation of the graph execution process.
Example: Viewing Debug events
Example
for
event
in
agent.
stream
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Hello" (Chinese)
}
]
}
,
stream_mode
=
"debug"
)
:
(
"Event type:"
,
event.
get
(
"type"
)
)
(
"Time:"
,
event.
get
(
"timestamp"
)
)
(
"Step:"
,
event.
get
(
"step"
)
)
payload
=
event.
get
(
"payload"
,
{
}
)
if
isinstance
(
payload
,
dict
)
:
(
"Node:"
,
payload.
get
(
"name"
)
)
(
"Data fields:"
,
list
(
payload.
keys
(
)
)
)
(
"-"
40
)
The fields and nested structure of actual Debug events may change with LangGraph versions.
It is recommended to first print the complete event or observe its key structure, then decide how to extract fields such as input and output.
**Note:** The data volume of debug mode can be large, suitable for local troubleshooting; it is not recommended to send all events directly to ordinary users' front-end pages.
XIV. Infinite Tool Call Loops
When executing, the Agent usually repeats the following flow:
调用模型
↓
模型要求使用工具
↓
执行工具
↓
将工具结果返回模型
↓
再次调用模型
If the model always believes the task is not complete, it may repeatedly call the same tool.
For example:
search_course("Python")
↓
返回结果
↓
search_course("Python")
↓
返回结果
↓
search_course("Python")
↓
...
Common causes:
- The tool result does not indicate the actual query status.
- The model cannot understand the content returned by the tool.
- The prompt requires repeated verification.
- Tools trigger each other.
- Lack of an execution count limit.
Use ToolCallLimitMiddleware to limit tool calls
Example
from
langchain.
agents
.
middleware
import
ToolCallLimitMiddleware
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
search_course
]
,
middleware
=
[
ToolCallLimitMiddleware
(
tool_name
=
"search_course"
,
run_limit
=
3
,
exit_behavior
=
"end"
)
]
)
This example limits the number of search_course calls in a single Agent run.
When the limit is reached, the Middleware ends the relevant execution flow according to configuration, rather than looping infinitely.
**Note:** Different exit_behavior values affect the handling result after the limit is triggered; choose according to business needs, and do not treat limited calls as successful executions.
XV. Limiting the Number of Model Calls
In addition to the number of tool calls, you can also limit the number of model calls.
LangChain provides ModelCallLimitMiddleware。
Example: Limiting a single model call
Example
from
langchain.
agents
.
middleware
import
ModelCallLimitMiddleware
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
search_course
]
,
middleware
=
[
ModelCallLimitMiddleware
(
run_limit
=
5
,
exit_behavior
=
"end"
)
]
)
This allows you to set a model call upper limit for each Agent run.
But note that limiting the number of calls does not necessarily solve the root cause.
If there is a problem with the tool's returned content, you should still fix the tool output rather than relying only on the upper limit to stop the loop.
XVI. GraphRecursionError: Recursion Limit Exception
If the graph executes too many steps, you may encounter:
GraphRecursionError
You can control the recursion limit through the run configuration:
Example
from
langgraph.
errors
import
GraphRecursionError
try
:
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Query Python courses."
}
]
}
,
config
=
{
"recursion_limit"
:
20
}
)
(
result
[
"messages"
]
[
1
]
.
content
)
except
GraphRecursionError:
(
"Agent execution steps exceeded the limit, please check the loop logic."
)
Where:
recursion_limit=20
What is limited is the number of underlying graph execution steps, not equivalent to a maximum of 20 model calls.
Because a complete tool interaction may include multiple node execution steps.
**Recommendation:** Do not infinitely increase recursion_limit whenever a GraphRecursionError occurs. You should first check whether tools are being called repeatedly, whether routing conditions are correct, and whether the Agent can determine that the task is complete.
XVII. Tool Parameter Validation Errors
The model may generate incorrect tool parameters.
For example, the course tool requires:
course_id: int
but the model passes in:
{"course_id": "abc"}
a parameter validation error may occur.
You can use Pydantic to define a clear input Schema for the tool.
Example: Constraining tool parameters
Example
from
pydantic
import
BaseModel
,
Field
from
langchain.
tools
import
tool
class
CourseInput
(
BaseModel
)
:
course_id:
int
=
Field
(
gt
=
0
,
description
=
"Positive integer course ID"
)
@
tool
(
args_schema
=
CourseInput
)
def
get_course
(
course_id:
int
)
str
:
"""Query simulated courses by course ID."""
return
f
"Course {course_id}: Python Basics"
(
get_course.
invoke
(
{
"course_id"
:
100
}
)
)
This allows checking parameter types and ranges before tool execution.
For example course_id Must be an integer greater than 0.
If the parameters do not meet the requirements, the tool call may produce a validation failure message or exception; the actual handling depends on the ToolNode and the corresponding error handling configuration.
XVIII. Structured Output Errors
For tasks that require a fixed JSON or Pydantic format, the model may return content that does not conform to the Schema.
For example, we require the model to return:
{
"course_name": "Python 基础",
"difficulty": "beginner"
}
but the model omits required fields.
You can use the ToolStrategy Define structured output.
Example: Structured output validation
Example
from
typing
import
Literal
from
pydantic
import
BaseModel
,
Field
from
langchain.
agents
import
create_agent
from
langchain.
agents
.
structured_output
import
ToolStrategy
class
CourseInfo
(
BaseModel
)
:
course_name:
str
=
Field
(
description
=
"Course name"
)
difficulty: Literal
[
"beginner"
,
"intermediate"
,
"advanced"
]
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
]
,
response_format
=
ToolStrategy
(
CourseInfo
,
handle_errors
=
True
)
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Return information about the Python Basics course."
}
]
}
)
(
result
[
"structured_response"
]
)
handle_errors=True In scenarios that support structured output errors, validation feedback can be given to the model so that it can attempt to correct itself.
But it does not mean that all model failures, API timeouts, or network exceptions can be automatically fixed.
Production environments should also set an overall request time limit and return a reasonable business error when validation fails.
XIX. Token Overruns and Long Conversation Issues
After using a Checkpointer to save multi-turn history, the conversation content may continue to grow.
For example:
第 1 轮:2 条消息
第 10 轮:20 条消息
第 50 轮:100 条消息
第 100 轮:200 条消息
If all messages are sent to the model every time, it may eventually exceed the model's context window.
Handling methods include:
- Limit the length of history passed to the model.
- Summarize earlier content into a summary.
- Clear tool results that are no longer needed.
- Store long-term user preferences in the Store.
LangChain provides SummarizationMiddleware, can summarize history messages when specific conditions are met.
Example: SummarizationMiddleware
Example
from
langchain.
agents
.
middleware
import
SummarizationMiddleware
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
search_course
]
,
middleware
=
[
SummarizationMiddleware
(
model
=
"deepseek:deepseek-chat"
,
trigger
=
(
"messages"
,
20
)
,
keep
=
(
"messages"
,
8
)
)
]
)
This demonstrates a configuration that triggers summarization based on the number of messages.
Note that the number of messages is not equivalent to the number of Tokens. Formal projects can choose the trigger strategy based on the actual model's Token counting capability and context budget.
Also, you cannot simply use:
return {"messages": messages[-6:]}
and assume you can delete old messages from the Agent State, because messages usually use the add_messages reducer.
If you really need to modify persistent history, you should use a message deletion mechanism that conforms to reducer semantics, to avoid breaking the correspondence between AI tool call messages and ToolMessage.
XX. Conversation Memory Not Taking Effect
If the Agent does not remember what was discussed before, you usually need to check the Checkpointer configuration.
First confirm:
- Whether checkpointer was passed when creating the Agent.
- Whether the same thread_id is used across different turns.
- Whether the Checkpointer's connection is still valid.
- Whether the program mistakenly created a new storage instance.
- Whether there is Middleware that actively clears or summarizes history messages.
Example: Checking conversation state
Example
from
langgraph.
checkpoint
.
memory
import
InMemorySaver
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
]
,
checkpointer
=
InMemorySaver
(
)
)
config
=
{
"configurable"
:
{
"thread_id"
:
"debug-memory-001"
}
}
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"My name is Xiaoming."
}
]
}
,
config
=
config
)
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"What is my name?"
}
]
}
,
config
=
config
)
state
=
agent.
get_state
(
config
)
(
"Message count: "
,
len
(
state.
values
.
get
(
"messages"
,
[
]
)
)
)
(
"Pending nodes: "
,
state.
next
)
If two rounds of calls use the same thread_id, the second round can usually access previous messages.
**Note:** InMemorySaver only saves in the current process memory, and records are lost after a program restart. If cross-process persistence is needed, use a Checkpointer such as SQLite or PostgreSQL.
XXI. Using Python logging to Record Business Logs
In addition to LangChain's built-in Debug mode, you can also use the Python standard library logging to record business information.
Example: Configuring logging
Example
import
logging
logging
.
basicConfig
(
level
=
logging
.
INFO
,
format
=
"%(asctime)s %(levelname)s %(name)s: %(message)s"
)
logger
=
logging
.
getLogger
(
"runoob.agent"
)
def
query_course_service
(
keyword
:
str
)
str
:
logger.
info
(
"Starting course query"
)
try
:
result
=
f
"Simulated course query result: {keyword}"
logger.
info
(
"Course query complete"
)
return
result
except
Exception
:
logger.
exception
(
"Course query failed"
)
raise
(
query_course_service
(
"Python"
)
)
Compared with using print() directly, logging makes it easier to control log levels and output formats.
It is recommended to record:
- Request ID.
- Tool name.
- Call duration.
- Error category.
- Retry count.
- Whether it completed successfully.
Do not directly record the full API Key, access tokens, or unnecessary user personal information.
XXII. LangSmith: Visual Debugging
For more complex Agents, relying only on local Debug and print logs may make it difficult to fully understand the call relationships between models and tools.
You can enable LangSmith tracing.
in .env Configure in :
LANGSMITH_TRACING=true
LANGSMITH_API_KEY=your_langsmith_api_key
LANGSMITH_PROJECT=runoob-agent-debug
Then execute normally:
agent.invoke({
"messages": [{"role": "user", "content": "搜索 Python 课程。"}]
})
In LangSmith you can view traceable:
- Model requests and replies.
- Tool calls and results.
- Execution timeline.
- Error information.
- Token and related usage data.
**Note:** LangSmith may record input and output content. Production environments should set up desensitization, hiding, and access control as needed.
XXIII. Complete Example: An Agent with Retry and Execution Limits
Finally, integrate the core features of this section into a simple Agent.
include:
- Model request timeout.
- ModelRetryMiddleware。
- ToolRetryMiddleware。
- ToolErrorMiddleware。
- Model call count limit.
- Tool call count limit.
- Top-level exception catching.
Filename:agent_debug_demo.py
Complete example
import
logging
from
dotenv
import
load_dotenv
from
langchain.
agents
import
create_agent
from
langchain.
agents
.
middleware
import
(
ModelRetryMiddleware
,
ToolRetryMiddleware
,
ToolErrorMiddleware
,
ModelCallLimitMiddleware
,
ToolCallLimitMiddleware
)
from
langchain.
tools
import
tool
from
langchain_deepseek
import
ChatDeepSeek
from
langgraph.
errors
import
GraphRecursionError
load_dotenv
(
)
logging
.
basicConfig
(
level
=
logging
.
INFO
)
logger
=
logging
.
getLogger
(
"agent_debug"
)
========== 1. Tools ==========
@
tool
def
search_course
(
keyword
:
str
)
str
:
"""Query simulated courses by keyword."""
if
not
keyword
.
strip
(
)
:
raise
ValueError
(
"Search keyword cannot be empty"
)
return
f
"Found simulated courses related to {keyword}"
========== 2. Business error handling ==========
def
handle_error
(
exc
,
request
)
:
if
isinstance
(
exc
,
ValueError
)
:
return
"Query parameters are invalid, please provide a non-empty keyword."
return
None
========== 3. Create the model ==========
model
=
ChatDeepSeek
(
model
=
"deepseek-chat"
,
temperature
=
0
,
timeout
=
30
,
max_retries
=
0
)
========== 4. Create the Agent ==========
agent
=
create_agent
(
model
=
model
,
tools
=
[
search_course
]
,
middleware
=
[
ToolErrorMiddleware
(
on_error
=
handle_error
)
,
ToolRetryMiddleware
(
tools
=
[
"search_course"
]
,
retry_on
=
(
ConnectionError
,
TimeoutError
)
,
max_retries
=
2
,
on_failure
=
"error"
)
,
ModelRetryMiddleware
(
max_retries
=
2
,
initial_delay
=
1
,
backoff_factor
=
2
,
on_failure
=
"error"
)
,
ToolCallLimitMiddleware
(
tool_name
=
"search_course"
,
run_limit
=
3
,
exit_behavior
=
"end"
)
,
ModelCallLimitMiddleware
(
run_limit
=
5
,
exit_behavior
=
"end"
)
]
,
system_prompt
=
(
"You are a programming course assistant."
"Use search_course when querying courses."
"Answer only based on tool results, do not fabricate real course information."
)
)
========== 5. Calls and exception handling ==========
def
run_agent
(
question:
str
)
:
logger.
info
(
"Starting Agent request"
)
try
:
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
: question
}
]
}
,
config
=
{
"recursion_limit"
:
20
}
)
(
"Final answer: "
,
result
[
"messages"
]
[
1
]
.
content
)
logger.
info
(
"Agent execution returned"
)
except
GraphRecursionError:
logger.
error
(
"Agent exceeded the graph execution step limit"
)
(
"Request incomplete: Agent executed too many steps."
)
except
TimeoutError:
logger.
error
(
"Request timed out"
)
(
"Request incomplete: service is temporarily responding slowly."
)
except
Exception
:
logger.
exception
(
"Agent execution failed"
)
(
"Request processing failed, please check the service and logs."
)
if
name
==
"main"
:
run_agent
(
"Please query introductory Python courses."
)
This set of code provides basic fault control for the Agent.
But note that when the Middleware converts an error into an AIMessage or ToolMessage, the program may normally return a result object, which does not mean the business was successfully executed.
Therefore, in addition to checking whether an exception was thrown, formal applications also need to explicitly check the business result status.
XXIV. Production Best Practices
1. Decide whether to retry based on error type
Network errors, rate limiting, and temporary service failures can be considered for limited retries; authentication, permission, and parameter errors should usually be handled immediately.
2. Avoid duplicate side effects
Payments, order creation, email sending, and deletion operations need idempotent protection and cannot rely solely on general retry middleware.
3. Unify timeout and retry budgets
Model SDKs, Middleware, HTTP clients, and application gateways may all have their own timeout or retry mechanisms; avoid stacking multiple layers that cause requests to remain unfinished for a long time.
4. Limit Agent execution count
Use ModelCallLimitMiddleware, ToolCallLimitMiddleware, and recursion_limit to prevent infinite tool loops.
5. Preserve request tracing information
It is recommended to use request IDs to correlate model logs, tool logs, and external service logs.
6. Protect sensitive data
Debug logs and LangSmith traces may contain user messages and tool parameters. Formal environments should desensitize credentials and private information.
7. Distinguish technical errors from business failures
For example, "order does not exist" is a normal business result and should not be retried automatically; a database connection interruption is a technical exception.
8. Provide clear feedback for failed results
If a tool did not execute successfully, do not let the model claim that it has completed. When necessary, explicitly mark the status as failed or requiring manual handling.
9. Establish regression tests
Turn real encountered errors into test cases, such as tool parameter errors, API timeouts, no retrieval results, and repeated tool calls.
10. Do not rely on the model to fix all errors by itself
Business validation, database transactions, authorization control, and exception recovery should be handled by trusted code, not by relying only on the System Prompt.
XXV. Frequently Asked Questions
1. What is the difference between ModelRetryMiddleware and ToolRetryMiddleware?
The former handles model call failures, the latter handles tool execution failures.
2. Does max_retries=3 mean at most three calls?
No. It means at most three additional retries after the first call fails, so a total of at most four attempts.
3. Does backoff_factor=2 necessarily mean waiting 2, 4, 8 seconds?
No. The actual delay also depends on initial_delay, max_delay, and jitter.
4. Why do I still get an immediate error even though model retries are set?
It may be that the exception type does not meet the retry_on condition, or the error occurred outside the model call.
5. Can ToolRetryMiddleware be used to send emails?
It is not recommended to directly auto-retry email sending operations without idempotent protection, otherwise emails may be sent repeatedly.
6. Does ToolErrorMiddleware retry automatically?
No. It is mainly used to intercept specified tool errors and convert failure results.
7. What is the difference between debug=True and stream_mode="debug"?
debug=True makes graph execution output more detailed debug logs; stream_mode="debug" obtains structured Debug events through an iteration stream.
8. How can I tell whether the model called the correct tool?
You can check AIMessage.tool_calls and ToolMessage, or view the call trace through LangSmith.
9. How should GraphRecursionError be handled?
You should check for repeated tool calls, model stopping conditions, and graph routing, and set reasonable execution limits.
10. Why does the Agent always call tools repeatedly?
It may be that the tool results are unclear, the Prompt has conflicts, the routing logic is wrong, or the model cannot determine whether the task is complete.
11. Can Pydantic prevent all tool parameter errors?
No. It mainly validates data formats and field constraints, and cannot automatically guarantee that the business object corresponding to a parameter actually exists or can be accessed.
12. Can SummarizationMiddleware prevent all Token overruns?
No. It still needs to be managed in combination with model context limits, message counts, tool output lengths, and actual Token usage.
13. Why is there still no history under the same thread_id?
You need to check whether the Checkpointer is configured, whether the storage persists, and whether history messages have been cleared or overwritten.
14. Why did the Agent return a failure message without throwing an exception?
It may be that the Middleware converted the exception into an AIMessage or ToolMessage; the application should additionally check the business result.
15. Should debug=True be enabled in production?
It is usually not recommended to keep full debugging enabled for a long time; priority should be given to structured logging, sampling traces, and controllable error monitoring.
Summary
Error handling and debugging are an important part of building a reliable LangChain Agent.
This chapter introduces:
- Common issues such as ImportError, API Key, timeout, and context overruns.
ModelRetryMiddleware: Model call retry.ToolRetryMiddleware: Tool execution retry.ToolErrorMiddleware: Tool error handling.- Exponential backoff and retry count control.
debug=True: Detailed execution logs.stream_mode="updates": Observe node updates.stream_mode="debug": Inspect graph debug events.ToolCallLimitMiddleware: Limit the number of tool calls.ModelCallLimitMiddleware: Limit the number of model calls.GraphRecursionError: Troubleshoot excessive execution steps.SummarizationMiddleware: Manage long conversation history.- Python logging and LangSmith observability.
A practical error handling architecture can be summarized as:
用户请求
↓
输入验证
↓
Agent 执行
↓
模型或工具调用
↓
错误分类
|
├── 临时故障 → 有限重试
├── 参数错误 → 返回校验信息
├── 权限错误 → 立即拒绝
├── 业务失败 → 返回业务状态
└── 严重异常 → 终止并记录日志
↓
记录执行信息
↓
返回结果或失败提示
**Core principle:** A reliable Agent is not just able to retry automatically, but able to correctly judge which errors are worth retrying, which errors must be stopped immediately, and how to avoid repeatedly executing real business operations.
For formal applications, Middleware, tool parameter validation, execution count limits, structured logging, and LangSmith tracing should be combined to establish a diagnosable, recoverable, and secure error handling system.