YouTip LogoYouTip

Langchain Error Handling

LangChain Error Handling and Debugging |

\n\n

In 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\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Error TypeTypical CausesSolutions
ImportErrorProvider package not installedpip install langchain-deepseek etc.
API Key Error.env not configured or key invalidCheck environment variables and key validity
Timeout ErrorNetwork issues or slow model responseSet timeout parameter
Token Limit ExceededMessage history too longUse trim_messages() to trim
Tool Call ErrorInternal exception in toolUse ToolException + handle_tool_errors
Model Output Format ErrorModel output does not match expectationsUse structured output + handle_errors
\n\n
\n\n

ModelRetryMiddleware β€”β€” Model Call Retry

\n\n

LangChain provides a built-in retry middleware:

\n\n

Example

\n\n
from 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\n

ToolRetryMiddleware β€”β€” Tool Call Retry

\n\n

Example

\n\n
from 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

Built-in RetryMiddleware and custom @wrap_model_call / @wrap_tool_call decorators can coexist. Place built-in middleware at the front of the middleware list for outermost-layer protection.

\n
\n\n
\n\n

debug=True β€”β€” Verbose Logging

\n\n

Example

\n\n
from 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\n

Sample output with debug=True:

\n\n
 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\n

Example

\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\n

Issue 1: Model keeps calling tools indefinitely

\n\n

Possible cause: Tool returns insufficient information, preventing the model from determining whether the task is complete.

\n\n

Solutions:

\n
    \n
  • Make tools return clearer information (e.g., "Task completed")
  • \n
  • Set stopping conditions in system_prompt
  • \n
  • Use after_model to check loop count and jump_to="end" after exceeding threshold
  • \n
\n\n

Issue 2: Model calls wrong tool or incorrect parameters

\n\n

Possible cause: Tool description is unclear.

\n\n

Solutions:

\n
    \n
  • Improve the docstring of the tool function
  • \n
  • Use args_schema to restrict parameter range
  • \n
  • Use a better model (e.g., deepseek-v4-pro instead of deepseek-v4-flash)
  • \n
\n\n

Issue 3: Conversation memory not working

\n\n

Checklist:

\n
    \n
  • Is the checkpointer parameter passed in?
  • \n
  • Is the same thread_id used each time?
  • \n
  • If using SqliteSaver\n
← Langchain Agent ApiLangchain Project Personal Ass β†’