LangChain Error Handling and Debugging |
\n\nIn Agent development, encountering various errors is inevitable. This article summarizes common error types, debugging methods, and best practices.
\n\n\n\n
Common Error Types
\n\n| Error Type | \nTypical Causes | \nSolutions | \n
|---|---|---|
| ImportError | \nProvider package not installed | \npip install langchain-deepseek etc. | \n
| API Key Error | \n.env not configured or key invalid | \nCheck environment variables and key validity | \n
| Timeout Error | \nNetwork issues or slow model response | \nSet timeout parameter | \n
| Token Limit Exceeded | \nMessage history too long | \nUse trim_messages() to trim | \n
| Tool Call Error | \nInternal exception in tool | \nUse ToolException + handle_tool_errors | \n
| Model Output Format Error | \nModel output does not match expectations | \nUse structured output + handle_errors | \n
\n\n
ModelRetryMiddleware ββ Model Call Retry
\n\nLangChain provides a built-in retry middleware:
\n\nExample
\n\nfrom langchain.agents.middleware import ModelRetryMiddleware\n\nfrom langchain.agents import create_agent\n\nfrom langchain.chat_models import init_chat_model\n\n# Built-in model retry middleware\n# Automatically retries when model calls fail\n\nagent = create_agent(\n model=init_chat_model("deepseek:deepseek-v4-flash", timeout=30, max_retries=2),\n middleware=[\n ModelRetryMiddleware(\n max_retries=3, # Retry up to 3 times\n backoff_factor=2.0, # Backoff factor (2s, 4s, 8s)\n ),\n ],\n system_prompt="You are an assistant for TUTORIAL, the.",\n)\n\n\nToolRetryMiddleware ββ Tool Call Retry
\n\nExample
\n\nfrom langchain.agents.middleware import ToolRetryMiddleware\n\nagent = create_agent(\n model="deepseek:deepseek-v4-flash",\n tools=,\n middleware=[\n ToolRetryMiddleware(\n max_retries=3,\n backoff_factor=1.5,\n ),\n ],\n)\n\n\n\n\n\nBuilt-in
\nRetryMiddlewareand custom@wrap_model_call/@wrap_tool_calldecorators can coexist. Place built-in middleware at the front of themiddlewarelist for outermost-layer protection.
\n\n
debug=True ββ Verbose Logging
\n\nExample
\n\nfrom langchain.agents import create_agent\nfrom langchain.chat_models import init_chat_model\nfrom langchain.messages import HumanMessage\n\n# Enable debug mode to output detailed execution logs\nagent = create_agent(\n model=init_chat_model("deepseek:deepseek-v4-flash"),\n debug=True, # Enable debug logging\n system_prompt="You are an assistant for TUTORIAL, the.",\n)\n\n# Execution will print:\n# - Input state of each node\n# - Output state of each node\n# - Edge (jump) decision logic\n\nresult = agent.invoke({\n "messages": [HumanMessage(content="Hello")]\n})\n\n\nSample output with debug=True:
Starting graph execution\n Executing node: model\n Node 'model' input: {'messages': [HumanMessage(content='Hello')]}\n Node 'model' output: {'messages': [AIMessage(content='HelloοΌ...')]}\n Edge 'model' -> '__end__': routing to __end__\n Graph execution complete\n\n\n\n\n
stream_mode="debug" ββ Most Detailed Debugging Information
\n\nExample
\n\n# Obtain the most detailed information via stream_mode="debug"\nfor event in agent.stream(\n {"messages": [HumanMessage(content="Hello")]},\n stream_mode="debug",\n):\n # event contains: node name, input, output, timestamp, task info, etc.\n print(f"[{event['type']}] {event.get('name', '')}")\n if 'input' in event:\n print(f" Input: {event['input']}")\n if 'output' in event:\n print(f" Output: {event['output']}")\n\n\n\n\n
Common Troubleshooting
\n\nIssue 1: Model keeps calling tools indefinitely
\n\nPossible cause: Tool returns insufficient information, preventing the model from determining whether the task is complete.
\n\nSolutions:
\n- \n
- Make tools return clearer information (e.g., "Task completed") \n
- Set stopping conditions in
system_prompt\n - Use
after_modelto check loop count andjump_to="end"after exceeding threshold \n
Issue 2: Model calls wrong tool or incorrect parameters
\n\nPossible cause: Tool description is unclear.
\n\nSolutions:
\n- \n
- Improve the docstring of the tool function \n
- Use
args_schemato restrict parameter range \n - Use a better model (e.g.,
deepseek-v4-proinstead ofdeepseek-v4-flash) \n
Issue 3: Conversation memory not working
\n\nChecklist:
\n- \n
- Is the
checkpointerparameter passed in? \n - Is the same
thread_idused each time? \n - If using
SqliteSaver>, is the database file present and writable?</li>\n
YouTip